Socle back-end, admin (magasins, carte, employés) et logo

- 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>
This commit is contained in:
Tony AVERTY 2026-10-06 12:34:26 +02:00
commit a6533f2520
57 changed files with 10019 additions and 0 deletions

9
.gitignore vendored Normal file
View file

@ -0,0 +1,9 @@
node_modules/
dist/
.env
*.p12
*.pem
certs/
uploads/
.expo/
*.tsbuildinfo

16
admin/index.html Normal file
View file

@ -0,0 +1,16 @@
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="robots" content="noindex" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<title>MonEspacePro — Admin</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link href="https://fonts.googleapis.com/css2?family=Figtree:wght@400;500;600;700;800&display=swap" rel="stylesheet" />
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

1834
admin/package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

24
admin/package.json Normal file
View file

@ -0,0 +1,24 @@
{
"name": "@mep/admin",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"typecheck": "tsc -b",
"preview": "vite preview"
},
"dependencies": {
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.30.6"
},
"devDependencies": {
"@types/react": "^18.3.31",
"@types/react-dom": "^18.3.7",
"@vitejs/plugin-react": "^4.7.0",
"typescript": "^5.9.3",
"vite": "^5.4.21"
}
}

1
admin/public/favicon.svg Normal file
View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="7" fill="#0E7A66"/><g transform="translate(4.6 5.5) scale(0.36)"><path d="M12 54V32a9 9 0 0 1 18 0v22M30 32a9 9 0 0 1 18 0v22" fill="none" stroke="#FFFFFF" stroke-width="9"/><circle cx="51" cy="12" r="7" fill="#F2B544"/></g></svg>

After

Width:  |  Height:  |  Size: 324 B

179
admin/src/api.ts Normal file
View file

@ -0,0 +1,179 @@
/** Client de l'API : jeton d'accès en mémoire + rafraîchissement transparent. */
const BASE = import.meta.env.VITE_API_URL ?? '';
const REFRESH_KEY = 'mep.admin.refresh';
let accessToken: string | null = null;
let onLogout: () => void = () => undefined;
export class ApiError extends Error {
constructor(public status: number, message: string) {
super(message);
}
}
export function assetUrl(path: string | null | undefined) {
return path ? `${BASE}${path}` : null;
}
export function setLogoutHandler(fn: () => void) {
onLogout = fn;
}
export function hasSession() {
try {
return !!localStorage.getItem(REFRESH_KEY);
} catch {
return false;
}
}
function storeTokens(t: { accessToken: string; refreshToken: string }) {
accessToken = t.accessToken;
try {
localStorage.setItem(REFRESH_KEY, t.refreshToken);
} catch {
/* navigation privée : la session durera le temps de l'onglet */
}
}
export function logout() {
accessToken = null;
try {
localStorage.removeItem(REFRESH_KEY);
} catch {
/* rien */
}
onLogout();
}
export async function login(email: string, password: string) {
const t = await request<{ accessToken: string; refreshToken: string }>('POST', '/api/auth/admin/login', {
email,
password,
}, false);
storeTokens(t);
}
let refreshing: Promise<boolean> | null = null;
async function refresh(): Promise<boolean> {
let token: string | null = null;
try {
token = localStorage.getItem(REFRESH_KEY);
} catch {
/* rien */
}
if (!token) return false;
// Une seule demande de rafraîchissement à la fois, partagée par les requêtes concurrentes.
refreshing ??= fetch(`${BASE}/api/auth/refresh`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ refreshToken: token }),
})
.then(async (r) => {
if (!r.ok) return false;
storeTokens(await r.json());
return true;
})
.catch(() => false)
.finally(() => {
refreshing = null;
});
return refreshing;
}
async function request<T>(method: string, path: string, body?: unknown, auth = true, retry = true): Promise<T> {
if (auth && !accessToken) await refresh();
const isForm = body instanceof FormData;
const res = await fetch(`${BASE}${path}`, {
method,
headers: {
...(body !== undefined && !isForm && { 'Content-Type': 'application/json' }),
...(auth && accessToken && { Authorization: `Bearer ${accessToken}` }),
},
body: body === undefined ? undefined : isForm ? body : JSON.stringify(body),
});
if (res.status === 401 && auth) {
if (retry && (await refresh())) return request(method, path, body, auth, false);
logout();
}
if (!res.ok) {
const data = await res.json().catch(() => ({}));
const msg = Array.isArray(data.message) ? data.message.join(' · ') : data.message;
throw new ApiError(res.status, msg || 'Une erreur est survenue');
}
// NestJS renvoie un corps vide quand le contrôleur retourne null (ex. carte pas encore conçue).
const text = await res.text();
return (text ? JSON.parse(text) : null) as T;
}
export const api = {
get: <T>(path: string) => request<T>('GET', path),
post: <T>(path: string, body?: unknown) => request<T>('POST', path, body ?? {}),
put: <T>(path: string, body: unknown) => request<T>('PUT', path, body),
patch: <T>(path: string, body: unknown) => request<T>('PATCH', path, body),
};
// ── Types partagés avec l'API ─────────────────────────────────
export type StoreStatus = 'DRAFT' | 'ACTIVE' | 'SUSPENDED' | 'CLOSED';
export type SubscriptionStatus = 'INCOMPLETE' | 'ACTIVE' | 'PAST_DUE' | 'CANCELED';
export interface Store {
id: string;
slug: string;
name: string;
addressLine: string;
postalCode: string;
city: string;
siret: string;
contactName: string;
contactEmail: string;
contactPhone: string;
status: StoreStatus;
maxAmountEuros: number;
minScanIntervalMin: number;
createdAt: string;
}
export interface StoreListItem extends Store {
customers: number;
subscriptionStatus: SubscriptionStatus | null;
}
export interface StoreDetail extends Store {
counts: { cards: number; staff: number; transactions: number };
subscription: { status: SubscriptionStatus } | null;
}
export type PointsMode = 'AMOUNT' | 'STAMP';
export interface Reward {
id?: string;
label: string;
cost: number;
active?: boolean;
}
export interface CardDesign {
programName: string;
backgroundColor: string;
foregroundColor: string;
labelColor: string;
pointsMode: PointsMode;
pointsPerEuro: number;
rewards: Reward[];
logoUrl: string | null;
stripUrl: string | null;
}
export type StaffRole = 'MANAGER' | 'EMPLOYEE';
export interface StaffUser {
id: string;
email: string;
displayName: string;
role: StaffRole;
active: boolean;
createdAt: string;
provisionalPassword?: string;
}

View file

@ -0,0 +1,57 @@
import { NavLink, Outlet } from 'react-router-dom';
import { logout } from '../api';
/** Symbole officiel (Claude Design) ; la couleur des arches suit le thème via --brand-arch. */
export function BrandSymbol({ size = 32 }: { size?: number }) {
return (
<svg width={size} height={size} viewBox="0.5 -2 64 64" aria-hidden="true">
<path d="M12 54V32a9 9 0 0 1 18 0v22M30 32a9 9 0 0 1 18 0v22" fill="none" stroke="var(--brand-arch)" strokeWidth="8" />
<circle cx="51" cy="12" r="6" fill="#F2B544" />
</svg>
);
}
export function Brand({ admin = true }: { admin?: boolean }) {
return (
<div className="brand">
<BrandSymbol />
<span className="brand-name">
MonEspace<b>Pro</b>
</span>
{admin && (
<span className="badge DRAFT" style={{ marginLeft: 'auto', height: 22 }}>
Admin
</span>
)}
</div>
);
}
export function Layout() {
return (
<div className="shell">
<aside className="sidebar">
<Brand />
<nav aria-label="Navigation principale">
<NavLink to="/magasins">Magasins</NavLink>
</nav>
<div className="bottom">
<button type="button" className="btn secondary small" onClick={logout}>
Se déconnecter
</button>
</div>
</aside>
<main className="main">
<div className="container">
<Outlet />
</div>
</main>
</div>
);
}
export const STATUS_LABEL = { DRAFT: 'Brouillon', ACTIVE: 'Actif', SUSPENDED: 'Suspendu', CLOSED: 'Fermé' } as const;
export function StatusBadge({ status }: { status: keyof typeof STATUS_LABEL }) {
return <span className={`badge ${status}`}>{STATUS_LABEL[status]}</span>;
}

View file

@ -0,0 +1,107 @@
import { FormEvent, useState } from 'react';
import { Store } from '../api';
export type StoreInput = Omit<Store, 'id' | 'slug' | 'status' | 'createdAt'>;
export const EMPTY_STORE: StoreInput = {
name: '',
siret: '',
addressLine: '',
postalCode: '',
city: '',
contactName: '',
contactEmail: '',
contactPhone: '',
maxAmountEuros: 500,
minScanIntervalMin: 5,
};
/** Formulaire partagé entre la création et l'onglet Infos. */
export function StoreForm({
initial,
submitLabel,
onSubmit,
}: {
initial: StoreInput;
submitLabel: string;
onSubmit: (v: StoreInput) => Promise<void>;
}) {
const [v, setV] = useState(initial);
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const set = <K extends keyof StoreInput>(k: K) => (e: { target: { value: string } }) =>
setV((prev) => ({ ...prev, [k]: typeof prev[k] === 'number' ? Number(e.target.value) : e.target.value }));
async function submit(e: FormEvent) {
e.preventDefault();
setBusy(true);
setError(null);
try {
await onSubmit(v);
} catch (err) {
setError((err as Error).message);
} finally {
setBusy(false);
}
}
const text = (k: keyof StoreInput, label: string, props: React.InputHTMLAttributes<HTMLInputElement> = {}) => (
<div className="field">
<label htmlFor={k}>{label} *</label>
<input id={k} className="input" required value={v[k]} onChange={set(k)} {...props} />
</div>
);
return (
<form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
<p className="muted" style={{ margin: 0 }}>Les champs marqués d'un astérisque (*) sont obligatoires.</p>
{error && <div className="alert error" role="alert">{error}</div>}
<section className="card" style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
<h2>Commerce</h2>
<div className="grid-2">
{text('name', 'Nom du magasin')}
{text('siret', 'SIRET', { placeholder: '14 chiffres', inputMode: 'numeric', pattern: '[0-9 ]{14,17}' })}
</div>
{text('addressLine', 'Adresse', { placeholder: 'Numéro et nom de rue' })}
<div className="grid-2">
{text('postalCode', 'Code postal', { placeholder: '5 chiffres', inputMode: 'numeric', pattern: '[0-9]{5}' })}
{text('city', 'Ville')}
</div>
</section>
<section className="card" style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
<h2>Contact</h2>
{text('contactName', 'Nom du contact', { placeholder: 'Prénom Nom' })}
<div className="grid-2">
{text('contactEmail', 'E-mail', { type: 'email', placeholder: 'contact@exemple.fr' })}
{text('contactPhone', 'Téléphone', { type: 'tel', placeholder: '06 12 34 56 78' })}
</div>
</section>
<section className="card" style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
<div>
<h2>Anti-triche</h2>
<p className="muted" style={{ margin: 0 }}>
Limitent les crédits abusifs. Une opération hors limites est refusée et apparaît dans l'onglet Opérations.
</p>
</div>
<div className="grid-2">
<div className="field">
<label htmlFor="maxAmountEuros">Plafond par opération (€) *</label>
<input id="maxAmountEuros" className="input" type="number" min={1} max={10000} required value={v.maxAmountEuros} onChange={set('maxAmountEuros')} />
</div>
<div className="field">
<label htmlFor="minScanIntervalMin">Délai minimum entre deux crédits (min) *</label>
<input id="minScanIntervalMin" className="input" type="number" min={0} max={1440} required value={v.minScanIntervalMin} onChange={set('minScanIntervalMin')} />
</div>
</div>
</section>
<div>
<button className="btn" disabled={busy}>{busy ? 'Enregistrement…' : submitLabel}</button>
</div>
</form>
);
}

View file

