Période en contrôle segmenté, exports à pictogramme, indicateurs à pictogramme, fréquentation et heures d'affluence côte à côte sur grand écran, meilleurs clients avec rang et podium. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
223 lines
10 KiB
TypeScript
223 lines
10 KiB
TypeScript
import { useEffect, useState } from 'react';
|
||
import { api, downloadFile } from '../api';
|
||
|
||
interface Stats {
|
||
allowed: boolean;
|
||
days: number;
|
||
pointsMode: 'AMOUNT' | 'STAMP';
|
||
kpis: {
|
||
cardsTotal: number;
|
||
newCards: number;
|
||
newCardsChange: number | null;
|
||
visits: number;
|
||
visitsChange: number | null;
|
||
activeCustomers: number;
|
||
returningRate: number | null;
|
||
visitsPerCustomer: number;
|
||
revenueCents: number;
|
||
averageBasketCents: number | null;
|
||
pointsGiven: number;
|
||
rewardsRedeemed: number;
|
||
appleWalletRate: number | null;
|
||
};
|
||
series: { label: string; visits: number; newCards: number }[];
|
||
heatmap: { weekdays: string[]; values: number[][] };
|
||
busiest: string | null;
|
||
top: { firstName: string; visits: number; amountCents: number; balance: number }[];
|
||
}
|
||
|
||
const PERIODS: [number, string][] = [[30, '30 jours'], [90, '3 mois'], [365, '12 mois']];
|
||
const euros = (c: number) => (c / 100).toLocaleString('fr-FR', { style: 'currency', currency: 'EUR', maximumFractionDigits: c >= 100000 ? 0 : 2 });
|
||
const nf = (n: number) => n.toLocaleString('fr-FR');
|
||
|
||
function Change({ value }: { value: number | null }) {
|
||
if (value === null) return null;
|
||
const up = value >= 0;
|
||
return (
|
||
<span style={{ fontSize: 13, fontWeight: 700, color: up ? 'var(--ok)' : 'var(--err)' }}>
|
||
{up ? '▲' : '▼'} {Math.abs(value).toLocaleString('fr-FR')} %
|
||
</span>
|
||
);
|
||
}
|
||
|
||
function Kpi({ icon, label, value, hint, change }: { icon: string; label: string; value: string; hint?: string; change?: number | null }) {
|
||
return (
|
||
<div className="card" style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 4 }}>
|
||
<span className="muted" style={{ fontSize: 14, display: 'flex', gap: 8, alignItems: 'center' }}><span aria-hidden="true">{icon}</span>{label}</span>
|
||
<span style={{ fontSize: 26, fontWeight: 800 }}>{value}</span>
|
||
<span style={{ display: 'flex', gap: 8, alignItems: 'baseline' }}>
|
||
{change !== undefined && <Change value={change} />}
|
||
{hint && <span className="muted" style={{ fontSize: 13 }}>{hint}</span>}
|
||
</span>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
/** Barres : passages (plein) et nouvelles cartes (clair). */
|
||
function Bars({ series }: { series: Stats['series'] }) {
|
||
const max = Math.max(1, ...series.map((s) => Math.max(s.visits, s.newCards)));
|
||
const w = 100 / series.length;
|
||
const every = Math.ceil(series.length / 8);
|
||
return (
|
||
<svg viewBox="0 0 100 46" preserveAspectRatio="none" style={{ width: '100%', height: 220 }} role="img" aria-label="Passages et nouvelles cartes sur la période">
|
||
{series.map((s, i) => (
|
||
<g key={i}>
|
||
<title>{`${s.label} : ${s.visits} passage(s), ${s.newCards} nouvelle(s) carte(s)`}</title>
|
||
<rect x={i * w + w * 0.1} y={40 - (s.visits / max) * 38} width={w * 0.45} height={(s.visits / max) * 38} fill="var(--primary)" />
|
||
<rect x={i * w + w * 0.55} y={40 - (s.newCards / max) * 38} width={w * 0.35} height={(s.newCards / max) * 38} fill="var(--primary-soft)" stroke="var(--primary)" strokeWidth={0.1} />
|
||
{i % every === 0 && (
|
||
<text x={i * w + w / 2} y={45} fontSize={2.2} textAnchor="middle" fill="currentColor" opacity={0.6}>{s.label}</text>
|
||
)}
|
||
</g>
|
||
))}
|
||
<line x1={0} x2={100} y1={40} y2={40} stroke="var(--border)" strokeWidth={0.2} />
|
||
</svg>
|
||
);
|
||
}
|
||
|
||
function Heatmap({ heat }: { heat: Stats['heatmap'] }) {
|
||
const hours = Array.from({ length: 15 }, (_, i) => i + 7); // 7 h – 21 h
|
||
const max = Math.max(1, ...heat.values.flat());
|
||
return (
|
||
<div className="table-scroll">
|
||
<table style={{ borderCollapse: 'separate', borderSpacing: 3, minWidth: 560 }}>
|
||
<thead>
|
||
<tr>
|
||
<th />
|
||
{hours.map((h) => <th key={h} style={{ fontSize: 12, fontWeight: 500, padding: 0, textAlign: 'center' }}>{h}h</th>)}
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
{heat.weekdays.map((d, i) => (
|
||
<tr key={d}>
|
||
<th scope="row" style={{ fontSize: 13, fontWeight: 600, padding: '0 8px 0 0' }}>{d}</th>
|
||
{hours.map((h) => {
|
||
const n = heat.values[i][h];
|
||
return (
|
||
<td
|
||
key={h}
|
||
title={`${d} ${h} h : ${n} passage(s)`}
|
||
style={{ padding: 0, height: 26, borderRadius: 4, background: n ? `color-mix(in srgb, var(--primary) ${Math.round(15 + (n / max) * 85)}%, transparent)` : 'var(--surface-2)' }}
|
||
/>
|
||
);
|
||
})}
|
||
</tr>
|
||
))}
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
export function StatsTab({ storeId, storeSlug }: { storeId: string; storeSlug: string }) {
|
||
const [days, setDays] = useState(30);
|
||
const [data, setData] = useState<Stats | null>(null);
|
||
const [error, setError] = useState<string | null>(null);
|
||
const [busy, setBusy] = useState<string | null>(null);
|
||
|
||
useEffect(() => {
|
||
setError(null);
|
||
api.get<Stats>(`/api/admin/stores/${storeId}/stats?days=${days}`).then(setData).catch((e) => setError(e.message));
|
||
}, [storeId, days]);
|
||
|
||
async function download(kind: 'customers' | 'transactions') {
|
||
setBusy(kind);
|
||
try {
|
||
const date = new Date().toISOString().slice(0, 10);
|
||
if (kind === 'customers') await downloadFile(`/api/admin/stores/${storeId}/export/customers`, `clients-${storeSlug}-${date}.csv`);
|
||
else await downloadFile(`/api/admin/stores/${storeId}/export/transactions?days=${days}`, `operations-${storeSlug}-${days}j-${date}.csv`);
|
||
} catch (e) {
|
||
setError((e as Error).message);
|
||
} finally {
|
||
setBusy(null);
|
||
}
|
||
}
|
||
|
||
const k = data?.kpis;
|
||
const unit = data?.pointsMode === 'STAMP' ? 'tampons' : 'points';
|
||
|
||
return (
|
||
<>
|
||
<div className="row between" style={{ alignItems: 'center' }}>
|
||
<div role="group" aria-label="Période" className="s-seg">
|
||
{PERIODS.map(([d, label]) => (
|
||
<button key={d} type="button" aria-pressed={days === d} onClick={() => setDays(d)}>{label}</button>
|
||
))}
|
||
</div>
|
||
<div className="row" style={{ gap: 8 }}>
|
||
<button className="btn secondary" disabled={!!busy} onClick={() => download('customers')}>{busy === 'customers' ? 'Export…' : '📇 Clients (CSV)'}</button>
|
||
<button className="btn secondary" disabled={!!busy} onClick={() => download('transactions')}>{busy === 'transactions' ? 'Export…' : '🧾 Opérations (CSV)'}</button>
|
||
</div>
|
||
</div>
|
||
{error && <div className="alert error" role="alert">{error}</div>}
|
||
{data && !data.allowed && <div className="alert warn">Ce magasin n'a pas la formule Pro : il ne voit pas ces statistiques dans son app (vous, si).</div>}
|
||
{!data || !k ? (
|
||
!error && <p className="muted">Chargement…</p>
|
||
) : (
|
||
<>
|
||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(190px, 1fr))', gap: 12 }}>
|
||
<Kpi icon="🚶" label="Passages" value={nf(k.visits)} change={k.visitsChange} hint="vs période précédente" />
|
||
<Kpi icon="🆕" label="Nouvelles cartes" value={nf(k.newCards)} change={k.newCardsChange} hint={`${nf(k.cardsTotal)} au total`} />
|
||
<Kpi icon="👥" label="Clients actifs" value={nf(k.activeCustomers)} hint={`${k.visitsPerCustomer.toLocaleString('fr-FR')} passage(s) par client`} />
|
||
<Kpi icon="🔁" label="Clients fidèles" value={k.returningRate === null ? '—' : `${k.returningRate.toLocaleString('fr-FR')} %`} hint="venus au moins 2 fois" />
|
||
{data.pointsMode === 'AMOUNT' && (
|
||
<Kpi icon="💶" label="Achats enregistrés" value={euros(k.revenueCents)} hint={k.averageBasketCents === null ? undefined : `panier moyen ${euros(k.averageBasketCents)}`} />
|
||
)}
|
||
<Kpi icon="🎁" label="Récompenses" value={nf(k.rewardsRedeemed)} hint={`${nf(k.pointsGiven)} ${unit} distribués`} />
|
||
<Kpi icon="📱" label="Cartes dans Apple Wallet" value={k.appleWalletRate === null ? '—' : `${k.appleWalletRate.toLocaleString('fr-FR')} %`} hint="iPhone joignables" />
|
||
</div>
|
||
|
||
<div className="stats-pair">
|
||
<section className="card">
|
||
<h2>Fréquentation</h2>
|
||
<p className="muted" style={{ marginTop: 0, fontSize: 14 }}>
|
||
<span style={{ display: 'inline-block', width: 10, height: 10, background: 'var(--primary)', borderRadius: 2 }} /> Passages
|
||
|
||
<span style={{ display: 'inline-block', width: 10, height: 10, background: 'var(--primary-soft)', border: '1px solid var(--primary)', borderRadius: 2 }} /> Nouvelles cartes
|
||
</p>
|
||
<Bars series={data.series} />
|
||
</section>
|
||
|
||
<section className="card">
|
||
<h2>Heures d'affluence</h2>
|
||
<p className="muted" style={{ marginTop: 0 }}>{data.busiest ? `Créneau le plus fréquenté : ${data.busiest}.` : 'Pas encore de passage sur la période.'}</p>
|
||
<Heatmap heat={data.heatmap} />
|
||
</section>
|
||
</div>
|
||
|
||
<section className="card">
|
||
<h2>Meilleurs clients</h2>
|
||
{data.top.length === 0 ? (
|
||
<p className="muted" style={{ margin: 0 }}>Pas encore de passage sur la période.</p>
|
||
) : (
|
||
<div className="table-scroll">
|
||
<table>
|
||
<thead>
|
||
<tr>
|
||
<th scope="col" style={{ width: 56 }}>Rang</th>
|
||
<th scope="col">Client</th>
|
||
<th scope="col" className="num">Passages</th>
|
||
{data.pointsMode === 'AMOUNT' && <th scope="col" className="num">Achats</th>}
|
||
<th scope="col" className="num">Solde</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
{data.top.map((t, i) => (
|
||
<tr key={i}>
|
||
<td><span className={`rank${i < 3 ? ' top' : ''}`}>{['🥇', '🥈', '🥉'][i] ?? i + 1}</span></td>
|
||
<td style={{ fontWeight: 600 }}>{t.firstName}</td>
|
||
<td className="num">{t.visits}</td>
|
||
{data.pointsMode === 'AMOUNT' && <td className="num">{euros(t.amountCents)}</td>}
|
||
<td className="num">{t.balance}</td>
|
||
</tr>
|
||
))}
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
)}
|
||
</section>
|
||
</>
|
||
)}
|
||
</>
|
||
);
|
||
}
|