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 (
{up ? '▲' : '▼'} {Math.abs(value).toLocaleString('fr-FR')} %
);
}
function Kpi({ icon, label, value, hint, change }: { icon: string; label: string; value: string; hint?: string; change?: number | null }) {
return (
{icon}{label}
{value}
{change !== undefined && }
{hint && {hint}}
);
}
/** 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 (
);
}
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 (
|
{hours.map((h) => {h}h | )}
{heat.weekdays.map((d, i) => (
| {d} |
{hours.map((h) => {
const n = heat.values[i][h];
return (
|
);
})}
))}
);
}
export function StatsTab({ storeId, storeSlug }: { storeId: string; storeSlug: string }) {
const [days, setDays] = useState(30);
const [data, setData] = useState(null);
const [error, setError] = useState(null);
const [busy, setBusy] = useState(null);
useEffect(() => {
setError(null);
api.get(`/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 (
<>
{PERIODS.map(([d, label]) => (
))}
{error && {error}
}
{data && !data.allowed && Ce magasin n'a pas la formule Pro : il ne voit pas ces statistiques dans son app (vous, si).
}
{!data || !k ? (
!error && Chargement…
) : (
<>
{data.pointsMode === 'AMOUNT' && (
)}
Fréquentation
Passages
Nouvelles cartes
Heures d'affluence
{data.busiest ? `Créneau le plus fréquenté : ${data.busiest}.` : 'Pas encore de passage sur la période.'}
Meilleurs clients
{data.top.length === 0 ? (
Pas encore de passage sur la période.
) : (
| Rang |
Client |
Passages |
{data.pointsMode === 'AMOUNT' && Achats | }
Solde |
{data.top.map((t, i) => (
| {['🥇', '🥈', '🥉'][i] ?? i + 1} |
{t.firstName} |
{t.visits} |
{data.pointsMode === 'AMOUNT' && {euros(t.amountCents)} | }
{t.balance} |
))}
)}
>
)}
>
);
}