From 361ea66a329595921435c434be0626cf7ae9a97b Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 20:26:58 +0000 Subject: [PATCH] =?UTF-8?q?Console=20d'administration=20s=C3=A9par=C3=A9e,?= =?UTF-8?q?=20joignable=20seulement=20par=20Tailscale?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Site à part (admin/, build:admin → dist-admin/), jamais dans l'app publique : tableau de bord, membres (suspendre / réactiver), avis (retirer), commentaires (supprimer), journal. Motif obligatoire. Session en mémoire seulement, 1 h maximum, déconnexion après 15 min d'inactivité. - Connexion : mot de passe + code de double authentification obligatoire (jeton aal2). - Fonction Edge « admin » : secret X-Admin-Gate (ajouté par nginx sur le VPS, sinon 404), jeton aal2, liste admin.admins ; accès à la base par connexion directe. Alertes e-mail si SMTP_PASSWORD est configuré. - Schéma « admin » (20261130150000, appliqué) non exposé par l'API : admins, journal en ajout seulement (modification, suppression et vidage refusés), fonctions de la console. - nginx : admin.conf sur 127.0.0.1:8081 (CSP stricte, sans cache, noindex), relais vers la fonction avec le secret lu dans /etc/nginx/bobinoo-admin-gate.conf (hors dépôt). Publié par « tailscale serve ». - Déploiement : build de la console et copie dans chaque release. Guide : docs/admin.md. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YVo1qxKoBQCaMd7Ue8PGbe --- .gitea/workflows/deploy.yml | 2 +- .gitignore | 1 + CLAUDE.md | 4 +- admin/index.html | 15 + admin/src/App.tsx | 177 +++++++++ admin/src/api.ts | 90 +++++ admin/src/auth.ts | 65 ++++ admin/src/main.tsx | 11 + admin/src/screens.tsx | 358 ++++++++++++++++++ admin/src/styles.css | 61 +++ deploy/nginx/admin.conf | 48 +++ deploy/nginx/site.conf | 3 + deploy/release.sh | 3 + docs/admin.md | 82 ++++ docs/database.md | 7 +- package.json | 3 +- supabase/config.toml | 3 + supabase/functions/admin/index.ts | 204 ++++++++++ .../20261130150000_admin_console.sql | 219 +++++++++++ tsconfig.json | 2 +- vite.admin.config.ts | 22 ++ 21 files changed, 1372 insertions(+), 8 deletions(-) create mode 100644 admin/index.html create mode 100644 admin/src/App.tsx create mode 100644 admin/src/api.ts create mode 100644 admin/src/auth.ts create mode 100644 admin/src/main.tsx create mode 100644 admin/src/screens.tsx create mode 100644 admin/src/styles.css create mode 100644 deploy/nginx/admin.conf create mode 100644 docs/admin.md create mode 100644 supabase/functions/admin/index.ts create mode 100644 supabase/migrations/20261130150000_admin_console.sql create mode 100644 vite.admin.config.ts diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index cf8930b..2d1583b 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -35,7 +35,7 @@ jobs: env: VITE_SUPABASE_URL: ${{ vars.VITE_SUPABASE_URL }} VITE_SUPABASE_ANON_KEY: ${{ secrets.VITE_SUPABASE_ANON_KEY }} - run: cd src && npm run build + run: cd src && npm run build && npm run build:admin - name: Publier (atomique, 3 versions conservées) env: SHA: ${{ github.sha }} diff --git a/.gitignore b/.gitignore index c85b641..f865532 100644 --- a/.gitignore +++ b/.gitignore @@ -11,3 +11,4 @@ supabase/.branches _to_delete .env.deploy tsconfig.tsbuildinfo +dist-admin diff --git a/CLAUDE.md b/CLAUDE.md index b87b1bd..5d0d1f0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -65,7 +65,7 @@ npm run build # build de prod - **Appels aux données publiques** (proxy TMDB, notes Trakt) : `publicFetch` dans `cloud/api.ts`, sans aucun en-tête → pas de pré-requête CORS (un aller-retour au lieu de deux). Limite côté serveur par adresse IP (tmdb 1000, ratings 400 / 10 min). Les données perso restent sur `cloudFetch` (jeton). ## État (au 28 nov. 2026) -- **Toutes les migrations de `supabase/migrations/` sont appliquées en ligne**, jusqu'à `20261130120000_remove_admin.sql` incluse (pg_net supprimée, index des notifications revus, réserve des notes Trakt ; notifications aux abonnés en une requête, quota vérifié une fois par envoi (trigger `*_quota_stmt`), fiche renvoyée à l'identique non réécrite). +- **Toutes les migrations de `supabase/migrations/` sont appliquées en ligne**, jusqu'à `20261130150000_admin_console.sql` incluse (pg_net supprimée, index des notifications revus, réserve des notes Trakt ; notifications aux abonnés en une requête, quota vérifié une fois par envoi (trigger `*_quota_stmt`), fiche renvoyée à l'identique non réécrite). - **29 nov. 2026** : 123 avis du compte de Romain contenaient « Réalisation : … » (ancien import, `legacyImport.ts`, corrigé). Lignes retirées en base (la copie de sauvegarde a été supprimée le même jour, correction validée). - **Affiches** : une fiche garde l'**adresse** de l'affiche (TMDB w342 / AniList), jamais l'image copiée en base64 (≈ 50 Ko par fiche, renvoyés à chaque modification et chez les amis). Seule une image choisie dans la galerie (EditDetails, 360 px) est intégrée. Le 29 nov. 2026, 109 affiches intégrées (342 px, copies automatiques) ont été remplacées par leur adresse TMDB : base des fiches 5,95 Mo → 267 Ko. - **Cache (service worker, `vite.config.ts`)** : pré-téléchargement ~1 Mo (app + français). Les 17 autres langues (`assets/locale-*`) et les variantes de police sont mises en cache à la demande (`app-files`). Caches d'exécution : `posters` (petites images TMDB/AniList, 1500), `backdrops` (grandes images, 80) — réponses opaques acceptées (`posters-v2` / `backdrops-v2`, d'un essai abandonné, sont supprimés au lancement par `main.tsx`), `catalog` (fiches TMDB avec `append_to_response`, saisons, personnes, notes Trakt : StaleWhileRevalidate 14 j ; jamais `/tv/123` seul, recherche, sorties ni données perso). React est dans son propre fichier (`react-*.js`), gardé d'une version à l'autre. @@ -79,7 +79,7 @@ npm run build # build de prod - **Compression** : `deploy/nginx/site.conf` active gzip (JS, CSS, JSON, SVG), avec `gzip_http_version 1.0` car le proxy en façade parle HTTP/1.0. Sans ça les fichiers partaient bruts. Mesure Lighthouse mobile (1re visite, 29 nov. 2026) : score 67 → 97, premier affichage 3,9 → 1,8 s, poids 789 → 248 Ko. - **Anciennes icônes installées depuis kino.rdacet.fr / azuucine.rdacet.fr** : ces adresses n'existent plus, l'app installée tourne sur sa copie (plus de mises à jour) et les fonctions serveur la refusent (CORS) → « Impossible de joindre le serveur ». Solution : supprimer l'icône et réinstaller depuis https://bobinoo.org. La date de la version est affichée en bas des Réglages. - **Notifications** (dans l'app, pas de push) : abonnements (`new_follower`, `follow_request`, `unfollow`, `follow_accepted`, trigger `follows_notify`), réaction / commentaire sur mon avis (`reaction`, `review_comment`, triggers sur `review_reactions` / `review_comments`), activité des comptes suivis (`friend_review`, `friend_started`, `friend_added`, trigger `items_notify` → `azuu_notify_followers`, rafales regroupées sur 3 h). Pas de notification pour les listes perso (privées). RPC `get_notifications` (avec le titre lié) / `unread_notifications` / `mark_notifications_read`. La fonction Edge `send-push` répond 410 : à supprimer depuis le tableau de bord Supabase. -- **Pas d'administration** (retirée le 30 nov. 2026) : pas d'écran admin, pas de signalements, bugs ou erreurs stockés en base. « Signaler » (avis, commentaire, profil, liste) et « Signaler un bug » ouvrent un e-mail pré-rempli vers contact@bobinoo.org (`mailto` dans `components/moderation/BugReport.tsx`). Modération à la main dans Supabase (voir `docs/database.md`). Après une mise à jour, une ancienne version ouverte qui ne trouve plus un fichier se recharge d'elle-même (`ErrorBoundary`). +- **Administration = console séparée** (`docs/admin.md`) : site `admin/` (build `npm run build:admin` → `dist-admin/`), jamais dans l'app publique. Servi par nginx sur `127.0.0.1:8081` (`deploy/nginx/admin.conf`), publié uniquement sur le réseau Tailscale. Appels → fonction Edge `admin` (secret `X-Admin-Gate` ajouté par nginx + jeton aal2 obligatoire + `admin.admins`) → schéma `admin` (non exposé par l'API) par connexion directe. Journal `admin.journal` en ajout seulement. Dans l'app : « Signaler » et « Signaler un bug » ouvrent un e-mail vers contact@bobinoo.org (`components/moderation/BugReport.tsx`). Après une mise à jour, une ancienne version qui ne trouve plus un fichier se recharge d'elle-même (`ErrorBoundary`). - **E-mails du compte** (inscription, mot de passe oublié, changement d'adresse) : envoyés par `contact@bobinoo.org` (OVH Zimbra Starter, SMTP `ssl0.ovh.net:465`, DKIM actif), modèles dans `docs/emails/`. Testé le 30 nov. 2026 : reçu en boîte de réception, lien de confirmation OK. Limite Supabase : 30 e-mails / heure. `contact@bobinoo.org` est aussi l'adresse de contact des pages légales, de « Signaler un bug » et du Play Store. - **Retirés (27-28 nov. 2026)** : défis, couleur d'accent au choix, apparences Nuit/Étoilé, notation sur 10 (les notes restent stockées sur 10 en interne, affichées sur 5 étoiles). - **Double authentification (TOTP)** : optionnelle, Réglages → Mon compte (`src/components/TwoFactor.tsx`, fonctions dans `src/lib/cloud/auth.ts`). À la connexion, `Root.tsx` demande le code (`MfaScreen`) si le compte a un facteur vérifié. Côté serveur, `azuu_mfa_ok()` : règles RLS restrictives « mfa required » (items, lists, settings, follows, profiles, activity), `is_admin()` et `azuu_me_active()` ; les fonctions Edge (`_shared/auth.ts`) refusent un jeton « aal1 » d'un compte protégé. diff --git a/admin/index.html b/admin/index.html new file mode 100644 index 0000000..ba23ce0 --- /dev/null +++ b/admin/index.html @@ -0,0 +1,15 @@ + + + + + + + + + Console Bobinoo + + +
+ + + diff --git a/admin/src/App.tsx b/admin/src/App.tsx new file mode 100644 index 0000000..e271cc2 --- /dev/null +++ b/admin/src/App.tsx @@ -0,0 +1,177 @@ +import { LogOut, ShieldCheck } from 'lucide-react' +import { useCallback, useEffect, useRef, useState, type FormEvent } from 'react' +import { ApiError, call, type Card } from './api' +import { AuthError, expiresAt, signIn, signOut, verifyCode } from './auth' +import { Comments, Dashboard, Journal, Members, Reviews } from './screens' + +/** Déconnexion automatique après 15 minutes sans toucher à la console. */ +const IDLE_MS = 15 * 60_000 + +type Tab = 'dashboard' | 'members' | 'reviews' | 'comments' | 'journal' +const TABS: { id: Tab; label: string }[] = [ + { id: 'dashboard', label: 'Tableau de bord' }, + { id: 'members', label: 'Membres' }, + { id: 'reviews', label: 'Avis' }, + { id: 'comments', label: 'Commentaires' }, + { id: 'journal', label: 'Journal' }, +] + +export default function App() { + // Jeton gardé en mémoire seulement : recharger la page déconnecte + const [session, setSession] = useState<{ token: string; me: Card }>() + const [notice, setNotice] = useState() + + const logout = useCallback((why?: string) => { + setSession((s) => { + if (s) void signOut(s.token) + return undefined + }) + setNotice(why) + }, []) + + // Fin de validité du jeton, inactivité : retour à l'écran de connexion + useEffect(() => { + if (!session) return + const end = window.setTimeout(() => logout('Session terminée (1 h) : reconnecte-toi.'), Math.max(0, expiresAt(session.token) - Date.now() - 30_000)) + let idle = window.setTimeout(() => logout('Déconnecté après 15 minutes sans activité.'), IDLE_MS) + const touch = () => { + window.clearTimeout(idle) + idle = window.setTimeout(() => logout('Déconnecté après 15 minutes sans activité.'), IDLE_MS) + } + for (const ev of ['pointerdown', 'keydown'] as const) window.addEventListener(ev, touch) + return () => { + window.clearTimeout(end) + window.clearTimeout(idle) + for (const ev of ['pointerdown', 'keydown'] as const) window.removeEventListener(ev, touch) + } + }, [session, logout]) + + if (!session) return (setNotice(undefined), setSession({ token, me }))} /> + return +} + +function Login({ notice, onReady }: { notice?: string; onReady: (token: string, me: Card) => void }) { + const [step, setStep] = useState<{ token: string; factorId: string }>() + const [email, setEmail] = useState('') + const [password, setPassword] = useState('') + const [code, setCode] = useState('') + const [busy, setBusy] = useState(false) + const [error, setError] = useState() + const codeRef = useRef(null) + + const submit = async (e: FormEvent) => { + e.preventDefault() + if (busy) return + setBusy(true) + setError(undefined) + try { + if (!step) { + const r = await signIn(email, password) + setPassword('') + if (!r.factorId) { + await signOut(r.token) + throw new AuthError("Ce compte n'a pas la double authentification. Active-la d'abord dans l'app (Réglages → Mon compte), elle est obligatoire ici.") + } + setStep({ token: r.token, factorId: r.factorId }) + setTimeout(() => codeRef.current?.focus(), 0) + } else { + const token = await verifyCode(step.token, step.factorId, code.replace(/\s/g, '')) + const me = await call(token, 'hello') + onReady(token, me) + } + } catch (err) { + setError(err instanceof AuthError || err instanceof ApiError ? err.message : 'Erreur inattendue.') + if (step) setCode('') + } finally { + setBusy(false) + } + } + + return ( +
+
+ + Console +
+

Bobinoo

+

Accès réservé. Chaque connexion est inscrite au journal et signalée par e-mail.

+ {notice &&

{notice}

} +
+ {!step ? ( + <> + setEmail(e.target.value)} required /> + setPassword(e.target.value)} required /> + + ) : ( + <> +

Code à 6 chiffres de ton application d'authentification :

+ setCode(e.target.value)} + required + /> + + )} + {error &&

{error}

} + + {step && ( + + )} +
+
+ ) +} + +function Console({ token, me, onLogout }: { token: string; me: Card; onLogout: (why?: string) => void }) { + const [tab, setTab] = useState('dashboard') + // Erreur de session renvoyée par le serveur : retour à la connexion + const onAuthError = useCallback( + (e: unknown) => { + if (e instanceof ApiError && (e.status === 401 || e.status === 403)) onLogout(e.message) + }, + [onLogout], + ) + const props = { token, onAuthError } + return ( +
+
+
+ + Console Bobinoo + @{me.username} + +
+ +
+
+ {tab === 'dashboard' && } + {tab === 'members' && } + {tab === 'reviews' && } + {tab === 'comments' && } + {tab === 'journal' && } +
+
+ ) +} diff --git a/admin/src/api.ts b/admin/src/api.ts new file mode 100644 index 0000000..85d9680 --- /dev/null +++ b/admin/src/api.ts @@ -0,0 +1,90 @@ +/** Appels à la fonction serveur « admin », par le relais nginx du VPS (qui ajoute le secret). */ +export class ApiError extends Error { + constructor( + public status: number, + message: string, + ) { + super(message) + } +} + +const MESSAGES: Record = { + session: 'Session expirée : reconnecte-toi.', + mfa: 'Code de double authentification requis : reconnecte-toi.', + interdit: "Ce compte n'est pas administrateur.", + 'trop de requêtes': 'Trop de requêtes, patiente une minute.', +} + +export async function call(token: string, action: string, params: Record = {}): Promise { + let res: Response + try { + res = await fetch('/api/admin', { + method: 'POST', + headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` }, + body: JSON.stringify({ action, ...params }), + credentials: 'omit', + cache: 'no-store', + }) + } catch { + throw new ApiError(0, 'Serveur injoignable (VPN Tailscale activé ?).') + } + if (res.status === 404) throw new ApiError(404, 'La console n\'est pas reliée au serveur (secret du VPS absent ou différent).') + const body = (await res.json().catch(() => ({}))) as { error?: string } + if (!res.ok) throw new ApiError(res.status, MESSAGES[body.error ?? ''] ?? body.error ?? `Erreur ${res.status}`) + return body as T +} + +export interface Card { + id: string + username: string + display_name: string + avatar_url?: string | null + suspended: boolean +} +export interface Overview { + members: number + members_week: number + active_week: number + suspended: number + private: number + items: number + reviews: number + comments: number + follows: number + shared_lists: number + latest: (Card & { created_at: string })[] +} +export interface Member extends Card { + email: string + created_at: string + last_sign_in_at?: string | null + items: number + mfa: boolean + is_admin: boolean +} +export interface Review { + user: Card + item_id: string + title: string + rating?: number | null + spoiler: boolean + notes: string + updated_at: string + comments: number +} +export interface Comment { + id: number + body: string + created_at: string + user: Card + author: Card + title?: string | null +} +export interface JournalEntry { + id: number + at: string + action: string + target?: string | null + details: Record + admin?: string | null +} diff --git a/admin/src/auth.ts b/admin/src/auth.ts new file mode 100644 index 0000000..73e83e2 --- /dev/null +++ b/admin/src/auth.ts @@ -0,0 +1,65 @@ +/** + * Connexion à la console : mot de passe, puis code de double authentification (obligatoire). + * La session ne vit qu'en mémoire : recharger ou fermer l'onglet déconnecte. Pas de jeton de + * renouvellement gardé : au bout d'une heure (durée du jeton Supabase), il faut se reconnecter. + */ +const URL = (import.meta.env.VITE_SUPABASE_URL ?? '').replace(/\/+$/, '') +const KEY = import.meta.env.VITE_SUPABASE_ANON_KEY ?? '' + +export class AuthError extends Error {} + +type Json = Record + +async function gotrue(path: string, opts: { token?: string; body?: Json } = {}): Promise { + if (!URL || !KEY) throw new AuthError('Console mal construite : adresse Supabase manquante.') + const res = await fetch(`${URL}/auth/v1${path}`, { + method: opts.body ? 'POST' : 'GET', + headers: { apikey: KEY, 'Content-Type': 'application/json', ...(opts.token ? { Authorization: `Bearer ${opts.token}` } : {}) }, + body: opts.body ? JSON.stringify(opts.body) : undefined, + credentials: 'omit', + cache: 'no-store', + }) + const data = (await res.json().catch(() => ({}))) as Json + if (!res.ok) { + const code = String(data.error_code ?? data.error ?? '') + if (res.status === 400 && /invalid_credentials|invalid_grant/.test(code)) throw new AuthError('E-mail ou mot de passe incorrect.') + if (res.status === 429) throw new AuthError('Trop de tentatives. Réessaie dans quelques minutes.') + if (/mfa_verification_failed|invalid.*code/i.test(code + String(data.msg ?? ''))) throw new AuthError('Code incorrect ou expiré.') + throw new AuthError(String(data.msg ?? data.message ?? data.error_description ?? `Erreur ${res.status}`)) + } + return data +} + +/** Étape 1 : e-mail et mot de passe. Renvoie le facteur TOTP à valider (absent : pas de double authentification). */ +export async function signIn(email: string, password: string): Promise<{ token: string; factorId?: string }> { + const d = await gotrue('/token?grant_type=password', { body: { email: email.trim().toLowerCase(), password } }) + const user = (d.user ?? {}) as { factors?: { id?: string; factor_type?: string; status?: string }[] } + const factor = (user.factors ?? []).find((f) => f.factor_type === 'totp' && f.status === 'verified') + if (typeof d.access_token !== 'string') throw new AuthError('Réponse inattendue du serveur.') + return { token: d.access_token, factorId: factor?.id } +} + +/** Étape 2 : code à 6 chiffres → jeton « aal2 », le seul accepté par la console. */ +export async function verifyCode(token: string, factorId: string, code: string): Promise { + const ch = await gotrue(`/factors/${encodeURIComponent(factorId)}/challenge`, { token, body: {} }) + if (typeof ch.id !== 'string') throw new AuthError('Réponse inattendue du serveur.') + const v = await gotrue(`/factors/${encodeURIComponent(factorId)}/verify`, { token, body: { challenge_id: ch.id, code } }) + if (typeof v.access_token !== 'string') throw new AuthError('Réponse inattendue du serveur.') + return v.access_token +} + +/** Déconnexion : la session est aussi fermée côté serveur. */ +export async function signOut(token: string): Promise { + await gotrue('/logout?scope=local', { token, body: {} }).catch(() => {}) +} + +/** Fin de validité du jeton (ms). */ +export function expiresAt(token: string): number { + try { + const part = token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/') + const { exp } = JSON.parse(atob(part.padEnd(part.length + ((4 - (part.length % 4)) % 4), '='))) as { exp?: number } + return typeof exp === 'number' ? exp * 1000 : Date.now() + } catch { + return Date.now() + } +} diff --git a/admin/src/main.tsx b/admin/src/main.tsx new file mode 100644 index 0000000..8a32306 --- /dev/null +++ b/admin/src/main.tsx @@ -0,0 +1,11 @@ +import { StrictMode } from 'react' +import { createRoot } from 'react-dom/client' +import '@fontsource-variable/epilogue/wght.css' +import './styles.css' +import App from './App' + +createRoot(document.getElementById('root')!).render( + + + , +) diff --git a/admin/src/screens.tsx b/admin/src/screens.tsx new file mode 100644 index 0000000..ae32ec6 --- /dev/null +++ b/admin/src/screens.tsx @@ -0,0 +1,358 @@ +import { Search } from 'lucide-react' +import { useCallback, useEffect, useState, type FormEvent, type ReactNode } from 'react' +import { ApiError, call, type Card, type Comment, type JournalEntry, type Member, type Overview, type Review } from './api' + +interface ScreenProps { + token: string + onAuthError: (e: unknown) => void +} + +const dateTime = new Intl.DateTimeFormat('fr-FR', { dateStyle: 'medium', timeStyle: 'short' }) +const date = new Intl.DateTimeFormat('fr-FR', { dateStyle: 'medium' }) +const fmt = (d?: string | null, withTime = true) => (d ? (withTime ? dateTime : date).format(new Date(d)) : '—') + +/** Liste paginée (« Voir plus ») avec recherche facultative. */ +function usePaged(token: string, action: string, onAuthError: (e: unknown) => void, q = '') { + const [rows, setRows] = useState() + const [more, setMore] = useState(false) + const [error, setError] = useState() + const [tick, setTick] = useState(0) + const load = useCallback( + async (offset: number) => { + setError(undefined) + try { + const page = await call(token, action, { q, offset }) + setRows((prev) => (offset ? [...(prev ?? []), ...page] : page)) + setMore(page.length >= (action === 'members' || action === 'journal' ? 50 : 30)) + } catch (e) { + onAuthError(e) + setError(e instanceof ApiError ? e.message : 'Erreur inattendue.') + } + }, + [token, action, q, onAuthError], + ) + useEffect(() => { + void load(0) + }, [load, tick]) + return { rows, more, error, loadMore: () => void load(rows?.length ?? 0), reload: () => setTick((n) => n + 1) } +} + +function Avatar({ card }: { card: Card }) { + return card.avatar_url ? ( + + ) : ( + + {(card.display_name || card.username || '?').charAt(0).toUpperCase()} + + ) +} + +function Who({ card, sub }: { card: Card; sub?: ReactNode }) { + return ( +
+ +
+

+ {card.display_name || card.username} @{card.username} + {card.suspended && suspendu} +

+ {sub &&

{sub}

} +
+
+ ) +} + +function Status({ rows, error, empty }: { rows?: unknown[]; error?: string; empty: string }) { + if (error) return

{error}

+ if (!rows) return

Chargement…

+ if (!rows.length) return

{empty}

+ return null +} + +function SearchBar({ placeholder, onSearch }: { placeholder: string; onSearch: (q: string) => void }) { + const [value, setValue] = useState('') + const submit = (e: FormEvent) => { + e.preventDefault() + onSearch(value.trim()) + } + return ( +
+ setValue(e.target.value.slice(0, 60))} enterKeyHint="search" /> + +
+ ) +} + +function MoreButton({ more, onMore }: { more: boolean; onMore: () => void }) { + return more ? ( + + ) : null +} + +/** Action sensible : motif obligatoire (inscrit au journal et dans l'e-mail d'alerte). */ +function Confirm({ + title, + text, + confirmLabel, + onConfirm, + onClose, +}: { + title: string + text: ReactNode + confirmLabel: string + onConfirm: (reason: string) => Promise + onClose: () => void +}) { + const [reason, setReason] = useState('') + const [busy, setBusy] = useState(false) + const [error, setError] = useState() + const submit = async (e: FormEvent) => { + e.preventDefault() + if (busy) return + setBusy(true) + setError(undefined) + try { + await onConfirm(reason.trim()) + onClose() + } catch (err) { + setError(err instanceof ApiError ? err.message : 'Erreur inattendue.') + } finally { + setBusy(false) + } + } + return ( +
+
e.stopPropagation()} className="w-full max-w-md border border-line-strong bg-surface p-5 pb-[max(1.25rem,env(safe-area-inset-bottom))]"> +

{title}

+
{text}
+ +