@ -0,0 +1,108 @@
import { CardDesign } from '../api';
export type PreviewDesign = Omit<CardDesign, 'rewards'> & { storeName: string };
/** QR factice (motif fixe) : l'aperçu ne doit pas laisser croire à un vrai code. */
function FakeQr({ size }: { size: number }) {
const cells = 21;
const c = size / cells;
const finder = (x: number, y: number) => (
<g key={`${x}-${y}`}>
<rect x={x * c} y={y * c} width={7 * c} height={7 * c} fill="#000" />
<rect x={(x + 1) * c} y={(y + 1) * c} width={5 * c} height={5 * c} fill="#fff" />
<rect x={(x + 2) * c} y={(y + 2) * c} width={3 * c} height={3 * c} fill="#000" />
</g>
);
const dots = [];
for (let y = 0; y < cells; y++)
for (let x = 0; x < cells; x++) {
const inFinder = (x < 8 && y < 8) || (x > 12 && y < 8) || (x < 8 && y > 12);
if (!inFinder && (x * 7 + y * 13 + x * y) % 3 === 0) dots.push(<rect key={`${x}.${y}`} x={x * c} y={y * c} width={c} height={c} fill="#000" />);
}
return (
<svg width={size} height={size} aria-hidden="true">
<rect width={size} height={size} fill="#fff" />
{finder(0, 0)}
{finder(14, 0)}
{finder(0, 14)}
{dots}
</svg>
);
}
function balanceLabel(d: PreviewDesign) {
return d.pointsMode === 'STAMP' ? { label: 'TAMPONS', value: '7' } : { label: 'POINTS', value: '120' };
}
/** Approximation fidèle du gabarit Apple « Store Card » (logo, bandeau 1125×432, champ principal, QR). */
export function ApplePreview({ d }: { d: PreviewDesign }) {
const b = balanceLabel(d);
return (
<div style={{ width: 320, borderRadius: 14, overflow: 'hidden', background: d.backgroundColor, color: d.foregroundColor, boxShadow: '0 12px 32px rgb(0 0 0 / 0.25)', fontFamily: '-apple-system, system-ui, sans-serif' }}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px 14px', height: 50 }}>
{d.logoUrl ? (
<img src={d.logoUrl} alt="" style={{ maxHeight: 34, maxWidth: 140, objectFit: 'contain' }} />
) : (
<span style={{ fontWeight: 700 }}>{d.storeName}</span>
)}
<div style={{ textAlign: 'right' }}>
<div style={{ fontSize: 10, fontWeight: 600, color: d.labelColor }}>{b.label}</div>
<div style={{ fontSize: 18 }}>{b.value}</div>
</div>
</div>
<div style={{ position: 'relative', height: 123, background: d.stripUrl ? `center/cover url(${d.stripUrl})` : 'rgb(255 255 255 / 0.08)' }}>
<div style={{ position: 'absolute', left: 14, bottom: 10 }}>
<div style={{ fontSize: 11, fontWeight: 600, color: d.labelColor, textShadow: d.stripUrl ? '0 1px 2px rgb(0 0 0 / 0.5)' : undefined }}>SOLDE</div>
<div style={{ fontSize: 36, lineHeight: 1, textShadow: d.stripUrl ? '0 1px 3px rgb(0 0 0 / 0.5)' : undefined }}>{b.value}</div>
</div>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between', padding: '10px 14px' }}>
<div>
<div style={{ fontSize: 10, fontWeight: 600, color: d.labelColor }}>PROGRAMME</div>
<div style={{ fontSize: 14 }}>{d.programName || '—'}</div>
</div>
<div style={{ textAlign: 'right' }}>
<div style={{ fontSize: 10, fontWeight: 600, color: d.labelColor }}>MEMBRE</div>
<div style={{ fontSize: 14 }}>Camille</div>
</div>
</div>
<div style={{ display: 'flex', justifyContent: 'center', padding: '14px 0 20px' }}>
<div style={{ background: '#fff', padding: 8, borderRadius: 6 }}>
<FakeQr size={120} />
</div>
</div>
</div>
);
}
/** Gabarit Google Wallet « Loyalty » : en-tête logo + nom, solde, bandeau en bas (hero). */
export function GooglePreview({ d }: { d: PreviewDesign }) {
const b = balanceLabel(d);
return (
<div style={{ width: 320, borderRadius: 20, overflow: 'hidden', background: d.backgroundColor, color: d.foregroundColor, boxShadow: '0 12px 32px rgb(0 0 0 / 0.25)', fontFamily: 'Roboto, system-ui, sans-serif' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '14px 16px' }}>
<span style={{ width: 32, height: 32, borderRadius: '50%', background: '#fff', overflow: 'hidden', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
{d.logoUrl && <img src={d.logoUrl} alt="" style={{ width: '100%', height: '100%', objectFit: 'contain' }} />}
</span>
<span style={{ fontSize: 14 }}>{d.storeName}</span>
</div>
<div style={{ padding: '0 16px 12px', fontSize: 22 }}>{d.programName || '—'}</div>
<div style={{ display: 'flex', gap: 32, padding: '0 16px 16px' }}>
<div>
<div style={{ fontSize: 11, opacity: 0.8 }}>{b.label === 'POINTS' ? 'Points' : 'Tampons'}</div>
<div style={{ fontSize: 18 }}>{b.value}</div>
</div>
<div>
<div style={{ fontSize: 11, opacity: 0.8 }}>Membre</div>
<div style={{ fontSize: 18 }}>Camille</div>
</div>
</div>
<div style={{ display: 'flex', justifyContent: 'center', padding: '8px 0 16px' }}>
<div style={{ background: '#fff', padding: 10, borderRadius: 12 }}>
<FakeQr size={120} />
</div>
</div>
{d.stripUrl && <img src={d.stripUrl} alt="" style={{ display: 'block', width: '100%', aspectRatio: '1125 / 432', objectFit: 'cover' }} />}
</div>
);
}

View file

@ -0,0 +1,84 @@
/** Préparation des images côté navigateur : tout ressort en PNG aux dimensions Wallet. */
function load(file: File): Promise<HTMLImageElement> {
return new Promise((resolve, reject) => {
const url = URL.createObjectURL(file);
const img = new Image();
img.onload = () => {
URL.revokeObjectURL(url);
resolve(img);
};
img.onerror = () => reject(new Error('Image illisible'));
img.src = url;
});
}
function toPng(canvas: HTMLCanvasElement): Promise<Blob> {
return new Promise((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error('Conversion impossible'))), 'image/png'));
}
/** Bandeau : recadrage centré au ratio Apple (1125×432, @3x). */
export async function prepareStrip(file: File) {
const img = await load(file);
const W = 1125;
const H = 432;
const scale = Math.max(W / img.width, H / img.height);
const sw = W / scale;
const sh = H / scale;
const canvas = Object.assign(document.createElement('canvas'), { width: W, height: H });
canvas.getContext('2d')!.drawImage(img, (img.width - sw) / 2, (img.height - sh) / 2, sw, sh, 0, 0, W, H);
return toPng(canvas);
}
/** Logo : contenu dans 480×480 sans déformation, fond transparent conservé. */
export async function prepareLogo(file: File) {
const img = await load(file);
const scale = Math.min(1, 480 / Math.max(img.width, img.height));
const canvas = Object.assign(document.createElement('canvas'), {
width: Math.round(img.width * scale),
height: Math.round(img.height * scale),
});
canvas.getContext('2d')!.drawImage(img, 0, 0, canvas.width, canvas.height);
return toPng(canvas);
}
/** Couleur dominante (hors pixels transparents / quasi blancs) : suggestion de fond. */
export async function dominantColor(src: string): Promise<string | null> {
const img = new Image();
img.crossOrigin = 'anonymous';
img.src = src;
try {
await img.decode();
} catch {
return null;
}
const canvas = Object.assign(document.createElement('canvas'), { width: 48, height: 48 });
const ctx = canvas.getContext('2d')!;
ctx.drawImage(img, 0, 0, 48, 48);
const data = ctx.getImageData(0, 0, 48, 48).data;
const buckets = new Map<string, { n: number; r: number; g: number; b: number }>();
for (let i = 0; i < data.length; i += 4) {
const [r, g, b, a] = [data[i], data[i + 1], data[i + 2], data[i + 3]];
if (a < 128 || (r > 235 && g > 235 && b > 235)) continue;
const key = `${r >> 5}${g >> 5}${b >> 5}`;
const e = buckets.get(key) ?? { n: 0, r: 0, g: 0, b: 0 };
buckets.set(key, { n: e.n + 1, r: e.r + r, g: e.g + g, b: e.b + b });
}
const best = [...buckets.values()].sort((a, b) => b.n - a.n)[0];
if (!best) return null;
const hex = (v: number) => Math.round(v / best.n).toString(16).padStart(2, '0');
return `#${hex(best.r)}${hex(best.g)}${hex(best.b)}`.toUpperCase();
}
/** Ratio de contraste WCAG entre deux couleurs #RRGGBB. */
export function contrast(a: string, b: string) {
const lum = (hex: string) => {
const [r, g, bl] = [1, 3, 5].map((i) => {
const c = parseInt(hex.slice(i, i + 2), 16) / 255;
return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
});
return 0.2126 * r + 0.7152 * g + 0.0722 * bl;
};
const [l1, l2] = [lum(a), lum(b)].sort((x, y) => y - x);
return (l1 + 0.05) / (l2 + 0.05);
}

49
admin/src/main.tsx Normal file
View file

@ -0,0 +1,49 @@
import { StrictMode, useEffect, useState } from 'react';
import { createRoot } from 'react-dom/client';
import { BrowserRouter, Navigate, Route, Routes, useNavigate } from 'react-router-dom';
import { hasSession, setLogoutHandler } from './api';
import { Layout } from './components/Layout';
import { LoginPage } from './pages/LoginPage';
import { StoresPage } from './pages/StoresPage';
import { NewStorePage } from './pages/NewStorePage';
import { StorePage } from './pages/StorePage';
import './styles.css';
function App() {
const navigate = useNavigate();
const [authed, setAuthed] = useState(hasSession());
useEffect(() => {
setLogoutHandler(() => {
setAuthed(false);
navigate('/connexion');
});
}, [navigate]);
if (!authed) {
return (
<Routes>
<Route path="/connexion" element={<LoginPage onLogin={() => setAuthed(true)} />} />
<Route path="*" element={<Navigate to="/connexion" replace />} />
</Routes>
);
}
return (
<Routes>
<Route element={<Layout />}>
<Route path="/magasins" element={<StoresPage />} />
<Route path="/magasins/nouveau" element={<NewStorePage />} />
<Route path="/magasins/:id/*" element={<StorePage />} />
</Route>
<Route path="*" element={<Navigate to="/magasins" replace />} />
</Routes>
);
}
createRoot(document.getElementById('root')!).render(
<StrictMode>
<BrowserRouter future={{ v7_startTransition: true }}>
<App />
</BrowserRouter>
</StrictMode>,
);

View file

@ -0,0 +1,293 @@
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>
</>
);
}

View file

