MonEspacePro/admin/src/pages/ModulesTab.tsx
Tony AVERTY 6968d26ce6 Admin : onglet Modules retravaillé
Chiffres clés (activés, disponibles, sur mesure), pictogramme par module,
interrupteur d'activation en un clic, chiffres du module en tuiles, réglages
et messages regroupés, barre d'enregistrement fixe signalant les
modifications non enregistrées.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 15:19:27 +02:00

261 lines
12 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useCallback, useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { api } from '../api';
import { CampaignSender } from './CampaignSender';
type Value = string | number | boolean;
export type FieldDef =
| { key: string; type: 'boolean'; label: string; help?: string; default: boolean }
| { key: string; type: 'int' | 'hour'; label: string; help?: string; default: number; min: number; max: number; unit?: string }
| { key: string; type: 'text' | 'textarea' | 'url'; label: string; help?: string; default: string; maxLength: number; variables?: string[] };
export interface ModuleInfo {
id: string;
name: string;
tagline: string;
description: string;
fields: FieldDef[];
inPlan: boolean;
override: boolean | null;
available: boolean;
config: Record<string, Value> & { enabled: boolean };
stats?: Record<string, number | string | null> | null;
}
/** Pictogramme de chaque module (même que dans l'app). */
const ICON: Record<string, string> = { campaigns: '📣', reminders: '⏰', birthday: '🎂', reviews: '⭐', referral: '🤝', stats: '📊', whiteLabel: '🏷️' };
const isMessage = (f: FieldDef) => f.type === 'text' || f.type === 'textarea';
/** Origine du module pour ce magasin. */
function Origin({ m }: { m: ModuleInfo }) {
const [label, tone] =
m.override === true ? ['Ajouté sur mesure', 'ACTIVE'] : m.override === false ? ['Retiré', 'CLOSED'] : m.inPlan ? ['Inclus dans la formule', 'ACTIVE'] : ['Non inclus', 'DRAFT'];
return <span className={`badge ${tone}`}>{label}</span>;
}
/** Champ de réglage générique, construit depuis la définition du module (API). */
function Field({ f, value, onChange }: { f: FieldDef; value: Value; onChange: (v: Value) => void }) {
const id = `f-${f.key}`;
const help = (
<>
{f.help && <span className="muted" style={{ fontSize: 14 }}>{f.help} </span>}
{'variables' in f && f.variables?.length ? (
<span className="muted" style={{ fontSize: 14 }}>
Variables : {f.variables.map((v) => <code key={v} style={{ marginRight: 6 }}>{v}</code>)}
</span>
) : null}
</>
);
if (f.type === 'boolean') {
return (
<label style={{ display: 'flex', alignItems: 'center', gap: 10, fontWeight: 600 }}>
<input type="checkbox" checked={!!value} onChange={(e) => onChange(e.target.checked)} />
{f.label}
{f.help && <span className="muted" style={{ fontWeight: 400, fontSize: 14 }}>— {f.help}</span>}
</label>
);
}
if (f.type === 'int' || f.type === 'hour') {
return (
<div>
<label htmlFor={id} style={{ fontWeight: 600 }}>{f.label}</label>
<div className="row" style={{ gap: 8, alignItems: 'center' }}>
<input
id={id}
className="input"
type="number"
style={{ width: 120 }}
min={f.min}
max={f.max}
value={Number(value)}
onChange={(e) => onChange(Math.floor(Number(e.target.value) || 0))}
/>
<span className="muted">{f.type === 'hour' ? 'h' : f.unit}</span>
</div>
{help}
</div>
);
}
const t = f as Extract<FieldDef, { maxLength: number }>;
const text = String(value ?? '');
return (
<div>
<label htmlFor={id} style={{ fontWeight: 600 }}>{f.label}</label>
{t.type === 'textarea' ? (
<textarea id={id} className="input" rows={2} maxLength={t.maxLength} value={text} onChange={(e) => onChange(e.target.value)} />
) : (
<input id={id} className="input" type={t.type === 'url' ? 'url' : 'text'} maxLength={t.maxLength} value={text} onChange={(e) => onChange(e.target.value)} />
)}
<div className="row between" style={{ gap: 8 }}>
<span>{help}</span>
<span className="muted" style={{ fontSize: 13 }}>{text.length} / {t.maxLength}</span>
</div>
{t.type !== 'url' && text !== t.default && (
<button type="button" className="link" style={{ fontSize: 14 }} onClick={() => onChange(t.default)}>Remettre le texte par défaut</button>
)}
</div>
);
}
function ModulePanel({ storeId, storeName, initial, onChanged }: { storeId: string; storeName: string; initial: ModuleInfo; onChanged: () => void }) {
const [m, setM] = useState<ModuleInfo>(initial);
const [values, setValues] = useState<Record<string, Value>>(initial.config);
const [open, setOpen] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const base = `/api/admin/stores/${storeId}/modules/${m.id}`;
const apply = (next: ModuleInfo) => {
setM(next);
setValues(next.config);
};
useEffect(() => {
if (open) api.get<ModuleInfo>(base).then(apply).catch((e) => setError(e.message));
}, [open, base]);
async function run(fn: () => Promise<ModuleInfo>, done: string) {
setBusy(true);
setError(null);
setNotice(null);
try {
apply(await fn());
setNotice(done);
onChanged();
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(false);
}
}
const dirty = JSON.stringify(values) !== JSON.stringify(m.config);
return (
<section className="card" style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
<div className="row between" style={{ alignItems: 'flex-start', gap: 12 }}>
<div style={{ flex: '1 1 320px', display: 'flex', gap: 14 }}>
<span className={`mod-ic${m.available && m.config.enabled ? ' on' : ''}`} aria-hidden="true">{ICON[m.id] ?? '🧩'}</span>
<div>
<div className="row" style={{ gap: 10, alignItems: 'center' }}>
<h2 style={{ margin: 0 }}>{m.name}</h2>
<Origin m={m} />
</div>
<p className="muted" style={{ margin: '6px 0 0' }}>{m.description}</p>
</div>
</div>
<div className="row" style={{ gap: 8 }}>
{/* Interrupteur : active ou désactive sans ouvrir les réglages */}
{m.available && (
<label className="switch" title={m.config.enabled ? 'Désactiver le module' : 'Activer le module'}>
<input
type="checkbox"
checked={m.config.enabled}
disabled={busy}
onChange={(e) => {
const enabled = e.target.checked;
run(() => api.put<ModuleInfo>(base, { enabled }), enabled ? 'Module activé.' : 'Module désactivé.');
}}
/>
<span aria-hidden="true" />
<span className="sr-only">Module activé</span>
</label>
)}
<label className="sr-only" htmlFor={`ov-${m.id}`}>Disponibilité du module</label>
<select
id={`ov-${m.id}`}
className="input"
style={{ width: 'auto' }}
disabled={busy}
value={m.override === null ? 'plan' : m.override ? 'add' : 'remove'}
onChange={(e) => {
const v = e.target.value === 'plan' ? null : e.target.value === 'add';
run(() => api.put<ModuleInfo>(`${base}/override`, { value: v }), v === null ? 'Module remis selon la formule.' : v ? 'Module ajouté sur mesure.' : 'Module retiré.');
}}
>
<option value="plan">Selon la formule{m.inPlan ? ' (inclus)' : ' (non inclus)'}</option>
<option value="add">Ajouter sur mesure</option>
<option value="remove">Retirer</option>
</select>
<button type="button" className="btn secondary" onClick={() => setOpen(!open)} aria-expanded={open}>
{open ? 'Fermer' : 'Personnaliser'}
</button>
</div>
</div>
{error && <div className="alert error" role="alert">{error}</div>}
{notice && <div className="alert ok" role="status">{notice}</div>}
{open && (
<>
{!m.available && <div className="alert warn">Module non disponible pour ce magasin : ajoutez-le sur mesure ou changez de formule pour l'activer. Vous pouvez déjà préparer ses réglages.</div>}
{m.stats && (
<div className="kpis">
{Object.entries(m.stats).map(([k, v]) => (
<div key={k} className="kpi"><b>{v ?? '—'}</b><span>{k}</span></div>
))}
</div>
)}
{(
[
['Réglages', m.fields.filter((f) => !isMessage(f)), 'mod-grid'],
['Messages', m.fields.filter(isMessage), 'mod-stack'],
] as const
).map(([title, fields, layout]) =>
fields.length ? (
<fieldset key={title} className="mod-group">
<legend>{title}</legend>
<div className={layout}>
{fields.map((f) => (
<Field key={f.key} f={f} value={values[f.key]} onChange={(v) => setValues({ ...values, [f.key]: v })} />
))}
</div>
</fieldset>
) : null,
)}
{m.id === 'stats' && <Link to="../statistiques">Voir les statistiques du magasin →</Link>}
<div className={`row mod-save${dirty ? ' dirty' : ''}`} style={{ gap: 8, justifyContent: 'flex-end' }}>
{dirty && <span className="muted" style={{ marginRight: 'auto', fontSize: 14 }}>Modifications non enregistrées</span>}
{dirty && <button type="button" className="btn secondary" disabled={busy} onClick={() => setValues(m.config)}>Annuler</button>}
<button type="button" className="btn" disabled={busy || !dirty} onClick={() => run(() => api.put<ModuleInfo>(base, values), 'Réglages enregistrés.')}>
{busy ? 'Enregistrement…' : 'Enregistrer'}
</button>
</div>
{m.id === 'campaigns' && m.available && m.config.enabled && <CampaignSender storeId={storeId} storeName={storeName} />}
</>
)}
</section>
);
}
/** Onglet « Modules » : modules complémentaires du magasin, disponibilité sur mesure et réglages complets. */
export function ModulesTab({ storeId, storeName }: { storeId: string; storeName: string }) {
const [list, setList] = useState<ModuleInfo[] | null>(null);
const [error, setError] = useState<string | null>(null);
const load = useCallback(() => {
api.get<ModuleInfo[]>(`/api/admin/stores/${storeId}/modules`).then(setList).catch((e) => setError(e.message));
}, [storeId]);
useEffect(load, [load]);
if (!list) return error ? <div className="alert error">{error}</div> : <p className="muted">Chargement…</p>;
const active = list.filter((m) => m.available && m.config.enabled).length;
const available = list.filter((m) => m.available).length;
const custom = list.filter((m) => m.override !== null).length;
return (
<>
<div className="kpis">
<div className="kpi ok"><b>{active}</b><span>modules activés</span></div>
<div className="kpi"><b>{available} / {list.length}</b><span>disponibles pour ce magasin</span></div>
<div className="kpi"><b>{custom}</b><span>ajout(s) ou retrait(s) sur mesure</span></div>
</div>
<p className="muted" style={{ margin: 0 }}>
Chaque module est inclus ou non dans la formule ; vous pouvez l’ajouter ou le retirer sur mesure. L’interrupteur l’active d’un clic,
« Personnaliser » ouvre tous ses textes et réglages. Le dirigeant peut aussi les régler depuis l’app MonEspacePro.
</p>
{list.map((m) => (
<ModulePanel key={m.id} storeId={storeId} storeName={storeName} initial={m} onChanged={load} />
))}
</>
);
}