- API NestJS + Prisma (base mep) : auth admin/employés, magasins, design de carte avec récompenses et images, comptes du personnel - Admin Vite/React : liste et fiche magasin, assistant de carte avec aperçu Apple/Google Wallet, gestion des employés - Logo MonEspacePro (Claude Design) en SVG, favicon Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
293 lines
14 KiB
TypeScript
293 lines
14 KiB
TypeScript
import { ChangeEvent, useEffect, useState } from 'react';
|
||
import { api, assetUrl, CardDesign, Reward, StoreDetail } from '../api';
|
||
import { ApplePreview, GooglePreview } from '../components/WalletPreview';
|
||
import { contrast, dominantColor, prepareLogo, prepareStrip } from '../components/images';
|
||
|
||
const STEPS = ['Identité', 'Couleurs', 'Règle de points', 'Récompenses', 'Récapitulatif'];
|
||
|
||
type Draft = Omit<CardDesign, 'logoUrl' | 'stripUrl'>;
|
||
|
||
function defaults(store: StoreDetail): Draft {
|
||
return {
|
||
programName: `Fidélité ${store.name}`.slice(0, 40),
|
||
backgroundColor: '#1F2937',
|
||
foregroundColor: '#FFFFFF',
|
||
labelColor: '#D1D5DB',
|
||
pointsMode: 'AMOUNT',
|
||
pointsPerEuro: 1,
|
||
rewards: [],
|
||
};
|
||
}
|
||
|
||
export function CardWizard({ store, onSaved }: { store: StoreDetail; onSaved: () => void }) {
|
||
const base = `/api/admin/stores/${store.id}/card-design`;
|
||
const [step, setStep] = useState(0);
|
||
const [draft, setDraft] = useState<Draft | null>(null);
|
||
const [images, setImages] = useState<{ logoUrl: string | null; stripUrl: string | null }>({ logoUrl: null, stripUrl: null });
|
||
const [saved, setSaved] = useState(false);
|
||
const [platform, setPlatform] = useState<'apple' | 'google'>('apple');
|
||
const [error, setError] = useState<string | null>(null);
|
||
const [busy, setBusy] = useState(false);
|
||
const [suggested, setSuggested] = useState<string | null>(null);
|
||
|
||
function apply(d: CardDesign) {
|
||
const { logoUrl, stripUrl, ...rest } = d;
|
||
setDraft(rest);
|
||
setImages({ logoUrl: assetUrl(logoUrl), stripUrl: assetUrl(stripUrl) });
|
||
setSaved(true);
|
||
}
|
||
|
||
useEffect(() => {
|
||
api
|
||
.get<CardDesign | null>(base)
|
||
.then((d) => (d ? apply(d) : setDraft(defaults(store))))
|
||
.catch((e) => setError(e.message));
|
||
}, [base, store]);
|
||
|
||
useEffect(() => {
|
||
if (images.logoUrl) dominantColor(images.logoUrl).then(setSuggested);
|
||
}, [images.logoUrl]);
|
||
|
||
if (!draft) return error ? <div className="alert error">{error}</div> : <p className="muted">Chargement…</p>;
|
||
|
||
const set = <K extends keyof Draft>(k: K, v: Draft[K]) => setDraft({ ...draft, [k]: v });
|
||
|
||
async function save() {
|
||
setError(null);
|
||
setBusy(true);
|
||
try {
|
||
// Uniquement les champs modifiables : l'API refuse id, storeId, updatedAt…
|
||
const { programName, backgroundColor, foregroundColor, labelColor, pointsMode, pointsPerEuro } = draft!;
|
||
const rewards = draft!.rewards.map(({ id, label, cost, active }) => ({ id, label, cost, active }));
|
||
apply(
|
||
await api.put<CardDesign>(base, {
|
||
programName,
|
||
backgroundColor,
|
||
foregroundColor,
|
||
labelColor,
|
||
pointsMode,
|
||
pointsPerEuro,
|
||
rewards,
|
||
}),
|
||
);
|
||
onSaved();
|
||
return true;
|
||
} catch (e) {
|
||
setError((e as Error).message);
|
||
return false;
|
||
} finally {
|
||
setBusy(false);
|
||
}
|
||
}
|
||
|
||
async function next() {
|
||
if (await save()) setStep((s) => Math.min(s + 1, STEPS.length - 1));
|
||
}
|
||
|
||
async function upload(kind: 'logo' | 'strip', e: ChangeEvent<HTMLInputElement>) {
|
||
const file = e.target.files?.[0];
|
||
e.target.value = '';
|
||
if (!file) return;
|
||
// Les images s'attachent à un design existant : on l'enregistre d'abord si besoin.
|
||
if (!saved && !(await save())) return;
|
||
setBusy(true);
|
||
setError(null);
|
||
try {
|
||
const png = kind === 'logo' ? await prepareLogo(file) : await prepareStrip(file);
|
||
const form = new FormData();
|
||
form.append('file', png, `${kind}.png`);
|
||
apply(await api.post<CardDesign>(`${base}/images/${kind}`, form));
|
||
} catch (err) {
|
||
setError((err as Error).message);
|
||
} finally {
|
||
setBusy(false);
|
||
}
|
||
}
|
||
|
||
const preview = { ...draft, ...images, storeName: store.name };
|
||
const fgRatio = contrast(draft.backgroundColor, draft.foregroundColor);
|
||
const labelRatio = contrast(draft.backgroundColor, draft.labelColor);
|
||
|
||
return (
|
||
<div className="wizard">
|
||
<div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
|
||
<ol className="steps" aria-label="Étapes">
|
||
{STEPS.map((label, i) => (
|
||
<li key={label}>
|
||
<button type="button" aria-current={i === step ? 'step' : undefined} onClick={() => setStep(i)}>
|
||
{i + 1} · {label}
|
||
</button>
|
||
</li>
|
||
))}
|
||
</ol>
|
||
|
||
{error && <div className="alert error" role="alert">{error}</div>}
|
||
|
||
<section className="card" style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
|
||
{step === 0 && (
|
||
<>
|
||
<h2>Identité</h2>
|
||
<div className="field">
|
||
<label htmlFor="programName">Nom du programme *</label>
|
||
<input id="programName" className="input" maxLength={40} value={draft.programName} onChange={(e) => set('programName', e.target.value)} />
|
||
</div>
|
||
<div className="field">
|
||
<span style={{ fontWeight: 600 }}>Logo</span>
|
||
<div className="upload-drop">
|
||
{images.logoUrl && <img src={images.logoUrl} alt="Logo actuel" />}
|
||
<label className="btn secondary small">
|
||
{images.logoUrl ? 'Remplacer' : 'Choisir un fichier'}
|
||
<input type="file" accept="image/png,image/jpeg,image/webp" className="sr-only" onChange={(e) => upload('logo', e)} disabled={busy} />
|
||
</label>
|
||
<span className="hint">PNG carré conseillé, fond transparent.</span>
|
||
</div>
|
||
</div>
|
||
<div className="field">
|
||
<span style={{ fontWeight: 600 }}>Bandeau</span>
|
||
<div className="upload-drop">
|
||
{images.stripUrl && <img src={images.stripUrl} alt="Bandeau actuel" />}
|
||
<label className="btn secondary small">
|
||
{images.stripUrl ? 'Remplacer' : 'Choisir un fichier'}
|
||
<input type="file" accept="image/png,image/jpeg,image/webp" className="sr-only" onChange={(e) => upload('strip', e)} disabled={busy} />
|
||
</label>
|
||
<span className="hint">Recadré automatiquement au format Wallet (1125 × 432).</span>
|
||
</div>
|
||
</div>
|
||
</>
|
||
)}
|
||
|
||
{step === 1 && (
|
||
<>
|
||
<h2>Couleurs</h2>
|
||
{suggested && suggested !== draft.backgroundColor && (
|
||
<div className="row" style={{ gap: 12 }}>
|
||
<span style={{ width: 28, height: 28, borderRadius: 8, background: suggested, border: '1px solid var(--border)' }} />
|
||
<span>Couleur extraite du logo : {suggested}</span>
|
||
<button type="button" className="btn secondary small" onClick={() => set('backgroundColor', suggested)}>Utiliser comme fond</button>
|
||
</div>
|
||
)}
|
||
{([
|
||
['backgroundColor', 'Fond'],
|
||
['foregroundColor', 'Texte'],
|
||
['labelColor', 'Libellés'],
|
||
] as const).map(([k, label]) => (
|
||
<div key={k} className="field">
|
||
<label htmlFor={k}>{label}</label>
|
||
<div className="color-row">
|
||
<input type="color" aria-label={`${label} (sélecteur)`} value={draft[k]} onChange={(e) => set(k, e.target.value.toUpperCase())} />
|
||
<input id={k} className="input" style={{ maxWidth: 160 }} value={draft[k]} pattern="#[0-9A-Fa-f]{6}" onChange={(e) => set(k, e.target.value)} />
|
||
</div>
|
||
</div>
|
||
))}
|
||
{fgRatio < 4.5 && <div className="alert warn">Contraste texte/fond insuffisant ({fgRatio.toFixed(1)}:1, minimum 4,5:1) : le solde sera difficile à lire.</div>}
|
||
{labelRatio < 3 && <div className="alert warn">Contraste libellés/fond faible ({labelRatio.toFixed(1)}:1, minimum conseillé 3:1).</div>}
|
||
</>
|
||
)}
|
||
|
||
{step === 2 && (
|
||
<>
|
||
<h2>Règle de points</h2>
|
||
<div className="mode-cards" role="radiogroup">
|
||
<label className="mode-card">
|
||
<input type="radio" name="mode" checked={draft.pointsMode === 'AMOUNT'} onChange={() => set('pointsMode', 'AMOUNT')} />
|
||
<span><strong>Points selon le montant</strong><br /><span className="muted">X points par euro dépensé</span></span>
|
||
</label>
|
||
<label className="mode-card">
|
||
<input type="radio" name="mode" checked={draft.pointsMode === 'STAMP'} onChange={() => set('pointsMode', 'STAMP')} />
|
||
<span><strong>Tampons</strong><br /><span className="muted">1 tampon par passage</span></span>
|
||
</label>
|
||
</div>
|
||
{draft.pointsMode === 'AMOUNT' ? (
|
||
<>
|
||
<div className="field">
|
||
<label htmlFor="ppe">Points par euro *</label>
|
||
<input id="ppe" className="input" type="number" step="0.01" min={0.01} max={100} style={{ maxWidth: 160 }} value={draft.pointsPerEuro} onChange={(e) => set('pointsPerEuro', Number(e.target.value))} />
|
||
</div>
|
||
<p className="muted" style={{ margin: 0 }}>
|
||
Exemple : un panier de 23,50 € = <strong>{Math.floor(23.5 * draft.pointsPerEuro)} points</strong> (arrondi à l'inférieur).
|
||
</p>
|
||
</>
|
||
) : (
|
||
<p className="muted" style={{ margin: 0 }}>Chaque passage validé par un employé ajoute un tampon, quel que soit le montant.</p>
|
||
)}
|
||
</>
|
||
)}
|
||
|
||
{step === 3 && (
|
||
<RewardsEditor
|
||
rewards={draft.rewards}
|
||
unit={draft.pointsMode === 'STAMP' ? 'tampons' : 'points'}
|
||
onChange={(r) => set('rewards', r)}
|
||
/>
|
||
)}
|
||
|
||
{step === 4 && (
|
||
<>
|
||
<h2>Récapitulatif</h2>
|
||
<ul style={{ margin: 0, paddingLeft: 20, lineHeight: 1.8 }}>
|
||
<li>Programme : <strong>{draft.programName}</strong></li>
|
||
<li>Règle : {draft.pointsMode === 'STAMP' ? '1 tampon par passage' : `${draft.pointsPerEuro} point(s) par euro`}</li>
|
||
<li>Récompenses : {draft.rewards.filter((r) => r.active !== false).map((r) => `${r.label} (${r.cost})`).join(', ') || 'aucune'}</li>
|
||
<li>Logo : {images.logoUrl ? 'oui' : <span style={{ color: 'var(--warn)' }}>manquant</span>} · Bandeau : {images.stripUrl ? 'oui' : 'non'}</li>
|
||
</ul>
|
||
<p className="muted" style={{ margin: 0 }}>
|
||
Le QR d'inscription imprimable sera disponible ici dès que la page d'inscription client sera en place.
|
||
</p>
|
||
{store.status === 'DRAFT' && <p style={{ margin: 0 }}>Utilisez le bouton <strong>Activer</strong> en haut de la fiche pour ouvrir le programme.</p>}
|
||
</>
|
||
)}
|
||
|
||
<div className="row between">
|
||
<button type="button" className="btn secondary" disabled={step === 0} onClick={() => setStep(step - 1)}>Précédent</button>
|
||
{step < STEPS.length - 1 ? (
|
||
<button type="button" className="btn" disabled={busy} onClick={next}>Enregistrer et continuer</button>
|
||
) : (
|
||
<button type="button" className="btn" disabled={busy} onClick={save}>Enregistrer</button>
|
||
)}
|
||
</div>
|
||
</section>
|
||
</div>
|
||
|
||
<aside className="preview-col" aria-label="Aperçu de la carte">
|
||
<div role="group" aria-label="Plateforme" className="row" style={{ gap: 8 }}>
|
||
<button type="button" className="chip" aria-pressed={platform === 'apple'} onClick={() => setPlatform('apple')}>Apple Wallet</button>
|
||
<button type="button" className="chip" aria-pressed={platform === 'google'} onClick={() => setPlatform('google')}>Google Wallet</button>
|
||
</div>
|
||
{platform === 'apple' ? <ApplePreview d={preview} /> : <GooglePreview d={preview} />}
|
||
<span className="muted" style={{ fontSize: 14 }}>Aperçu indicatif — QR et solde fictifs.</span>
|
||
</aside>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
function RewardsEditor({ rewards, unit, onChange }: { rewards: Reward[]; unit: string; onChange: (r: Reward[]) => void }) {
|
||
const update = (i: number, patch: Partial<Reward>) => onChange(rewards.map((r, j) => (j === i ? { ...r, ...patch } : r)));
|
||
return (
|
||
<>
|
||
<h2>Récompenses</h2>
|
||
{rewards.length === 0 && <p className="muted" style={{ margin: 0 }}>Aucune récompense. Exemple : « Café offert » pour 10 {unit}.</p>}
|
||
{rewards.map((r, i) => (
|
||
<div key={r.id ?? `new-${i}`} className="row" style={{ alignItems: 'flex-end', opacity: r.active === false ? 0.6 : 1 }}>
|
||
<div className="field" style={{ flex: '1 1 240px' }}>
|
||
<label htmlFor={`rw-label-${i}`}>Libellé</label>
|
||
<input id={`rw-label-${i}`} className="input" maxLength={60} value={r.label} onChange={(e) => update(i, { label: e.target.value })} />
|
||
</div>
|
||
<div className="field" style={{ width: 140 }}>
|
||
<label htmlFor={`rw-cost-${i}`}>Coût ({unit})</label>
|
||
<input id={`rw-cost-${i}`} className="input" type="number" min={1} value={r.cost} onChange={(e) => update(i, { cost: Number(e.target.value) })} />
|
||
</div>
|
||
{r.active === false ? (
|
||
<button type="button" className="btn secondary" onClick={() => update(i, { active: true })}>Réactiver</button>
|
||
) : (
|
||
<button type="button" className="btn secondary" aria-label={`Retirer ${r.label || 'la récompense'}`} onClick={() => onChange(rewards.filter((_, j) => j !== i))}>Retirer</button>
|
||
)}
|
||
</div>
|
||
))}
|
||
<div>
|
||
<button type="button" className="btn secondary" disabled={rewards.length >= 20} onClick={() => onChange([...rewards, { label: '', cost: 10 }])}>
|
||
+ Ajouter une récompense
|
||
</button>
|
||
</div>
|
||
</>
|
||
);
|
||
}
|