@ -0,0 +1,49 @@
import { FormEvent, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { login } from '../api';
import { Brand } from '../components/Layout';
export function LoginPage({ onLogin }: { onLogin: () => void }) {
const navigate = useNavigate();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
async function submit(e: FormEvent) {
e.preventDefault();
setBusy(true);
setError(null);
try {
await login(email, password);
onLogin();
navigate('/magasins');
} catch (err) {
setError((err as Error).message);
} finally {
setBusy(false);
}
}
return (
<main style={{ minHeight: '100vh', display: 'grid', placeItems: 'center', padding: 16 }}>
<form className="card" onSubmit={submit} style={{ width: '100%', maxWidth: 420, display: 'flex', flexDirection: 'column', gap: 20 }}>
<Brand />
<div>
<h1 style={{ fontSize: 26 }}>Connexion</h1>
<p className="muted" style={{ margin: 0 }}>Espace d'administration MonEspacePro</p>
</div>
{error && <div className="alert error" role="alert">{error}</div>}
<div className="field">
<label htmlFor="email">E-mail</label>
<input id="email" className="input" type="email" autoComplete="username" required value={email} onChange={(e) => setEmail(e.target.value)} />
</div>
<div className="field">
<label htmlFor="password">Mot de passe</label>
<input id="password" className="input" type="password" autoComplete="current-password" required minLength={8} value={password} onChange={(e) => setPassword(e.target.value)} />
</div>
<button className="btn" disabled={busy}>{busy ? 'Connexion…' : 'Se connecter'}</button>
</form>
</main>
);
}

View file

@ -0,0 +1,26 @@
import { Link, useNavigate } from 'react-router-dom';
import { api, Store } from '../api';
import { EMPTY_STORE, StoreForm } from '../components/StoreForm';
export function NewStorePage() {
const navigate = useNavigate();
return (
<>
<div>
<Link to="/magasins">← Magasins</Link>
<h1>Nouveau magasin</h1>
<p className="muted" style={{ margin: 0 }}>
Après la création, vous passerez à la conception de la carte de fidélité.
</p>
</div>
<StoreForm
initial={EMPTY_STORE}
submitLabel="Créer le magasin"
onSubmit={async (v) => {
const store = await api.post<Store>('/api/admin/stores', v);
navigate(`/magasins/${store.id}/carte`);
}}
/>
</>
);
}

View file

@ -0,0 +1,173 @@
import { FormEvent, useCallback, useEffect, useRef, useState } from 'react';
import { api, StaffRole, StaffUser } from '../api';
const ROLE_LABEL: Record<StaffRole, string> = { MANAGER: 'Gérant', EMPLOYEE: 'Employé' };
export function StaffTab({ storeId }: { storeId: string }) {
const base = `/api/admin/stores/${storeId}/staff`;
const [staff, setStaff] = useState<StaffUser[]>([]);
const [error, setError] = useState<string | null>(null);
const [created, setCreated] = useState<StaffUser | null>(null);
const formDialog = useRef<HTMLDialogElement>(null);
const passwordDialog = useRef<HTMLDialogElement>(null);
const reload = useCallback(() => {
api.get<StaffUser[]>(base).then(setStaff).catch((e) => setError(e.message));
}, [base]);
useEffect(reload, [reload]);
function showPassword(user: StaffUser) {
setCreated(user);
passwordDialog.current?.showModal();
reload();
}
async function toggle(u: StaffUser) {
try {
await api.patch(`${base}/${u.id}`, { active: !u.active });
reload();
} catch (e) {
setError((e as Error).message);
}
}
async function reset(u: StaffUser) {
if (!window.confirm(`Générer un nouveau mot de passe pour ${u.displayName} ? Ses sessions seront fermées.`)) return;
try {
showPassword(await api.post<StaffUser>(`${base}/${u.id}/reset-password`));
} catch (e) {
setError((e as Error).message);
}
}
return (
<>
<div className="row between">
<h2>Employés</h2>
<button className="btn" onClick={() => formDialog.current?.showModal()}>+ Nouvel employé</button>
</div>
{error && <div className="alert error" role="alert">{error}</div>}
<div className="table-wrap">
<div className="table-scroll">
<table style={{ minWidth: 720 }}>
<thead>
<tr>
<th scope="col" style={{ paddingLeft: 24 }}>Nom</th>
<th scope="col">E-mail</th>
<th scope="col">Rôle</th>
<th scope="col">Statut</th>
<th scope="col"><span className="sr-only">Actions</span></th>
</tr>
</thead>
<tbody>
{staff.map((u) => (
<tr key={u.id} style={{ opacity: u.active ? 1 : 0.6 }}>
<td style={{ paddingLeft: 24, fontWeight: 600 }}>{u.displayName}</td>
<td>{u.email}</td>
<td>{ROLE_LABEL[u.role]}</td>
<td>{u.active ? <span className="badge ACTIVE">Actif</span> : <span className="badge DRAFT">Désactivé</span>}</td>
<td style={{ textAlign: 'right', whiteSpace: 'nowrap' }}>
<button className="btn secondary small" onClick={() => reset(u)}>Nouveau mot de passe</button>{' '}
<button className="btn secondary small" onClick={() => toggle(u)}>{u.active ? 'Désactiver' : 'Réactiver'}</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
{staff.length === 0 && (
<p className="muted" style={{ padding: 24, margin: 0, textAlign: 'center' }}>
Aucun employé. Créez au moins un gérant pour que le magasin puisse utiliser l'app Pro.
</p>
)}
</div>
<dialog ref={formDialog} aria-labelledby="new-staff-title">
<NewStaffForm
base={base}
onCancel={() => formDialog.current?.close()}
onCreated={(u) => {
formDialog.current?.close();
showPassword(u);
}}
/>
</dialog>
<dialog ref={passwordDialog} aria-labelledby="pwd-title">
<div className="dialog-body">
<h2 id="pwd-title">Mot de passe provisoire</h2>
<p style={{ margin: 0 }}>
Communiquez-le à <strong>{created?.displayName}</strong> ({created?.email}). Il ne sera plus affiché ensuite.
</p>
<div className="password-box">{created?.provisionalPassword}</div>
<div className="row" style={{ justifyContent: 'flex-end' }}>
<button className="btn secondary" onClick={() => navigator.clipboard?.writeText(created?.provisionalPassword ?? '')}>Copier</button>
<button className="btn" onClick={() => passwordDialog.current?.close()}>J'ai noté le mot de passe</button>
</div>
</div>
</dialog>
</>
);
}
function NewStaffForm({ base, onCancel, onCreated }: { base: string; onCancel: () => void; onCreated: (u: StaffUser) => void }) {
const [displayName, setDisplayName] = useState('');
const [email, setEmail] = useState('');
const [role, setRole] = useState<StaffRole>('EMPLOYEE');
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
async function submit(e: FormEvent) {
e.preventDefault();
setBusy(true);
setError(null);
try {
onCreated(await api.post<StaffUser>(base, { displayName, email, role }));
setDisplayName('');
setEmail('');
setRole('EMPLOYEE');
} catch (err) {
setError((err as Error).message);
} finally {
setBusy(false);
}
}
return (
<form className="dialog-body" onSubmit={submit}>
<h2 id="new-staff-title">Nouvel employé</h2>
{error && <div className="alert error" role="alert">{error}</div>}
<div className="field">
<label htmlFor="staff-name">Prénom et nom *</label>
<input id="staff-name" className="input" required placeholder="Prénom Nom" value={displayName} onChange={(e) => setDisplayName(e.target.value)} />
</div>
<div className="field">
<label htmlFor="staff-email">E-mail *</label>
<input id="staff-email" className="input" type="email" required placeholder="prenom@exemple.fr" value={email} onChange={(e) => setEmail(e.target.value)} />
</div>
<fieldset style={{ border: 0, padding: 0, margin: 0 }} className="field">
<legend style={{ fontWeight: 600, marginBottom: 6 }}>Rôle *</legend>
<div className="mode-cards">
{(['EMPLOYEE', 'MANAGER'] as const).map((r) => (
<label key={r} className="mode-card">
<input type="radio" name="role" checked={role === r} onChange={() => setRole(r)} />
<span>
<strong>{ROLE_LABEL[r]}</strong>
<br />
<span className="muted" style={{ fontSize: 14 }}>
{r === 'MANAGER' ? 'Voit toutes les opérations du magasin' : 'Scanne et crédite, voit ses opérations'}
</span>
</span>
</label>
))}
</div>
</fieldset>
<p className="muted" style={{ margin: 0, fontSize: 14 }}>Un mot de passe provisoire sera généré à la création.</p>
<div className="row" style={{ justifyContent: 'flex-end' }}>
<button type="button" className="btn secondary" onClick={onCancel}>Annuler</button>
<button className="btn" disabled={busy}>Créer le compte</button>
</div>
</form>
);
}

View file

@ -0,0 +1,107 @@
import { useCallback, useEffect, useState } from 'react';
import { Link, NavLink, Navigate, Route, Routes, useParams } from 'react-router-dom';
import { api, StoreDetail, StoreStatus } from '../api';
import { StatusBadge } from '../components/Layout';
import { StoreForm } from '../components/StoreForm';
import { CardWizard } from './CardWizard';
import { StaffTab } from './StaffTab';
const TABS = [
['infos', 'Infos'],
['carte', 'Carte de fidélité'],
['employes', 'Employés'],
] as const;
export function StorePage() {
const { id } = useParams<{ id: string }>();
const [store, setStore] = useState<StoreDetail | null>(null);
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const reload = useCallback(() => {
api.get<StoreDetail>(`/api/admin/stores/${id}`).then(setStore).catch((e) => setError(e.message));
}, [id]);
useEffect(reload, [reload]);
async function changeStatus(status: StoreStatus, confirmText?: string) {
if (confirmText && !window.confirm(confirmText)) return;
setError(null);
try {
await api.patch(`/api/admin/stores/${id}/status`, { status });
reload();
} catch (e) {
setError((e as Error).message);
}
}
if (!store) return error ? <div className="alert error">{error}</div> : <p className="muted">Chargement…</p>;
return (
<>
<div className="row between">
<div>
<Link to="/magasins">← Magasins</Link>
<div className="row" style={{ gap: 12 }}>
<h1>{store.name}</h1>
<StatusBadge status={store.status} />
</div>
<p className="muted" style={{ margin: 0 }}>
{store.city} · {store.counts.cards} clients · {store.counts.staff} employés
</p>
</div>
<div className="row" style={{ gap: 8 }}>
{(store.status === 'DRAFT' || store.status === 'CLOSED') && (
<button className="btn" onClick={() => changeStatus('ACTIVE')}>Activer</button>
)}
{store.status === 'SUSPENDED' && (
<button className="btn" onClick={() => changeStatus('ACTIVE')}>Réactiver</button>
)}
{store.status === 'ACTIVE' && (
<button className="btn secondary" onClick={() => changeStatus('SUSPENDED', 'Suspendre ce magasin ? Les employés ne pourront plus scanner.')}>
Suspendre
</button>
)}
{store.status !== 'CLOSED' && (
<button className="btn secondary" onClick={() => changeStatus('CLOSED', 'Fermer ce magasin ?')}>Fermer</button>
)}
</div>
</div>
{store.status === 'SUSPENDED' && (
<div className="alert warn" role="status">
Magasin suspendu : les scans et les nouvelles inscriptions sont refusés.
</div>
)}
{error && <div className="alert error" role="alert">{error}</div>}
{notice && <div className="alert ok" role="status">{notice}</div>}
<nav className="tabs" aria-label="Sections du magasin">
{TABS.map(([path, label]) => (
<NavLink key={path} to={path}>{label}</NavLink>
))}
</nav>
<Routes>
<Route index element={<Navigate to="infos" replace />} />
<Route
path="infos"
element={
<StoreForm
key={store.id}
initial={store}
submitLabel="Enregistrer"
onSubmit={async (v) => {
const { name, siret, addressLine, postalCode, city, contactName, contactEmail, contactPhone, maxAmountEuros, minScanIntervalMin } = v;
await api.patch(`/api/admin/stores/${id}`, { name, siret, addressLine, postalCode, city, contactName, contactEmail, contactPhone, maxAmountEuros, minScanIntervalMin });
setNotice('Modifications enregistrées.');
reload();
}}
/>
}
/>
<Route path="carte" element={<CardWizard store={store} onSaved={reload} />} />
<Route path="employes" element={<StaffTab storeId={store.id} />} />
</Routes>
</>
);
}

View file

@ -0,0 +1,120 @@
import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { api, StoreListItem, StoreStatus } from '../api';
import { STATUS_LABEL, StatusBadge } from '../components/Layout';
const FILTERS: (StoreStatus | 'ALL')[] = ['ALL', 'DRAFT', 'ACTIVE', 'SUSPENDED', 'CLOSED'];
function initials(name: string) {
return name
.split(' ')
.filter((w) => w.length > 2)
.slice(-2)
.map((w) => w[0])
.join('')
.toUpperCase();
}
function subscriptionLabel(s: StoreListItem['subscriptionStatus']) {
if (s === 'ACTIVE') return <span style={{ color: 'var(--ok)', fontWeight: 600 }}>Actif</span>;
if (s === 'PAST_DUE') return <span style={{ color: 'var(--err)', fontWeight: 600 }}>Impayé</span>;
if (s === 'INCOMPLETE') return <span className="muted">En attente</span>;
return <span className="muted">—</span>;
}
export function StoresPage() {
const [q, setQ] = useState('');
const [status, setStatus] = useState<StoreStatus | 'ALL'>('ALL');
const [data, setData] = useState<{ items: StoreListItem[]; counts: Partial<Record<StoreStatus, number>> } | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
// Petite temporisation : pas une requête par frappe.
const t = setTimeout(() => {
const params = new URLSearchParams();
if (q.trim()) params.set('q', q.trim());
if (status !== 'ALL') params.set('status', status);
api
.get<typeof data>(`/api/admin/stores?${params}`)
.then(setData)
.catch((e) => setError(e.message));
}, 250);
return () => clearTimeout(t);
}, [q, status]);
const total = data ? Object.values(data.counts).reduce((a, b) => a + (b ?? 0), 0) : 0;
const unpaid = data?.items.filter((s) => s.subscriptionStatus === 'PAST_DUE').length ?? 0;
return (
<>
<div className="row between" style={{ alignItems: 'flex-end' }}>
<div>
<h1>Magasins</h1>
<p className="muted" style={{ margin: 0 }}>
{total} magasins inscrits · {unpaid} abonnements impayés
</p>
</div>
<Link to="/magasins/nouveau" className="btn">+ Nouveau magasin</Link>
</div>
<div className="row">
<div style={{ flex: '1 1 320px', maxWidth: 420 }}>
<label htmlFor="search" className="sr-only">Rechercher un magasin</label>
<input id="search" type="search" className="input" placeholder="Rechercher par nom ou ville" value={q} onChange={(e) => setQ(e.target.value)} />
</div>
<div role="group" aria-label="Filtrer par statut" className="row" style={{ gap: 8 }}>
{FILTERS.map((f) => (
<button key={f} type="button" className="chip" aria-pressed={status === f} onClick={() => setStatus(f)}>
{f === 'ALL' ? 'Tous' : STATUS_LABEL[f]}
<span style={{ opacity: 0.8, fontWeight: 500 }}>{f === 'ALL' ? total : data?.counts[f] ?? 0}</span>
</button>
))}
</div>
</div>
{error && <div className="alert error">{error}</div>}
<div className="table-wrap">
<div className="table-scroll">
<table style={{ minWidth: 860 }}>
<thead>
<tr>
<th scope="col" style={{ paddingLeft: 24 }}>Magasin</th>
<th scope="col">Ville</th>
<th scope="col">Statut</th>
<th scope="col" className="num">Clients</th>
<th scope="col">Abonnement</th>
<th scope="col">Créé le</th>
</tr>
</thead>
<tbody>
{data?.items.map((s) => (
<tr key={s.id}>
<td style={{ paddingLeft: 24 }}>
<Link to={`/magasins/${s.id}`} style={{ display: 'inline-flex', alignItems: 'center', gap: 12, color: 'var(--text)', fontWeight: 600, textDecoration: 'none' }}>
<span style={{ width: 36, height: 36, borderRadius: 10, background: 'var(--primary-soft)', color: 'var(--primary)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 13, fontWeight: 800 }}>
{initials(s.name)}
</span>
{s.name}
</Link>
</td>
<td>{s.city}</td>
<td><StatusBadge status={s.status} /></td>
<td className="num">{s.customers}</td>
<td>{subscriptionLabel(s.subscriptionStatus)}</td>
<td className="muted">{new Date(s.createdAt).toLocaleDateString('fr-FR', { day: 'numeric', month: 'short', year: 'numeric' })}</td>
</tr>
))}
</tbody>
</table>
</div>
{data && data.items.length === 0 && (
<div style={{ padding: '48px 24px', textAlign: 'center' }}>
<strong>Aucun magasin trouvé</strong>
<p className="muted" style={{ margin: 0 }}>Essayez un autre nom, une autre ville ou retirez le filtre de statut.</p>
</div>
)}
</div>
</>
);
}

177
admin/src/styles.css Normal file
View file

@ -0,0 +1,177 @@
/* Tokens du design system MonEspacePro (maquettes Claude Design). */
:root {
--primary: #0e7a66;
--primary-hover: #0b6253;
--primary-soft: #eaf6f2;
--accent: #f2b544;
--bg: #f6f6f3;
--surface: #ffffff;
--surface-2: #eeede8;
--border: #dedcd6;
--border-strong: #8a897f;
--text: #1c1c19;
--text-2: #45443e;
--text-3: #5f5e56;
--ok-bg: #e5f3e9;
--ok: #1e7a3c;
--warn-bg: #fcefd6;
--warn: #8f5300;
--err-bg: #fbe7e5;
--err: #b8322a;
--radius: 10px;
color-scheme: light;
}
@media (prefers-color-scheme: dark) {
:root {
--primary: #3cb59c;
--primary-hover: #5cc7b0;
--primary-soft: #143a33;
--bg: #141412;
--surface: #1d1d1a;
--surface-2: #272723;
--border: #34342f;
--border-strong: #6d6c63;
--text: #f2f1ec;
--text-2: #cfcec6;
--text-3: #a5a49b;
--ok-bg: #173523;
--ok: #6fcf8f;
--warn-bg: #3a2b10;
--warn: #f2b544;
--err-bg: #3d1a17;
--err: #f08a80;
color-scheme: dark;
}
}
* { box-sizing: border-box; }
body {
margin: 0;
background: var(--bg);
color: var(--text);
font: 400 16px/1.5 'Figtree', system-ui, sans-serif;
}
a { color: var(--primary); }
a:hover { color: var(--primary-hover); }
h1 { margin: 0; font-size: 32px; line-height: 40px; font-weight: 700; letter-spacing: -0.01em; }
h2 { margin: 0; font-size: 20px; font-weight: 700; }
.muted { color: var(--text-3); }
.sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); }
/* ── Layout ── */
.shell { min-height: 100vh; display: flex; flex-wrap: wrap; }
.sidebar {
flex: 1 1 240px; max-width: 280px; background: var(--surface); border-right: 1px solid var(--border);
padding: 24px 16px; display: flex; flex-direction: column; gap: 28px;
}
.sidebar nav { display: flex; flex-direction: column; gap: 4px; }
.sidebar nav a {
display: flex; align-items: center; gap: 12px; height: 44px; padding: 0 12px; border-radius: var(--radius);
color: var(--text-2); font-weight: 500; text-decoration: none;
}
.sidebar nav a.active { background: var(--primary-soft); color: var(--primary); font-weight: 600; }
.sidebar .bottom { margin-top: auto; border-top: 1px solid var(--surface-2); padding: 16px 8px 0; }
.main { flex: 999 1 560px; min-width: 0; padding: 32px 40px 48px; }
.container { max-width: 1200px; margin: 0 auto; display: flex; flex-direction: column; gap: 24px; }
.row { display: flex; flex-wrap: wrap; gap: 16px; align-items: center; }
.between { justify-content: space-between; }
@media (max-width: 720px) {
.sidebar { max-width: none; border-right: 0; border-bottom: 1px solid var(--border); }
.main { padding: 24px 16px; }
}
/* ── Logo ── */
.brand { display: flex; align-items: center; gap: 10px; padding: 0 8px; }
.brand { --brand-arch: #0e7a66; }
@media (prefers-color-scheme: dark) { .brand { --brand-arch: #3dc3a2; } }
.brand-name { font-size: 19px; font-weight: 700; letter-spacing: -0.03em; }
.brand-name b { font-weight: 700; color: var(--brand-arch); }
/* ── Composants ── */
.card { background: var(--surface); border: 1px solid var(--border); border-radius: 16px; padding: 24px; }
.btn {
height: 48px; padding: 0 20px; border-radius: var(--radius); border: 1px solid transparent; cursor: pointer;
font: 600 16px 'Figtree', sans-serif; display: inline-flex; align-items: center; justify-content: center; gap: 10px;
text-decoration: none; background: var(--primary); color: #fff;
}
.btn:hover:not(:disabled) { background: var(--primary-hover); color: #fff; }
.btn:disabled { opacity: 0.55; cursor: not-allowed; }
.btn.secondary { background: var(--surface); color: var(--text); border-color: var(--border-strong); }
.btn.secondary:hover:not(:disabled) { background: var(--surface-2); color: var(--text); }
.btn.danger { background: var(--err); }
.btn.small { height: 36px; padding: 0 14px; font-size: 14px; }
.field { display: flex; flex-direction: column; gap: 6px; }
.field label { font-size: 15px; font-weight: 600; }
.field .hint { font-size: 14px; color: var(--text-3); }
.field .error { font-size: 14px; color: var(--err); }
.input, select.input {
height: 48px; padding: 0 14px; border: 1px solid var(--border-strong); border-radius: var(--radius);
background: var(--surface); color: var(--text); font: 400 16px 'Figtree', sans-serif; width: 100%;
}
.input:focus { outline: 2px solid var(--primary); outline-offset: 1px; }
.grid-2 { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 20px; }
.badge {
display: inline-flex; align-items: center; gap: 8px; height: 28px; padding: 0 12px; border-radius: 999px;
font-size: 14px; font-weight: 600;
}
.badge::before { content: ''; width: 8px; height: 8px; border-radius: 50%; background: currentColor; }
.badge.DRAFT { background: var(--surface-2); color: var(--text-2); }
.badge.DRAFT::before { background: transparent; border: 2px solid currentColor; }
.badge.ACTIVE { background: var(--ok-bg); color: var(--ok); }
.badge.SUSPENDED { background: var(--warn-bg); color: var(--warn); }
.badge.CLOSED { background: var(--err-bg); color: var(--err); }
.chip {
height: 40px; padding: 0 14px; border-radius: 999px; border: 1px solid var(--border-strong); background: var(--surface);
color: var(--text); font: 600 15px 'Figtree', sans-serif; cursor: pointer; display: inline-flex; align-items: center; gap: 8px;
}
.chip[aria-pressed='true'] { background: var(--primary); border-color: var(--primary); color: #fff; }
.table-wrap { background: var(--surface); border: 1px solid var(--border); border-radius: 16px; overflow: hidden; }
.table-scroll { overflow-x: auto; }
table { width: 100%; border-collapse: collapse; font-size: 15px; }
th { background: var(--surface-2); text-align: left; color: var(--text-2); font-size: 13px; font-weight: 600; padding: 12px 16px; }
td { border-top: 1px solid var(--surface-2); padding: 12px 16px; height: 64px; }
td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; }
.alert { padding: 14px 18px; border-radius: 12px; font-weight: 500; }
.alert.error { background: var(--err-bg); color: var(--err); }
.alert.warn { background: var(--warn-bg); color: var(--warn); }
.alert.ok { background: var(--ok-bg); color: var(--ok); }
.tabs { display: flex; gap: 4px; border-bottom: 1px solid var(--border); overflow-x: auto; }
.tabs a {
padding: 12px 16px; text-decoration: none; color: var(--text-2); font-weight: 600; border-bottom: 3px solid transparent;
white-space: nowrap;
}
.tabs a.active { color: var(--primary); border-bottom-color: var(--primary); }
dialog { border: 0; border-radius: 16px; padding: 0; max-width: 520px; width: calc(100% - 32px); background: var(--surface); color: var(--text); }
dialog::backdrop { background: rgb(0 0 0 / 0.45); }
.dialog-body { padding: 24px; display: flex; flex-direction: column; gap: 20px; }
.password-box {
font: 600 22px ui-monospace, monospace; letter-spacing: 0.06em; background: var(--surface-2); border-radius: var(--radius);
padding: 14px; text-align: center; user-select: all;
}
/* ── Assistant de carte ── */
.wizard { display: grid; grid-template-columns: minmax(0, 1fr) 380px; gap: 32px; align-items: start; }
@media (max-width: 1000px) { .wizard { grid-template-columns: 1fr; } }
.steps { display: flex; gap: 8px; flex-wrap: wrap; list-style: none; margin: 0; padding: 0; }
.steps button {
height: 40px; padding: 0 14px; border-radius: 999px; border: 1px solid var(--border); background: var(--surface);
color: var(--text-2); font: 600 14px 'Figtree', sans-serif; cursor: pointer;
}
.steps button[aria-current='step'] { background: var(--primary); border-color: var(--primary); color: #fff; }
.preview-col { position: sticky; top: 24px; display: flex; flex-direction: column; gap: 16px; align-items: center; }
.color-row { display: flex; align-items: center; gap: 12px; }
.color-row input[type='color'] { width: 48px; height: 48px; border: 1px solid var(--border-strong); border-radius: var(--radius); padding: 2px; background: var(--surface); }
.mode-cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 16px; }
.mode-card { border: 2px solid var(--border); border-radius: 14px; padding: 18px; cursor: pointer; display: flex; gap: 12px; }
.mode-card:has(input:checked) { border-color: var(--primary); background: var(--primary-soft); }
.upload-drop { border: 2px dashed var(--border-strong); border-radius: 14px; padding: 20px; display: flex; align-items: center; gap: 16px; }
.upload-drop img { max-height: 72px; max-width: 200px; border-radius: 6px; }

15
admin/tsconfig.json Normal file
View file

@ -0,0 +1,15 @@
{
"compilerOptions": {
"target": "ES2021",
"lib": ["ES2021", "DOM", "DOM.Iterable"],
"module": "ESNext",
"moduleResolution": "bundler",
"jsx": "react-jsx",
"strict": true,
"noEmit": true,
"skipLibCheck": true,
"isolatedModules": true,
"types": ["vite/client"]
},
"include": ["src", "vite.config.ts"]
}

14
admin/vite.config.ts Normal file
View file

@ -0,0 +1,14 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
// En dev, l'API tourne sur :3100 ; en prod, VITE_API_URL pointe vers son sous-domaine.
export default defineConfig({
plugins: [react()],
server: {
port: 5173,
proxy: {
'/api': 'http://localhost:3100',
'/uploads': 'http://localhost:3100',
},
},
});

9
backend/.env.example Normal file
View file

@ -0,0 +1,9 @@
NODE_ENV=development
PORT=3100
TZ=Europe/Paris
DATABASE_URL="mysql://mep:CHANGE_ME@localhost:3306/mep"
JWT_ACCESS_SECRET=dev-access-secret
JWT_REFRESH_SECRET=dev-refresh-secret
CORS_ORIGINS=http://localhost:5173
SEED_ADMIN_EMAIL=
SEED_ADMIN_PASSWORD=

8
backend/nest-cli.json Normal file
View file

@ -0,0 +1,8 @@
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true
}
}

5199
backend/package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

49
backend/package.json Normal file
View file

@ -0,0 +1,49 @@
{
"name": "@mep/backend",
"version": "0.1.0",
"description": "API MonEspacePro — NestJS + Prisma + MySQL.",
"private": true,
"scripts": {
"build": "nest build",
"start": "nest start",
"start:dev": "nest start --watch",
"start:prod": "node dist/src/main.js",
"prisma:generate": "prisma generate",
"db:push": "prisma db push",
"prisma:migrate": "prisma migrate dev",
"prisma:deploy": "prisma migrate deploy",
"db:seed": "ts-node prisma/seed.ts",
"typecheck": "tsc --noEmit",
"postinstall": "prisma generate"
},
"dependencies": {
"@nestjs/common": "^10.4.4",
"@nestjs/config": "^3.2.3",
"@nestjs/core": "^10.4.4",
"@nestjs/jwt": "^10.2.0",
"@nestjs/mapped-types": "^2.1.1",
"@nestjs/passport": "^10.0.3",
"@nestjs/platform-express": "^10.4.4",
"@nestjs/throttler": "^6.5.0",
"@prisma/client": "^5.20.0",
"argon2": "^0.41.1",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
"helmet": "^8.3.0",
"passport": "^0.7.0",
"passport-jwt": "^4.0.1",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1"
},
"devDependencies": {
"@nestjs/cli": "^10.4.5",
"@nestjs/schematics": "^10.1.4",
"@types/express": "^5.0.0",
"@types/multer": "^2.3.0",
"@types/node": "^22.7.4",
"@types/passport-jwt": "^4.0.1",
"prisma": "^5.20.0",
"ts-node": "^10.9.2",
"typescript": "^5.6.2"
}
}

View file

@ -0,0 +1,219 @@
// ─────────────────────────────────────────────────────────────
// MonEspacePro (MEP) — carte de fidélité dématérialisée
// Prisma + MySQL, base « mep » (séparée de GoSortir).
// ─────────────────────────────────────────────────────────────
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
}
// ── Administration (moi) ──────────────────────────────────────
model Admin {
id String @id @default(cuid())
email String @unique
passwordHash String
createdAt DateTime @default(now())
}
// ── Magasins ──────────────────────────────────────────────────
enum StoreStatus {
DRAFT /// créé, carte pas encore conçue / abonnement pas encore actif
ACTIVE
SUSPENDED /// paiement échoué : scans et inscriptions refusés
CLOSED
}
model Store {
id String @id @default(cuid())
/// Identifiant public court utilisé dans les URL d'inscription (/c/<slug>).
slug String @unique
name String
addressLine String
postalCode String
city String
siret String @db.Char(14)
contactName String
contactEmail String
contactPhone String
status StoreStatus @default(DRAFT)
// Anti-triche : réglages par magasin
maxAmountCents Int @default(50000) /// plafond d'un montant saisi
minScanIntervalSec Int @default(300) /// délai minimum entre deux crédits d'un même client
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
cardDesign CardDesign?
staff StaffUser[]
cards LoyaltyCard[]
transactions Transaction[]
subscription Subscription?
invoices Invoice[]
}
enum PointsMode {
AMOUNT /// points proportionnels au montant (pointsPerEuro)
STAMP /// un tampon par passage
}
model CardDesign {
id String @id @default(cuid())
storeId String @unique
store Store @relation(fields: [storeId], references: [id], onDelete: Cascade)
programName String
logoPath String?
stripPath String? /// bandeau
backgroundColor String @default("#1F2937")
foregroundColor String @default("#FFFFFF")
labelColor String @default("#D1D5DB")
pointsMode PointsMode @default(AMOUNT)
pointsPerEuro Decimal @default(1) @db.Decimal(6, 2)
rewards Reward[]
updatedAt DateTime @updatedAt
}
model Reward {
id String @id @default(cuid())
cardDesignId String
cardDesign CardDesign @relation(fields: [cardDesignId], references: [id], onDelete: Cascade)
label String
cost Int /// points ou tampons nécessaires
active Boolean @default(true)
transactions Transaction[]
}
// ── Personnel du magasin (app Pro) ────────────────────────────
enum StaffRole {
MANAGER
EMPLOYEE
}
model StaffUser {
id String @id @default(cuid())
storeId String
store Store @relation(fields: [storeId], references: [id], onDelete: Cascade)
email String @unique
displayName String
passwordHash String
role StaffRole @default(EMPLOYEE)
active Boolean @default(true)
/// Incrémenté pour révoquer tous les jetons de rafraîchissement.
tokenVersion Int @default(0)
createdAt DateTime @default(now())
transactions Transaction[]
}
// ── Clients finaux ────────────────────────────────────────────
model Customer {
id String @id @default(cuid())
firstName String
email String
consentAt DateTime /// consentement RGPD horodaté
createdAt DateTime @default(now())
cards LoyaltyCard[]
}
model LoyaltyCard {
id String @id @default(cuid())
storeId String
store Store @relation(fields: [storeId], references: [id], onDelete: Cascade)
customerId String
customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade)
/// Numéro de série du pass Wallet ; contenu du QR (non devinable).
serial String @unique
/// Jeton d'authentification du service web Apple Wallet.
authToken String
balance Int @default(0)
lastCreditAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
transactions Transaction[]
devices AppleRegistration[]
@@unique([storeId, customerId])
}
enum TransactionType {
CREDIT
REDEEM
ADJUST /// correction manuelle (gérant)
}
/// Journal immuable : chaque scan est enregistré avec l'employé.
model Transaction {
id String @id @default(cuid())
storeId String
store Store @relation(fields: [storeId], references: [id], onDelete: Cascade)
cardId String
card LoyaltyCard @relation(fields: [cardId], references: [id], onDelete: Cascade)
staffId String
staff StaffUser @relation(fields: [staffId], references: [id])
type TransactionType
amountCents Int?
points Int /// positif (crédit) ou négatif (récompense)
rewardId String?
reward Reward? @relation(fields: [rewardId], references: [id])
createdAt DateTime @default(now())
@@index([storeId, createdAt])
@@index([cardId, createdAt])
}
// ── Apple Wallet (service web PassKit) ────────────────────────
model AppleDevice {
id String @id @default(cuid())
deviceLibraryId String @unique
pushToken String
registrations AppleRegistration[]
}
model AppleRegistration {
deviceId String
device AppleDevice @relation(fields: [deviceId], references: [id], onDelete: Cascade)
cardId String
card LoyaltyCard @relation(fields: [cardId], references: [id], onDelete: Cascade)
createdAt DateTime @default(now())
@@id([deviceId, cardId])
}
// ── Facturation ───────────────────────────────────────────────
enum SubscriptionStatus {
INCOMPLETE
ACTIVE
PAST_DUE
CANCELED
}
model Subscription {
id String @id @default(cuid())
storeId String @unique
store Store @relation(fields: [storeId], references: [id], onDelete: Cascade)
stripeCustomerId String? @unique
stripeSubscriptionId String? @unique
status SubscriptionStatus @default(INCOMPLETE)
currentPeriodEnd DateTime?
updatedAt DateTime @updatedAt
}
model Invoice {
id String @id @default(cuid())
/// Numérotation continue, sans trou : MEP-2026-000001
number String @unique
sequence Int @unique
storeId String
store Store @relation(fields: [storeId], references: [id])
stripeInvoiceId String? @unique
amountCents Int
periodStart DateTime
periodEnd DateTime
issuedAt DateTime @default(now())
paidAt DateTime?
pdfPath String?
}

23
backend/prisma/seed.ts Normal file
View file

@ -0,0 +1,23 @@
import { PrismaClient } from '@prisma/client';
import * as argon2 from 'argon2';
/** Crée (ou met à jour) le compte admin à partir de SEED_ADMIN_EMAIL / SEED_ADMIN_PASSWORD. */
async function main() {
// ts-node ne lit pas .env (seule la CLI Prisma le fait).
try {
process.loadEnvFile();
} catch {
/* pas de .env : variables déjà dans l'environnement */
}
const email = process.env.SEED_ADMIN_EMAIL?.toLowerCase();
const password = process.env.SEED_ADMIN_PASSWORD;
if (!email || !password || password.length < 12) {
throw new Error('SEED_ADMIN_EMAIL et SEED_ADMIN_PASSWORD (12 caractères min.) sont requis.');
}
const prisma = new PrismaClient();
const passwordHash = await argon2.hash(password);
await prisma.admin.upsert({ where: { email }, update: { passwordHash }, create: { email, passwordHash } });
console.log(`Admin prêt : ${email}`);
await prisma.$disconnect();
}
main();

View file

@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';
import { StoresController } from './stores/stores.controller';
import { StoresService } from './stores/stores.service';
import { CardDesignController } from './card-design/card-design.controller';
import { CardDesignService } from './card-design/card-design.service';
import { StaffController } from './staff/staff.controller';
import { StaffService } from './staff/staff.service';
/** Back-office : magasins, design des cartes, comptes du personnel. */
@Module({
controllers: [StoresController, CardDesignController, StaffController],
providers: [StoresService, CardDesignService, StaffService],
})
export class AdminModule {}

22
backend/src/app.module.ts Normal file
View file

@ -0,0 +1,22 @@
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { APP_GUARD } from '@nestjs/core';
import { ThrottlerGuard, ThrottlerModule } from '@nestjs/throttler';
import configuration from './config/configuration';
import { PrismaModule } from './prisma/prisma.module';
import { AuthModule } from './auth/auth.module';
import { AdminModule } from './admin.module';
import { HealthController } from './health.controller';
@Module({
imports: [
ConfigModule.forRoot({ isGlobal: true, load: [configuration] }),
ThrottlerModule.forRoot([{ ttl: 60_000, limit: 120 }]),
PrismaModule,
AuthModule,
AdminModule,
],
controllers: [HealthController],
providers: [{ provide: APP_GUARD, useClass: ThrottlerGuard }],
})
export class AppModule {}

View file

@ -0,0 +1,37 @@
import { Body, Controller, Get, HttpCode, Post, UseGuards } from '@nestjs/common';
import { Throttle } from '@nestjs/throttler';
import { AuthService } from './auth.service';
import { LoginDto, RefreshDto } from './dto/login.dto';
import { CurrentUser, JwtAuthGuard } from '../common/guards';
import { JwtPayload } from '../common/auth.types';
@Controller('auth')
export class AuthController {
constructor(private auth: AuthService) {}
@Post('admin/login')
@HttpCode(200)
@Throttle({ default: { limit: 5, ttl: 60_000 } })
loginAdmin(@Body() dto: LoginDto) {
return this.auth.loginAdmin(dto.email, dto.password);
}
@Post('staff/login')
@HttpCode(200)
@Throttle({ default: { limit: 10, ttl: 60_000 } })
loginStaff(@Body() dto: LoginDto) {
return this.auth.loginStaff(dto.email, dto.password);
}
@Post('refresh')
@HttpCode(200)
refresh(@Body() dto: RefreshDto) {
return this.auth.refresh(dto.refreshToken);
}
@Get('me')
@UseGuards(JwtAuthGuard)
me(@CurrentUser() user: JwtPayload) {
return user;
}
}

View file

@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { JwtStrategy } from './jwt.strategy';
@Module({
imports: [PassportModule, JwtModule.register({})],
controllers: [AuthController],
providers: [AuthService, JwtStrategy],
})
export class AuthModule {}

View file

@ -0,0 +1,95 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import * as argon2 from 'argon2';
import { PrismaService } from '../prisma/prisma.service';
import { JwtPayload } from '../common/auth.types';
type RefreshPayload = { sub: string; kind: 'admin' | 'staff'; v: number };
@Injectable()
export class AuthService {
constructor(
private prisma: PrismaService,
private jwt: JwtService,
private config: ConfigService,
) {}
async loginAdmin(email: string, password: string) {
const admin = await this.prisma.admin.findUnique({ where: { email: email.toLowerCase() } });
if (!admin || !(await argon2.verify(admin.passwordHash, password))) {
throw new UnauthorizedException('Identifiants invalides');
}
return this.issue({ sub: admin.id, kind: 'admin' }, 0);
}
async loginStaff(email: string, password: string) {
const staff = await this.prisma.staffUser.findUnique({
where: { email: email.toLowerCase() },
include: { store: { select: { id: true, name: true, status: true } } },
});
// Message identique dans tous les cas : ne révèle pas quels comptes existent.
if (!staff || !(await argon2.verify(staff.passwordHash, password))) {
throw new UnauthorizedException('Identifiants invalides');
}
if (!staff.active) throw new UnauthorizedException('Compte désactivé');
if (staff.store.status === 'SUSPENDED' || staff.store.status === 'CLOSED') {
throw new UnauthorizedException('Magasin suspendu');
}
const tokens = await this.issue(
{ sub: staff.id, kind: 'staff', storeId: staff.storeId, role: staff.role },
staff.tokenVersion,
);
return {
...tokens,
user: {
id: staff.id,
displayName: staff.displayName,
role: staff.role,
store: { id: staff.store.id, name: staff.store.name },
},
};
}
async refresh(refreshToken: string) {
let p: RefreshPayload;
try {
p = await this.jwt.verifyAsync<RefreshPayload>(refreshToken, {
secret: this.config.get('jwt.refreshSecret'),
});
} catch {
throw new UnauthorizedException();
}
if (p.kind === 'admin') {
const admin = await this.prisma.admin.findUnique({ where: { id: p.sub } });
if (!admin) throw new UnauthorizedException();
return this.issue({ sub: admin.id, kind: 'admin' }, 0);
}
const staff = await this.prisma.staffUser.findUnique({ where: { id: p.sub }, include: { store: true } });
if (
!staff?.active ||
staff.tokenVersion !== p.v ||
staff.store.status === 'SUSPENDED' ||
staff.store.status === 'CLOSED'
) {
throw new UnauthorizedException();
}
return this.issue(
{ sub: staff.id, kind: 'staff', storeId: staff.storeId, role: staff.role },
staff.tokenVersion,
);
}
private async issue(payload: JwtPayload, version: number) {
const accessToken = await this.jwt.signAsync(payload, {
secret: this.config.get('jwt.accessSecret'),
expiresIn: this.config.get('jwt.accessTtl'),
});
const refresh: RefreshPayload = { sub: payload.sub, kind: payload.kind, v: version };
const refreshToken = await this.jwt.signAsync(refresh, {
secret: this.config.get('jwt.refreshSecret'),
expiresIn: this.config.get('jwt.refreshTtl'),
});
return { accessToken, refreshToken };
}
}

View file

@ -0,0 +1,15 @@
import { IsEmail, IsString, MinLength } from 'class-validator';
export class LoginDto {
@IsEmail()
email!: string;
@IsString()
@MinLength(8)
password!: string;
}
export class RefreshDto {
@IsString()
refreshToken!: string;
}

View file

@ -0,0 +1,30 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PrismaService } from '../prisma/prisma.service';
import { JwtPayload } from '../common/auth.types';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(config: ConfigService, private prisma: PrismaService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: config.get<string>('jwt.accessSecret')!,
});
}
/** Un employé désactivé ou un magasin suspendu perd l'accès immédiatement. */
async validate(payload: JwtPayload): Promise<JwtPayload> {
if (payload.kind === 'staff') {
const staff = await this.prisma.staffUser.findUnique({
where: { id: payload.sub },
select: { active: true, store: { select: { status: true } } },
});
if (!staff?.active || staff.store.status === 'SUSPENDED' || staff.store.status === 'CLOSED') {
throw new UnauthorizedException();
}
}
return payload;
}
}

View file

@ -0,0 +1,50 @@
import {
BadRequestException,
Body,
Controller,
Get,
Param,
ParseEnumPipe,
Post,
Put,
UploadedFile,
UseGuards,
UseInterceptors,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { AdminGuard, JwtAuthGuard } from '../common/guards';
import { CardDesignService, ImageKind } from './card-design.service';
import { SaveCardDesignDto } from './dto/card-design.dto';
enum ImageKindParam {
logo = 'logo',
strip = 'strip',
}
@Controller('admin/stores/:storeId/card-design')
@UseGuards(JwtAuthGuard, AdminGuard)
export class CardDesignController {
constructor(private designs: CardDesignService) {}
@Get()
get(@Param('storeId') storeId: string) {
return this.designs.get(storeId);
}
@Put()
save(@Param('storeId') storeId: string, @Body() dto: SaveCardDesignDto) {
return this.designs.save(storeId, dto);
}
/** Logo et bandeau : PNG, 2 Mo max (le recadrage se fait côté admin). */
@Post('images/:kind')
@UseInterceptors(FileInterceptor('file', { limits: { fileSize: 2 * 1024 * 1024 } }))
upload(
@Param('storeId') storeId: string,
@Param('kind', new ParseEnumPipe(ImageKindParam, { exceptionFactory: () => new BadRequestException('Type d’image inconnu') }))
kind: ImageKind,
@UploadedFile() file: Express.Multer.File | undefined,
) {
return this.designs.saveImage(storeId, kind, file);
}
}

View file

@ -0,0 +1,104 @@
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { mkdir, unlink, writeFile } from 'fs/promises';
import { join } from 'path';
import { randomBytes } from 'crypto';
import { PrismaService } from '../prisma/prisma.service';
import { SaveCardDesignDto } from './dto/card-design.dto';
export type ImageKind = 'logo' | 'strip';
const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
export const UPLOADS_DIR = join(process.cwd(), 'uploads');
@Injectable()
export class CardDesignService {
constructor(private prisma: PrismaService) {}
async get(storeId: string) {
await this.ensureStore(storeId);
const design = await this.prisma.cardDesign.findUnique({
where: { storeId },
include: { rewards: { orderBy: { cost: 'asc' } } },
});
return design ? this.present(design) : null;
}
/**
* Enregistre le design et synchronise les récompenses. Une récompense déjà
* utilisée dans une opération n'est jamais supprimée (l'historique y fait
* référence) : retirée de la liste, elle est seulement désactivée.
*/
async save(storeId: string, dto: SaveCardDesignDto) {
await this.ensureStore(storeId);
const { rewards, pointsPerEuro, ...fields } = dto;
const data = { ...fields, pointsPerEuro: new Prisma.Decimal(pointsPerEuro) };
await this.prisma.$transaction(async (tx) => {
const design = await tx.cardDesign.upsert({
where: { storeId },
create: { ...data, storeId },
update: data,
include: { rewards: { include: { _count: { select: { transactions: true } } } } },
});
const keptIds = new Set(rewards.filter((r) => r.id).map((r) => r.id!));
for (const existing of design.rewards) {
if (keptIds.has(existing.id)) continue;
if (existing._count.transactions > 0) {
await tx.reward.update({ where: { id: existing.id }, data: { active: false } });
} else {
await tx.reward.delete({ where: { id: existing.id } });
}
}
const ownIds = new Set(design.rewards.map((r) => r.id));
for (const r of rewards) {
const values = { label: r.label, cost: r.cost, active: r.active ?? true };
if (r.id) {
if (!ownIds.has(r.id)) throw new BadRequestException('Récompense inconnue');
await tx.reward.update({ where: { id: r.id }, data: values });
} else {
await tx.reward.create({ data: { ...values, cardDesignId: design.id } });
}
}
});
return this.get(storeId);
}
async saveImage(storeId: string, kind: ImageKind, file: Express.Multer.File | undefined) {
if (!file) throw new BadRequestException('Fichier manquant');
// On se fie aux octets, pas au type annoncé par le navigateur.
if (!file.buffer.subarray(0, 8).equals(PNG_SIGNATURE)) {
throw new BadRequestException('Seules les images PNG sont acceptées (format exigé par Apple Wallet)');
}
const design = await this.prisma.cardDesign.findUnique({ where: { storeId } });
if (!design) throw new BadRequestException("Enregistrez d'abord l'identité de la carte");
const dir = join(UPLOADS_DIR, 'stores', storeId);
await mkdir(dir, { recursive: true });
// Nom aléatoire : chaque version a sa propre URL, pas de cache périmé.
const name = `${kind}-${randomBytes(6).toString('hex')}.png`;
await writeFile(join(dir, name), file.buffer);
const field = kind === 'logo' ? 'logoPath' : 'stripPath';
const previous = design[field];
await this.prisma.cardDesign.update({ where: { storeId }, data: { [field]: `stores/${storeId}/${name}` } });
if (previous) await unlink(join(UPLOADS_DIR, previous)).catch(() => undefined);
return this.get(storeId);
}
private async ensureStore(id: string) {
const store = await this.prisma.store.findUnique({ where: { id }, select: { id: true } });
if (!store) throw new NotFoundException('Magasin introuvable');
}
private present(d: Prisma.CardDesignGetPayload<{ include: { rewards: true } }>) {
const { logoPath, stripPath, pointsPerEuro, ...rest } = d;
return {
...rest,
pointsPerEuro: pointsPerEuro.toNumber(),
logoUrl: logoPath ? `/uploads/${logoPath}` : null,
stripUrl: stripPath ? `/uploads/${stripPath}` : null,
};
}
}

View file

@ -0,0 +1,53 @@
import { PointsMode } from '@prisma/client';
import { Transform, Type } from 'class-transformer';
import {
ArrayMaxSize,
IsBoolean,
IsEnum,
IsInt,
IsNumber,
IsOptional,
IsString,
Length,
Matches,
Max,
Min,
ValidateNested,
} from 'class-validator';
const HEX = /^#[0-9A-Fa-f]{6}$/;
const trim = ({ value }: { value: unknown }) => (typeof value === 'string' ? value.trim() : value);
export class RewardDto {
/** Absent = nouvelle récompense. */
@IsOptional() @IsString()
id?: string;
@Transform(trim) @IsString() @Length(2, 60)
label!: string;
@IsInt() @Min(1) @Max(100_000)
cost!: number;
@IsOptional() @IsBoolean()
active?: boolean;
}
export class SaveCardDesignDto {
@Transform(trim) @IsString() @Length(2, 40)
programName!: string;
@Matches(HEX) backgroundColor!: string;
@Matches(HEX) foregroundColor!: string;
@Matches(HEX) labelColor!: string;
@IsEnum(PointsMode)
pointsMode!: PointsMode;
/** Ignoré en mode tampons. */
@IsNumber({ maxDecimalPlaces: 2 }) @Min(0.01) @Max(100)
pointsPerEuro!: number;
@ValidateNested({ each: true }) @Type(() => RewardDto) @ArrayMaxSize(20)
rewards!: RewardDto[];
}

View file

@ -0,0 +1,6 @@
import { StaffRole } from '@prisma/client';
/** Contenu du jeton d'accès. `kind` sépare strictement admin et personnel. */
export type JwtPayload =
| { sub: string; kind: 'admin' }
| { sub: string; kind: 'staff'; storeId: string; role: StaffRole };

View file

@ -0,0 +1,44 @@
import {
CanActivate,
ExecutionContext,
ForbiddenException,
Injectable,
SetMetadata,
createParamDecorator,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { AuthGuard } from '@nestjs/passport';
import { StaffRole } from '@prisma/client';
import { JwtPayload } from './auth.types';
export const JwtAuthGuard = AuthGuard('jwt');
@Injectable()
export class AdminGuard implements CanActivate {
canActivate(ctx: ExecutionContext) {
const user = ctx.switchToHttp().getRequest().user as JwtPayload | undefined;
if (user?.kind !== 'admin') throw new ForbiddenException();
return true;
}
}
export const STAFF_ROLES = 'staffRoles';
/** Restreint une route du personnel à certains rôles (par défaut : tous). */
export const StaffRoles = (...roles: StaffRole[]) => SetMetadata(STAFF_ROLES, roles);
@Injectable()
export class StaffGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(ctx: ExecutionContext) {
const user = ctx.switchToHttp().getRequest().user as JwtPayload | undefined;
if (user?.kind !== 'staff') throw new ForbiddenException();
const roles = this.reflector.getAllAndOverride<StaffRole[]>(STAFF_ROLES, [ctx.getHandler(), ctx.getClass()]);
if (roles?.length && !roles.includes(user.role)) throw new ForbiddenException();
return true;
}
}
export const CurrentUser = createParamDecorator(
(_: unknown, ctx: ExecutionContext) => ctx.switchToHttp().getRequest().user as JwtPayload,
);

View file

@ -0,0 +1,21 @@
/**
* Contrôle de clé d'un SIRET (algorithme de Luhn). Exception connue : les
* établissements de La Poste (SIREN 356000000) suivent une autre règle —
* la somme des chiffres doit être un multiple de 5.
*/
export function isValidSiret(value: string): boolean {
if (!/^\d{14}$/.test(value)) return false;
if (value.startsWith('356000000')) {
return [...value].reduce((s, c) => s + Number(c), 0) % 5 === 0;
}
let sum = 0;
for (let i = 0; i < 14; i++) {
let d = Number(value[i]);
if (i % 2 === 0) {
d *= 2;
if (d > 9) d -= 9;
}
sum += d;
}
return sum % 10 === 0;
}

View file

@ -0,0 +1,11 @@
export default () => ({
env: process.env.NODE_ENV ?? 'development',
port: parseInt(process.env.PORT ?? '3100', 10),
cors: { origins: process.env.CORS_ORIGINS ?? '' },
jwt: {
accessSecret: process.env.JWT_ACCESS_SECRET ?? 'dev-access-secret',
refreshSecret: process.env.JWT_REFRESH_SECRET ?? 'dev-refresh-secret',
accessTtl: process.env.JWT_ACCESS_TTL ?? '15m',
refreshTtl: process.env.JWT_REFRESH_TTL ?? '30d',
},
});

View file

@ -0,0 +1,9 @@
import { Controller, Get } from '@nestjs/common';
@Controller('health')
export class HealthController {
@Get()
check() {
return { ok: true };
}
}

48
backend/src/main.ts Normal file
View file

@ -0,0 +1,48 @@
process.env.TZ = process.env.TZ || 'Europe/Paris';
import { NestFactory } from '@nestjs/core';
import { ValidationPipe } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { NestExpressApplication } from '@nestjs/platform-express';
import helmet from 'helmet';
import { AppModule } from './app.module';
import { UPLOADS_DIR } from './card-design/card-design.service';
/** Même garde-fou que GoSortir : un secret d'exemple en production est public. */
function verifierSecrets(config: ConfigService) {
if (config.get<string>('env') !== 'production') return;
const douteux = Object.entries({
JWT_ACCESS_SECRET: config.get<string>('jwt.accessSecret'),
JWT_REFRESH_SECRET: config.get<string>('jwt.refreshSecret'),
})
.filter(([, v]) => !v || v.startsWith('dev-') || v.startsWith('CHANGE_ME'))
.map(([nom]) => nom);
if (douteux.length) throw new Error(`Secrets absents ou d'exemple en production : ${douteux.join(', ')}.`);
}
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule);
const config = app.get(ConfigService);
verifierSecrets(config);
// Derrière nginx (CloudPanel) : IP réelle via X-Forwarded-For pour les limites de débit.
app.set('trust proxy', 1);
app.enableShutdownHooks();
// cross-origin : l'admin (autre sous-domaine) affiche les logos et bandeaux.
app.use(helmet({ contentSecurityPolicy: false, crossOriginResourcePolicy: { policy: 'cross-origin' } }));
// Logos et bandeaux des cartes (aperçu admin, page d'inscription, génération des pass).
app.useStaticAssets(UPLOADS_DIR, { prefix: '/uploads/' });
app.setGlobalPrefix('api');
app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }));
const origins = (config.get<string>('cors.origins') ?? '')
.split(',')
.map((s) => s.trim())
.filter(Boolean);
app.enableCors({ origin: origins.length ? origins : false, credentials: true });
const port = config.get<number>('port') ?? 3100;
await app.listen(port);
console.log(`MonEspacePro API en écoute sur le port ${port}`);
}
bootstrap();

View file

@ -0,0 +1,6 @@
import { Global, Module } from '@nestjs/common';
import { PrismaService } from './prisma.service';
@Global()
@Module({ providers: [PrismaService], exports: [PrismaService] })
export class PrismaModule {}

View file

@ -0,0 +1,9 @@
import { Injectable, OnModuleInit } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';
@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit {
async onModuleInit() {
await this.$connect();
}
}

View file

@ -0,0 +1,27 @@
import { StaffRole } from '@prisma/client';
import { Transform } from 'class-transformer';
import { IsBoolean, IsEmail, IsEnum, IsOptional, IsString, Length } from 'class-validator';
const trim = ({ value }: { value: unknown }) => (typeof value === 'string' ? value.trim() : value);
export class CreateStaffDto {
@Transform(trim) @IsString() @Length(2, 80)
displayName!: string;
@Transform(trim) @IsEmail()
email!: string;
@IsEnum(StaffRole)
role!: StaffRole;
}
export class UpdateStaffDto {
@IsOptional() @Transform(trim) @IsString() @Length(2, 80)
displayName?: string;
@IsOptional() @IsEnum(StaffRole)
role?: StaffRole;
@IsOptional() @IsBoolean()
active?: boolean;
}

View file

@ -0,0 +1,31 @@
import { Body, Controller, Get, HttpCode, Param, Patch, Post, UseGuards } from '@nestjs/common';
import { AdminGuard, JwtAuthGuard } from '../common/guards';
import { CreateStaffDto, UpdateStaffDto } from './dto/staff.dto';
import { StaffService } from './staff.service';
@Controller('admin/stores/:storeId/staff')
@UseGuards(JwtAuthGuard, AdminGuard)
export class StaffController {
constructor(private staff: StaffService) {}
@Get()
list(@Param('storeId') storeId: string) {
return this.staff.list(storeId);
}
@Post()
create(@Param('storeId') storeId: string, @Body() dto: CreateStaffDto) {
return this.staff.create(storeId, dto);
}
@Patch(':id')
update(@Param('storeId') storeId: string, @Param('id') id: string, @Body() dto: UpdateStaffDto) {
return this.staff.update(storeId, id, dto);
}
@Post(':id/reset-password')
@HttpCode(200)
resetPassword(@Param('storeId') storeId: string, @Param('id') id: string) {
return this.staff.resetPassword(storeId, id);
}
}

View file

@ -0,0 +1,94 @@
import { ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import * as argon2 from 'argon2';
import { randomInt } from 'crypto';
import { PrismaService } from '../prisma/prisma.service';
import { CreateStaffDto, UpdateStaffDto } from './dto/staff.dto';
const PUBLIC_FIELDS = {
id: true,
storeId: true,
email: true,
displayName: true,
role: true,
active: true,
createdAt: true,
} satisfies Prisma.StaffUserSelect;
/** Sans caractères ambigus (0/O, 1/l/I) : il sera recopié à la main. */
const ALPHABET = 'ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789';
function provisionalPassword(length = 12) {
return Array.from({ length }, () => ALPHABET[randomInt(ALPHABET.length)]).join('');
}
@Injectable()
export class StaffService {
constructor(private prisma: PrismaService) {}
async list(storeId: string) {
await this.ensureStore(storeId);
return this.prisma.staffUser.findMany({
where: { storeId },
select: PUBLIC_FIELDS,
orderBy: [{ active: 'desc' }, { role: 'asc' }, { displayName: 'asc' }],
});
}
/** Le mot de passe provisoire n'est renvoyé qu'ici, une seule fois ; il n'est stocké que haché. */
async create(storeId: string, dto: CreateStaffDto) {
await this.ensureStore(storeId);
const password = provisionalPassword();
try {
const staff = await this.prisma.staffUser.create({
data: {
storeId,
email: dto.email.toLowerCase(),
displayName: dto.displayName,
role: dto.role,
passwordHash: await argon2.hash(password),
},
select: PUBLIC_FIELDS,
});
return { ...staff, provisionalPassword: password };
} catch (e) {
if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002') {
throw new ConflictException('Un compte existe déjà avec cet e-mail');
}
throw e;
}
}
async update(storeId: string, id: string, dto: UpdateStaffDto) {
const current = await this.find(storeId, id);
// Désactivation ou changement de rôle : les sessions ouvertes sont révoquées.
const revoke = (dto.active === false && current.active) || (dto.role !== undefined && dto.role !== current.role);
return this.prisma.staffUser.update({
where: { id },
data: { ...dto, ...(revoke && { tokenVersion: { increment: 1 } }) },
select: PUBLIC_FIELDS,
});
}
async resetPassword(storeId: string, id: string) {
await this.find(storeId, id);
const password = provisionalPassword();
const staff = await this.prisma.staffUser.update({
where: { id },
data: { passwordHash: await argon2.hash(password), tokenVersion: { increment: 1 } },
select: PUBLIC_FIELDS,
});
return { ...staff, provisionalPassword: password };
}
private async find(storeId: string, id: string) {
const staff = await this.prisma.staffUser.findFirst({ where: { id, storeId } });
if (!staff) throw new NotFoundException('Employé introuvable');
return staff;
}
private async ensureStore(id: string) {
const store = await this.prisma.store.findUnique({ where: { id }, select: { id: true } });
if (!store) throw new NotFoundException('Magasin introuvable');
}
}

View file

@ -0,0 +1,83 @@
import { PartialType } from '@nestjs/mapped-types';
import { StoreStatus } from '@prisma/client';
import { Transform } from 'class-transformer';
import {
IsEmail,
IsEnum,
IsIn,
IsInt,
IsOptional,
IsString,
Length,
Matches,
Max,
MaxLength,
Min,
Validate,
ValidatorConstraint,
ValidatorConstraintInterface,
} from 'class-validator';
import { isValidSiret } from '../../common/siret.util';
const trim = ({ value }: { value: unknown }) => (typeof value === 'string' ? value.trim() : value);
/** « 123 456 789 00018 » → « 12345678900018 » */
const digitsOnly = ({ value }: { value: unknown }) => (typeof value === 'string' ? value.replace(/\s/g, '') : value);
@ValidatorConstraint({ name: 'siret' })
class SiretConstraint implements ValidatorConstraintInterface {
validate(value: unknown) {
return typeof value === 'string' && isValidSiret(value);
}
defaultMessage() {
return 'SIRET invalide (14 chiffres, clé de contrôle incorrecte)';
}
}
export class CreateStoreDto {
@Transform(trim) @IsString() @Length(2, 120)
name!: string;
@Transform(digitsOnly) @Validate(SiretConstraint)
siret!: string;
@Transform(trim) @IsString() @Length(3, 200)
addressLine!: string;
@Transform(digitsOnly) @Matches(/^\d{5}$/, { message: 'Code postal : 5 chiffres' })
postalCode!: string;
@Transform(trim) @IsString() @Length(1, 120)
city!: string;
@Transform(trim) @IsString() @Length(2, 120)
contactName!: string;
@Transform(trim) @IsEmail()
contactEmail!: string;
@Transform(digitsOnly) @Matches(/^(\+33|0)[1-9]\d{8}$/, { message: 'Téléphone invalide' })
contactPhone!: string;
/** Plafond d'une opération, en euros entiers (converti en centimes). */
@IsInt() @Min(1) @Max(10_000)
maxAmountEuros!: number;
/** Délai minimum entre deux crédits d'un même client, en minutes. */
@IsInt() @Min(0) @Max(24 * 60)
minScanIntervalMin!: number;
}
export class UpdateStoreDto extends PartialType(CreateStoreDto) {}
export class SetStoreStatusDto {
@IsEnum(StoreStatus)
status!: StoreStatus;
}
export class ListStoresQuery {
@IsOptional() @IsString() @MaxLength(100)
q?: string;
@IsOptional() @IsIn(Object.values(StoreStatus))
status?: StoreStatus;
}

View file

@ -0,0 +1,35 @@
import { Body, Controller, Get, Param, Patch, Post, Query, UseGuards } from '@nestjs/common';
import { AdminGuard, JwtAuthGuard } from '../common/guards';
import { CreateStoreDto, ListStoresQuery, SetStoreStatusDto, UpdateStoreDto } from './dto/store.dto';
import { StoresService } from './stores.service';
@Controller('admin/stores')
@UseGuards(JwtAuthGuard, AdminGuard)
export class StoresController {
constructor(private stores: StoresService) {}
@Get()
list(@Query() query: ListStoresQuery) {
return this.stores.list(query);
}
@Post()
create(@Body() dto: CreateStoreDto) {
return this.stores.create(dto);
}
@Get(':id')
get(@Param('id') id: string) {
return this.stores.get(id);
}
@Patch(':id')
update(@Param('id') id: string, @Body() dto: UpdateStoreDto) {
return this.stores.update(id, dto);
}
@Patch(':id/status')
setStatus(@Param('id') id: string, @Body() dto: SetStoreStatusDto) {
return this.stores.setStatus(id, dto.status);
}
}

View file

@ -0,0 +1,119 @@
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { Prisma, Store, StoreStatus } from '@prisma/client';
import { randomBytes } from 'crypto';
import { PrismaService } from '../prisma/prisma.service';
import { CreateStoreDto, ListStoresQuery, UpdateStoreDto } from './dto/store.dto';
/** Transitions autorisées depuis l'admin (la suspension pour impayé viendra de Stripe). */
const TRANSITIONS: Record<StoreStatus, StoreStatus[]> = {
DRAFT: ['ACTIVE', 'CLOSED'],
ACTIVE: ['SUSPENDED', 'CLOSED'],
SUSPENDED: ['ACTIVE', 'CLOSED'],
CLOSED: ['ACTIVE'],
};
@Injectable()
export class StoresService {
constructor(private prisma: PrismaService) {}
async list(query: ListStoresQuery) {
const where: Prisma.StoreWhereInput = {
...(query.status && { status: query.status }),
...(query.q && { OR: [{ name: { contains: query.q } }, { city: { contains: query.q } }] }),
};
const [stores, byStatus] = await Promise.all([
this.prisma.store.findMany({
where,
orderBy: { createdAt: 'desc' },
include: { subscription: { select: { status: true } }, _count: { select: { cards: true } } },
}),
this.prisma.store.groupBy({ by: ['status'], _count: true }),
]);
return {
items: stores.map(({ _count, subscription, ...s }) => ({
...this.present(s),
customers: _count.cards,
subscriptionStatus: subscription?.status ?? null,
})),
counts: Object.fromEntries(byStatus.map((g) => [g.status, g._count])),
};
}
async get(id: string) {
const store = await this.prisma.store.findUnique({
where: { id },
include: {
subscription: true,
_count: { select: { cards: true, staff: true, transactions: true } },
},
});
if (!store) throw new NotFoundException('Magasin introuvable');
const { _count, subscription, ...s } = store;
return { ...this.present(s), counts: _count, subscription };
}
async create(dto: CreateStoreDto) {
const store = await this.prisma.store.create({
data: { ...this.toData(dto), slug: await this.uniqueSlug(dto.name) } as Prisma.StoreCreateInput,
});
return this.present(store);
}
async update(id: string, dto: UpdateStoreDto) {
await this.ensure(id);
// Le slug ne change jamais : il est imprimé sur les QR d'inscription.
const store = await this.prisma.store.update({ where: { id }, data: this.toData(dto) });
return this.present(store);
}
async setStatus(id: string, status: StoreStatus) {
const store = await this.prisma.store.findUnique({ where: { id }, include: { cardDesign: true } });
if (!store) throw new NotFoundException('Magasin introuvable');
if (store.status === status) return this.present(store);
if (!TRANSITIONS[store.status].includes(status)) {
throw new BadRequestException(`Passage de ${store.status} à ${status} impossible`);
}
if (status === 'ACTIVE' && !store.cardDesign) {
throw new BadRequestException("La carte de fidélité doit être conçue avant l'activation");
}
const updated = await this.prisma.store.update({ where: { id }, data: { status } });
return this.present(updated);
}
async ensure(id: string) {
const store = await this.prisma.store.findUnique({ where: { id }, select: { id: true } });
if (!store) throw new NotFoundException('Magasin introuvable');
}
private toData(dto: UpdateStoreDto): Prisma.StoreUpdateInput {
const { maxAmountEuros, minScanIntervalMin, contactEmail, ...rest } = dto;
return {
...rest,
...(contactEmail !== undefined && { contactEmail: contactEmail.toLowerCase() }),
...(maxAmountEuros !== undefined && { maxAmountCents: maxAmountEuros * 100 }),
...(minScanIntervalMin !== undefined && { minScanIntervalSec: minScanIntervalMin * 60 }),
};
}
/** Expose les réglages anti-triche dans les unités saisies dans l'admin. */
private present(s: Store) {
const { maxAmountCents, minScanIntervalSec, ...rest } = s;
return { ...rest, maxAmountEuros: maxAmountCents / 100, minScanIntervalMin: Math.round(minScanIntervalSec / 60) };
}
/** « Boulangerie Le Fournil » → « boulangerie-le-fournil-k3f9 » (suffixe : non devinable, sans collision). */
private async uniqueSlug(name: string) {
const base =
name
.normalize('NFD')
.replace(/[̀-ͯ]/g, '')
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, '')
.slice(0, 40) || 'magasin';
for (;;) {
const slug = `${base}-${randomBytes(3).toString('hex').slice(0, 4)}`;
if (!(await this.prisma.store.findUnique({ where: { slug }, select: { id: true } }))) return slug;
}
}
}

23
backend/tsconfig.json Normal file
View file

@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "ES2021",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": true,
"noImplicitAny": true,
"strictBindCallApply": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"esModuleInterop": true,
"resolveJsonModule": true
}
}

1
brand/favicon.svg Normal file
View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="7" fill="#0E7A66"/><g transform="translate(4.6 5.5) scale(0.36)"><path d="M12 54V32a9 9 0 0 1 18 0v22M30 32a9 9 0 0 1 18 0v22" fill="none" stroke="#FFFFFF" stroke-width="9"/><circle cx="51" cy="12" r="7" fill="#F2B544"/></g></svg>

After

Width:  |  Height:  |  Size: 324 B

1
brand/symbole-blanc.svg Normal file
View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0.5 -2 64 64"><path d="M12 54V32a9 9 0 0 1 18 0v22M30 32a9 9 0 0 1 18 0v22" fill="none" stroke="#FFFFFF" stroke-width="8"/><circle cx="51" cy="12" r="6" fill="#F2B544"/></svg>

After

Width:  |  Height:  |  Size: 225 B

1
brand/symbole-mono.svg Normal file
View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0.5 -2 64 64"><path d="M12 54V32a9 9 0 0 1 18 0v22M30 32a9 9 0 0 1 18 0v22" fill="none" stroke="#1C1C19" stroke-width="8"/><circle cx="51" cy="12" r="6" fill="#1C1C19"/></svg>

After

Width:  |  Height:  |  Size: 225 B

1
brand/symbole-sombre.svg Normal file
View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0.5 -2 64 64"><path d="M12 54V32a9 9 0 0 1 18 0v22M30 32a9 9 0 0 1 18 0v22" fill="none" stroke="#3DC3A2" stroke-width="8"/><circle cx="51" cy="12" r="6" fill="#F2B544"/></svg>

After

Width:  |  Height:  |  Size: 225 B

1
brand/symbole.svg Normal file
View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0.5 -2 64 64"><path d="M12 54V32a9 9 0 0 1 18 0v22M30 32a9 9 0 0 1 18 0v22" fill="none" stroke="#0E7A66" stroke-width="8"/><circle cx="51" cy="12" r="6" fill="#F2B544"/></svg>

After

Width:  |  Height:  |  Size: 225 B

View file

@ -0,0 +1,66 @@
# Prompts Claude Design — MonEspacePro
À coller un par un dans Claude Design. Le prompt 0 pose l'identité ; les suivants s'y réfèrent.
---
## 0. Design system MonEspacePro
Crée le design system de « MonEspacePro », un SaaS français de carte de fidélité dématérialisée pour les petits commerces (boulangeries, coiffeurs, cafés, boutiques). Ton : professionnel, rassurant, simple, pensé pour des commerçants non techniques. Livre : logo texte + monogramme « MEP », palette (couleur primaire, neutres, succès/alerte/erreur), typographie (une sans-serif lisible), boutons, champs de formulaire, badges de statut (Brouillon, Actif, Suspendu, Fermé), tableaux, cartes, toasts. Clair et sombre. Tout en français.
---
## 1. Admin web — magasins (desktop)
Avec le design system MonEspacePro, maquette l'interface admin web (desktop, 1440 px) :
1. Connexion admin (e-mail + mot de passe).
2. Liste des magasins : tableau avec nom, ville, statut (badge), nombre de clients, abonnement (actif / impayé), date de création ; recherche et filtre par statut ; bouton « Nouveau magasin ».
3. Formulaire de création de magasin : nom, adresse, code postal, ville, SIRET (14 chiffres, validation), nom du contact, e-mail, téléphone ; réglages anti-triche (plafond de montant par opération en €, délai minimum entre deux crédits d'un même client en minutes).
4. Fiche magasin avec onglets : Infos, Carte de fidélité, Employés, Clients, Opérations, Facturation. Bandeau d'alerte rouge si le magasin est suspendu pour impayé, avec bouton « Renvoyer le lien de paiement ».
5. Onglet Employés : liste (nom, e-mail, rôle Gérant/Employé, actif), modale de création avec génération d'un mot de passe provisoire.
6. Onglet Facturation : statut de l'abonnement (10 €/mois), bouton « Envoyer le lien d'abonnement Stripe », liste des factures (numéro MEP-2026-000001, période, montant, payée/impayée, PDF).
---
## 2. Admin web — assistant de design de carte (desktop)
Maquette l'assistant de conception de carte de fidélité, en étapes, avec à droite un APERÇU EN DIRECT de la carte telle qu'elle apparaîtra dans Apple Wallet (format « Store Card » : logo en haut à gauche, bandeau horizontal 1125×432, solde de points en champ principal, QR code en bas) et un bouton pour basculer sur l'aperçu Google Wallet (format « Loyalty »).
Étapes :
1. Identité : nom du programme, upload logo (PNG carré), upload bandeau (avec recadrage au bon ratio).
2. Couleurs : fond, texte, libellés — avec sélecteurs, couleurs suggérées extraites du logo, et alerte de contraste insuffisant.
3. Règle de points : choix entre « Points selon le montant » (X points par euro dépensé) et « Tampons » (1 tampon par passage) ; exemple calculé en direct (« Un panier de 23,50 € = 23 points »).
4. Récompenses : liste éditable (libellé + coût en points/tampons), ex. « Café offert — 10 tampons ».
5. Récapitulatif : aperçu final, QR d'inscription imprimable (affichette A5/A6 pour le comptoir aux couleurs du magasin : « Scannez pour obtenir votre carte de fidélité »), bouton « Activer ».
---
## 3. Page d'inscription client (mobile web)
Maquette la page web mobile (390 px) qui s'ouvre quand un client scanne le QR au comptoir. Elle prend les couleurs, le logo et le bandeau DU MAGASIN (montre deux variantes : une boulangerie aux tons chauds, un barbier noir et doré) ; MonEspacePro n'apparaît qu'en petit en pied de page.
Écrans :
1. Accueil : logo, bandeau, nom du programme, promesse (« Gagnez 1 point par euro — café offert à 10 tampons »), formulaire prénom + e-mail, case de consentement RGPD non pré-cochée avec lien vers la politique de confidentialité, bouton « Créer ma carte ».
2. Succès : aperçu de la carte, boutons officiels « Ajouter à Apple Wallet » et « Ajouter à Google Wallet » (afficher le bon selon l'appareil, l'autre en lien secondaire).
3. Carte déjà existante pour cet e-mail : message + renvoi du lien par e-mail.
4. Magasin suspendu / programme indisponible : message neutre et poli.
---
## 4. App mobile Pro (iOS/Android, employés)
Maquette l'app mobile « MonEspacePro Pro » pour les employés d'un commerce (Expo/React Native, 390 px). Usage au comptoir, rapide, gros boutons, utilisable d'une main.
Écrans :
1. Connexion (e-mail + mot de passe), nom du magasin affiché après connexion.
2. Accueil : gros bouton « Scanner une carte », résumé du jour (opérations, points distribués), accès Historique.
3. Scanner : caméra plein écran avec cadre de visée, lampe torche.
4. Fiche client après scan : prénom, solde, dernière visite ; deux actions : « Créditer » et « Utiliser une récompense ».
5. Créditer : pavé numérique pour le montant en €, points calculés en direct, bouton « Valider » ; en mode tampons, simple confirmation « +1 tampon ».
6. Récompenses : liste des récompenses, celles accessibles mises en avant, les autres grisées avec « encore X points ».
7. Confirmation : animation de succès, nouveau solde, « Le Wallet du client est mis à jour ».
8. Erreurs anti-triche : « Montant supérieur au plafond (500 €) », « Carte déjà créditée il y a 2 min — réessayez dans 3 min », « Carte d'un autre magasin ».
9. Historique : liste des opérations (heure, client, type, montant, points, employé), filtres jour/semaine ; le gérant voit tous les employés, l'employé seulement les siennes.
---
## 5. Facture PDF
Maquette une facture A4 en français, sobre, émise par « EI Tony Averty — MonEspacePro », SIRET 100 142 819 00018, adressée à un commerçant (raison sociale, adresse, SIRET). Contenu : numéro de facture (MEP-2026-000042), date d'émission, période facturée, ligne « Abonnement MonEspacePro — 1 magasin — mois d'octobre 2026 — 10,00 € », total 10,00 €, mention « TVA non applicable, art. 293 B du CGI », mention « Payée le … par prélèvement », conditions de paiement, pénalités de retard (taux légal), « Indemnité forfaitaire pour frais de recouvrement : 40 € ».