Statistiques avancées et export CSV (formule Pro)

- Indicateurs sur 30 j / 3 mois / 12 mois : passages et nouvelles cartes (vs période
  précédente), clients actifs et fidèles, achats et panier moyen, récompenses, adoption Apple Wallet
- Courbe de fréquentation, heures d'affluence (jour × heure, heure de Paris), meilleurs clients
- Exports CSV clients et opérations (format Excel FR, formules neutralisées)
- Admin : onglet Statistiques avec téléchargement ; app Pro : écran gérant, export envoyé par e-mail

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Tony AVERTY 2026-10-07 10:47:48 +02:00
parent b75e396bde
commit 9096e799f4
11 changed files with 775 additions and 2 deletions

View file

@ -0,0 +1,219 @@
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({ label, value, hint, change }: { 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 }}>{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="row" style={{ gap: 8 }}>
{PERIODS.map(([d, label]) => (
<button key={d} type="button" className="chip" 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…' : 'Exporter les clients (CSV)'}</button>
<button className="btn secondary" disabled={!!busy} onClick={() => download('transactions')}>{busy === 'transactions' ? 'Export…' : 'Exporter les 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 label="Passages" value={nf(k.visits)} change={k.visitsChange} hint="vs période précédente" />
<Kpi label="Nouvelles cartes" value={nf(k.newCards)} change={k.newCardsChange} hint={`${nf(k.cardsTotal)} au total`} />
<Kpi label="Clients actifs" value={nf(k.activeCustomers)} hint={`${k.visitsPerCustomer.toLocaleString('fr-FR')} passage(s) par client`} />
<Kpi label="Clients fidèles" value={k.returningRate === null ? '—' : `${k.returningRate.toLocaleString('fr-FR')} %`} hint="venus au moins 2 fois" />
{data.pointsMode === 'AMOUNT' && (
<Kpi label="Achats enregistrés" value={euros(k.revenueCents)} hint={k.averageBasketCents === null ? undefined : `panier moyen ${euros(k.averageBasketCents)}`} />
)}
<Kpi label="Récompenses" value={nf(k.rewardsRedeemed)} hint={`${nf(k.pointsGiven)} ${unit} distribués`} />
<Kpi label="Cartes dans Apple Wallet" value={k.appleWalletRate === null ? '—' : `${k.appleWalletRate.toLocaleString('fr-FR')} %`} hint="iPhone joignables" />
</div>
<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
&nbsp;&nbsp;
<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>
<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">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>{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>
</>
)}
</>
);
}

View file

@ -7,12 +7,14 @@ import { CardWizard } from './CardWizard';
import { StaffTab } from './StaffTab';
import { BillingTab } from './BillingTab';
import { CampaignsTab } from './CampaignsTab';
import { StatsTab } from './StatsTab';
const TABS = [
['infos', 'Infos'],
['carte', 'Carte de fidélité'],
['employes', 'Employés'],
['campagnes', 'Fidélisation'],
['statistiques', 'Statistiques'],
['facturation', 'Facturation'],
] as const;
@ -112,6 +114,7 @@ export function StorePage() {
<Route path="carte" element={<CardWizard store={store} onSaved={reload} />} />
<Route path="employes" element={<StaffTab storeId={store.id} />} />
<Route path="campagnes" element={<CampaignsTab storeId={store.id} storeName={store.name} />} />
<Route path="statistiques" element={<StatsTab storeId={store.id} storeSlug={store.slug} />} />
<Route path="facturation" element={<BillingTab storeId={store.id} contactEmail={store.contactEmail} onChange={reload} />} />
</Routes>
</>

View file

@ -19,6 +19,7 @@ import { BirthdaysModule } from './birthdays/birthdays.controller';
import { ReviewsModule } from './reviews/reviews.controller';
import { ReferralsModule } from './referrals/referrals.controller';
import { ReferralsCoreModule } from './referrals/referrals.service';
import { StatsModule } from './stats/stats.controller';
import { HealthController } from './health.controller';
@Module({
@ -41,6 +42,7 @@ import { HealthController } from './health.controller';
ReviewsModule,
ReferralsCoreModule,
ReferralsModule,
StatsModule,
],
controllers: [HealthController],
providers: [{ provide: APP_GUARD, useClass: ThrottlerGuard }],

View file

@ -0,0 +1,117 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
const TYPE_LABEL = { CREDIT: 'Crédit', REDEEM: 'Récompense', ADJUST: 'Ajustement', REJECTED: 'Refusé' } as const;
const REJECT_LABEL = { AMOUNT_OVER_LIMIT: 'Montant au-dessus du plafond', TOO_SOON: 'Trop rapproché', INSUFFICIENT_BALANCE: 'Solde insuffisant' } as const;
/**
* Cellule CSV : guillemets doublés, et neutralisation des formules
* (une cellule qui commence par = + - @ serait exécutée par Excel).
*/
export function cell(value: unknown): string {
if (value === null || value === undefined) return '';
let s = value instanceof Date ? formatDate(value) : String(value);
if (/^[=+\-@\t\r]/.test(s)) s = `'${s}`;
return /[";\n\r]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
}
/** CSV au format Excel français : séparateur « ; », BOM UTF-8, fins de ligne CRLF. */
export function toCsv(header: string[], rows: unknown[][]) {
const lines = [header, ...rows].map((r) => r.map(cell).join(';'));
return Buffer.from(`${lines.join('\r\n')}\r\n`, 'utf8');
}
function formatDate(d: Date) {
return d.toLocaleString('fr-FR', { timeZone: 'Europe/Paris', dateStyle: 'short', timeStyle: 'short' });
}
const euros = (cents: number | null | undefined) => (cents === null || cents === undefined ? '' : (cents / 100).toFixed(2).replace('.', ','));
@Injectable()
export class ExportService {
constructor(private prisma: PrismaService) {}
private async storeOf(storeId: string) {
const store = await this.prisma.store.findUnique({ where: { id: storeId }, select: { slug: true } });
if (!store) throw new NotFoundException('Magasin introuvable');
return store;
}
/** Fichier clients : une ligne par carte. */
async customers(storeId: string) {
const store = await this.storeOf(storeId);
const cards = await this.prisma.loyaltyCard.findMany({
where: { storeId },
orderBy: { createdAt: 'asc' },
include: {
customer: true,
referredBy: { select: { customer: { select: { firstName: true } } } },
devices: { select: { deviceId: true }, take: 1 },
},
});
const totals = await this.prisma.transaction.groupBy({
by: ['cardId'],
where: { storeId, type: 'CREDIT' },
_count: { _all: true },
_sum: { amountCents: true },
});
const byCard = new Map(totals.map((t) => [t.cardId, t]));
const rows = cards.map((c) => {
const t = byCard.get(c.id);
const birthday = c.customer.birthMonth && c.customer.birthDay ? `${String(c.customer.birthDay).padStart(2, '0')}/${String(c.customer.birthMonth).padStart(2, '0')}` : '';
return [
c.customer.firstName,
c.customer.email,
birthday,
c.balance,
t?._count._all ?? 0,
euros(t?._sum.amountCents ?? null),
c.createdAt,
c.lastCreditAt,
c.devices.length ? 'Oui' : 'Non',
c.referredBy?.customer.firstName ?? '',
c.serial,
];
});
return {
filename: `clients-${store.slug}-${new Date().toISOString().slice(0, 10)}.csv`,
content: toCsv(
['Prénom', 'E-mail', 'Anniversaire', 'Solde', 'Passages', 'Total dépensé (€)', 'Inscrit le', 'Dernier passage', 'Apple Wallet', 'Parrainé par', 'N° de carte'],
rows,
),
count: rows.length,
};
}
/** Fichier des opérations de la période (jours). */
async transactions(storeId: string, days: number) {
const store = await this.storeOf(storeId);
const from = new Date(Date.now() - days * 24 * 3600_000);
const txs = await this.prisma.transaction.findMany({
where: { storeId, createdAt: { gte: from } },
orderBy: { createdAt: 'asc' },
include: {
staff: { select: { displayName: true } },
reward: { select: { label: true } },
card: { select: { serial: true, customer: { select: { firstName: true, email: true } } } },
},
});
const rows = txs.map((t) => [
t.createdAt,
TYPE_LABEL[t.type],
t.card.customer.firstName,
t.card.customer.email,
euros(t.amountCents),
t.points,
t.balanceAfter,
t.reward?.label ?? '',
t.rejectReason ? REJECT_LABEL[t.rejectReason] : '',
t.staff.displayName,
t.card.serial,
]);
return {
filename: `operations-${store.slug}-${days}j-${new Date().toISOString().slice(0, 10)}.csv`,
content: toCsv(['Date', 'Type', 'Client', 'E-mail', 'Montant (€)', 'Points', 'Solde après', 'Récompense', 'Motif du refus', 'Employé', 'N° de carte'], rows),
count: rows.length,
};
}
}

View file

@ -0,0 +1,109 @@
import { Body, Controller, Get, HttpCode, Module, Param, ParseIntPipe, Post, Query, Res, UseGuards } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Throttle } from '@nestjs/throttler';
import { IsIn } from 'class-validator';
import type { Response } from 'express';
import { EntitlementsService } from '../billing/entitlements.service';
import { JwtPayload } from '../common/auth.types';
import { AdminGuard, CurrentUser, JwtAuthGuard, StaffGuard, StaffRoles } from '../common/guards';
import { emailLayout, esc } from '../mail/email-layout';
import { MailService } from '../mail/mail.service';
import { PrismaService } from '../prisma/prisma.service';
import { ExportService } from './export.service';
import { PERIODS, StatsService } from './stats.service';
const period = (days: number) => (PERIODS.includes(days) ? days : 30);
function sendCsv(res: Response, file: { filename: string; content: Buffer }) {
res
.status(200)
.type('text/csv; charset=utf-8')
.setHeader('Content-Disposition', `attachment; filename="${file.filename}"`)
.setHeader('Cache-Control', 'no-store')
.send(file.content);
}
class ExportDto {
@IsIn(['customers', 'transactions'])
kind!: 'customers' | 'transactions';
@IsIn(PERIODS)
days!: number;
}
@Controller('admin/stores/:id')
@UseGuards(JwtAuthGuard, AdminGuard)
export class AdminStatsController {
constructor(private stats: StatsService, private exports: ExportService, private entitlements: EntitlementsService) {}
@Get('stats')
async get(@Param('id') id: string, @Query('days', new ParseIntPipe({ optional: true })) days = 30) {
const [data, allowed] = await Promise.all([this.stats.compute(id, period(days)), this.entitlements.can(id, 'advancedStats')]);
return { ...data, allowed };
}
@Get('export/customers')
async customers(@Param('id') id: string, @Res() res: Response) {
sendCsv(res, await this.exports.customers(id));
}
@Get('export/transactions')
async transactions(@Param('id') id: string, @Query('days', new ParseIntPipe({ optional: true })) days = 30, @Res() res: Response) {
sendCsv(res, await this.exports.transactions(id, period(days)));
}
}
/** App Pro : statistiques et exports pour les gérants (formule Pro). */
@Controller('staff')
@UseGuards(JwtAuthGuard, StaffGuard)
@StaffRoles('MANAGER')
export class StaffStatsController {
constructor(
private stats: StatsService,
private exports: ExportService,
private entitlements: EntitlementsService,
private prisma: PrismaService,
private mail: MailService,
private config: ConfigService,
) {}
@Get('stats')
async get(@CurrentUser() user: JwtPayload, @Query('days', new ParseIntPipe({ optional: true })) days = 30) {
if (user.kind !== 'staff') throw new Error('StaffGuard manquant');
await this.entitlements.require(user.storeId, 'advancedStats');
return this.stats.compute(user.storeId, period(days));
}
/** Le fichier part par e-mail au gérant : rien à stocker sur le téléphone. */
@Post('export')
@HttpCode(200)
@Throttle({ default: { limit: 5, ttl: 10 * 60_000 } })
async export(@CurrentUser() user: JwtPayload, @Body() dto: ExportDto) {
if (user.kind !== 'staff') throw new Error('StaffGuard manquant');
await this.entitlements.require(user.storeId, 'csvExport');
const staff = await this.prisma.staffUser.findUniqueOrThrow({ where: { id: user.sub }, include: { store: { select: { name: true } } } });
const file = dto.kind === 'customers' ? await this.exports.customers(user.storeId) : await this.exports.transactions(user.storeId, dto.days);
const what = dto.kind === 'customers' ? 'Fichier clients' : `Opérations des ${dto.days} derniers jours`;
const subject = `${what} — ${staff.store.name}`;
const text = `Bonjour ${staff.displayName},\n\nVoici votre export « ${what} » (${file.count} lignes), en pièce jointe au format CSV (ouvrable avec Excel).\n\nCe fichier contient des données personnelles de vos clients : conservez-le en lieu sûr et ne le partagez pas.\n\nMonEspacePro`;
const html = emailLayout({
webUrl: this.config.get('webUrl')!,
preheader: `${what} : ${file.count} lignes en pièce jointe.`,
eyebrow: 'Export',
title: what,
paragraphs: [
`Bonjour ${esc(staff.displayName)},`,
`Voici votre export pour <strong>${esc(staff.store.name)}</strong> : <strong>${file.count} lignes</strong>, en pièce jointe au format CSV (ouvrable avec Excel).`,
'Ce fichier contient des données personnelles de vos clients : conservez-le en lieu sûr et ne le partagez pas.',
],
});
await this.mail.sendWithAttachment(staff.email, subject, text, html, { filename: file.filename, content: file.content });
return { sentTo: staff.email, count: file.count };
}
}
@Module({
controllers: [AdminStatsController, StaffStatsController],
providers: [StatsService, ExportService],
})
export class StatsModule {}

View file

@ -0,0 +1,148 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
export const PERIODS = [30, 90, 365];
const DAY = 24 * 3600_000;
const WEEKDAYS = ['lun.', 'mar.', 'mer.', 'jeu.', 'ven.', 'sam.', 'dim.'];
const MONTHS = ['janv.', 'févr.', 'mars', 'avr.', 'mai', 'juin', 'juil.', 'août', 'sept.', 'oct.', 'nov.', 'déc.'];
const PARIS = new Intl.DateTimeFormat('en-GB', {
timeZone: 'Europe/Paris',
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
weekday: 'short',
hour12: false,
});
/** Date locale de Paris : année, mois, jour, heure (0-23), jour de semaine (0 = lundi). */
export function paris(d: Date) {
const p = Object.fromEntries(PARIS.formatToParts(d).map((x) => [x.type, x.value]));
return {
year: +p.year,
month: +p.month,
day: +p.day,
hour: +p.hour % 24,
weekday: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'].indexOf(p.weekday),
};
}
const pad = (n: number) => String(n).padStart(2, '0');
/** Regroupement de la courbe : jour (30 j), semaine (90 j), mois (365 j). */
function bucket(d: Date, days: number) {
const p = paris(d);
if (days <= 30) return { key: `${p.year}-${pad(p.month)}-${pad(p.day)}`, label: `${p.day} ${MONTHS[p.month - 1]}` };
if (days <= 90) {
// Lundi de la semaine (date de Paris).
const monday = new Date(Date.UTC(p.year, p.month - 1, p.day - p.weekday));
return { key: monday.toISOString().slice(0, 10), label: `sem. du ${monday.getUTCDate()} ${MONTHS[monday.getUTCMonth()]}` };
}
return { key: `${p.year}-${pad(p.month)}`, label: `${MONTHS[p.month - 1]} ${String(p.year).slice(2)}` };
}
const pct = (a: number, b: number) => (b ? Math.round((a / b) * 1000) / 10 : null);
/**
* Statistiques avancées d'un magasin sur une période : fréquentation, fidélité,
* chiffre déclaré, récompenses, heures d'affluence, meilleurs clients.
*/
@Injectable()
export class StatsService {
constructor(private prisma: PrismaService) {}
async compute(storeId: string, days: number, now = new Date()) {
const store = await this.prisma.store.findUnique({ where: { id: storeId }, include: { cardDesign: { select: { pointsMode: true } } } });
if (!store) throw new NotFoundException('Magasin introuvable');
const from = new Date(now.getTime() - days * DAY);
const prevFrom = new Date(from.getTime() - days * DAY);
const [txs, cardsTotal, newCards, prevNewCards, prevVisits, appleCards, cardsCreated] = await Promise.all([
this.prisma.transaction.findMany({
where: { storeId, createdAt: { gte: from }, type: { in: ['CREDIT', 'REDEEM'] } },
select: { cardId: true, type: true, amountCents: true, points: true, createdAt: true },
}),
this.prisma.loyaltyCard.count({ where: { storeId } }),
this.prisma.loyaltyCard.count({ where: { storeId, createdAt: { gte: from } } }),
this.prisma.loyaltyCard.count({ where: { storeId, createdAt: { gte: prevFrom, lt: from } } }),
this.prisma.transaction.count({ where: { storeId, type: 'CREDIT', createdAt: { gte: prevFrom, lt: from } } }),
this.prisma.loyaltyCard.count({ where: { storeId, devices: { some: {} } } }),
this.prisma.loyaltyCard.findMany({ where: { storeId, createdAt: { gte: from } }, select: { createdAt: true } }),
]);
const credits = txs.filter((t) => t.type === 'CREDIT');
const redeems = txs.filter((t) => t.type === 'REDEEM');
const visitsByCard = new Map<string, { visits: number; cents: number }>();
for (const t of credits) {
const v = visitsByCard.get(t.cardId) ?? { visits: 0, cents: 0 };
v.visits++;
v.cents += t.amountCents ?? 0;
visitsByCard.set(t.cardId, v);
}
const active = visitsByCard.size;
const returning = [...visitsByCard.values()].filter((v) => v.visits >= 2).length;
const revenueCents = credits.reduce((s, t) => s + (t.amountCents ?? 0), 0);
const withAmount = credits.filter((t) => t.amountCents !== null).length;
// Courbe : passages et nouvelles cartes, toutes les cases de la période (même vides).
const series = new Map<string, { label: string; visits: number; newCards: number }>();
for (let t = from.getTime(); t <= now.getTime(); t += DAY) {
const b = bucket(new Date(t), days);
if (!series.has(b.key)) series.set(b.key, { label: b.label, visits: 0, newCards: 0 });
}
const add = (d: Date, field: 'visits' | 'newCards') => {
const b = bucket(d, days);
const s = series.get(b.key) ?? { label: b.label, visits: 0, newCards: 0 };
s[field]++;
series.set(b.key, s);
};
credits.forEach((t) => add(t.createdAt, 'visits'));
cardsCreated.forEach((c) => add(c.createdAt, 'newCards'));
// Affluence : jour de semaine × heure.
const heat = Array.from({ length: 7 }, () => Array<number>(24).fill(0));
for (const t of credits) {
const p = paris(t.createdAt);
heat[p.weekday][p.hour]++;
}
const busiest = heat
.flatMap((row, d) => row.map((n, h) => ({ n, d, h })))
.sort((a, b) => b.n - a.n)[0];
// Meilleurs clients de la période.
const topIds = [...visitsByCard.entries()].sort((a, b) => b[1].visits - a[1].visits || b[1].cents - a[1].cents).slice(0, 10);
const topCards = await this.prisma.loyaltyCard.findMany({
where: { id: { in: topIds.map(([id]) => id) } },
select: { id: true, balance: true, customer: { select: { firstName: true } } },
});
const top = topIds.map(([id, v]) => {
const c = topCards.find((x) => x.id === id);
return { firstName: c?.customer.firstName ?? '—', visits: v.visits, amountCents: v.cents, balance: c?.balance ?? 0 };
});
return {
days,
pointsMode: store.cardDesign?.pointsMode ?? 'AMOUNT',
kpis: {
cardsTotal,
newCards,
newCardsChange: pct(newCards - prevNewCards, prevNewCards),
visits: credits.length,
visitsChange: pct(credits.length - prevVisits, prevVisits),
activeCustomers: active,
returningRate: pct(returning, active),
visitsPerCustomer: active ? Math.round((credits.length / active) * 10) / 10 : 0,
revenueCents,
averageBasketCents: withAmount ? Math.round(revenueCents / withAmount) : null,
pointsGiven: credits.reduce((s, t) => s + t.points, 0),
rewardsRedeemed: redeems.length,
appleWalletRate: pct(appleCards, cardsTotal),
},
series: [...series.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([, v]) => v),
heatmap: { weekdays: WEEKDAYS, values: heat },
busiest: busiest && busiest.n > 0 ? `${WEEKDAYS[busiest.d]} ${busiest.h} h–${busiest.h + 1} h` : null,
top,
};
}
}

View file

@ -53,6 +53,7 @@ function Navigator() {
<Stack.Screen name="birthday" options={{ title: "Offre d'anniversaire" }} />
<Stack.Screen name="reviews" options={{ title: 'Avis Google' }} />
<Stack.Screen name="referral" options={{ title: 'Parrainage' }} />
<Stack.Screen name="stats" options={{ title: 'Statistiques' }} />
<Stack.Screen name="loyalty" options={{ title: 'Fidélisation' }} />
</Stack.Protected>
</Stack>

View file

@ -113,6 +113,7 @@ export default function Home() {
<View style={{ flex: 1 }} />
{isManager && <Button label="Fidélisation" variant="secondary" onPress={() => router.push('/loyalty')} />}
{isManager && <Button label="Statistiques" variant="secondary" onPress={() => router.push('/stats')} />}
<Button label="Historique des opérations" variant="secondary" onPress={() => router.push('/history')} />
</ScrollView>
</SafeAreaView>

173
pro/app/stats.tsx Normal file
View file

@ -0,0 +1,173 @@
import { useCallback, useState } from 'react';
import { Alert, Pressable, RefreshControl, ScrollView, View } from 'react-native';
import { useFocusEffect } from 'expo-router';
import { api, ApiError } from '../src/api';
import { describe } from '../src/errors';
import { Banner, Button, Card, T } from '../src/ui';
import { font, useColors } from '../src/theme';
interface Stats {
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;
rewardsRedeemed: number;
};
series: { label: string; visits: number; newCards: number }[];
busiest: string | null;
top: { firstName: string; visits: number; amountCents: number }[];
}
const PERIODS: [number, string][] = [[30, '30 j'], [90, '3 mois'], [365, '12 mois']];
const euros = (c: number) => (c / 100).toLocaleString('fr-FR', { style: 'currency', currency: 'EUR', maximumFractionDigits: 0 });
const pctText = (n: number | null) => (n === null ? '' : `${n >= 0 ? '▲' : '▼'} ${Math.abs(n)} %`);
/** Statistiques (gérants, formule Pro) et exports CSV envoyés par e-mail. */
export default function StatsScreen() {
const c = useColors();
const [days, setDays] = useState(30);
const [data, setData] = useState<Stats | null>(null);
const [error, setError] = useState<string | null>(null);
const [locked, setLocked] = useState(false);
const [refreshing, setRefreshing] = useState(false);
const [sending, setSending] = useState<string | null>(null);
const load = useCallback(async (d: number) => {
try {
setError(null);
setData(await api.get<Stats>(`/api/staff/stats?days=${d}`));
} catch (e) {
const info = describe(e);
if (e instanceof ApiError && e.code === 'PLAN_REQUIRED') setLocked(true);
else setError(info.detail);
}
}, []);
useFocusEffect(
useCallback(() => {
load(days);
}, [load, days]),
);
async function exportCsv(kind: 'customers' | 'transactions') {
setSending(kind);
try {
const r = await api.post<{ sentTo: string; count: number }>('/api/staff/export', { kind, days });
Alert.alert('Export envoyé', `${r.count} lignes envoyées par e-mail à ${r.sentTo}.`);
} catch (e) {
Alert.alert('Export impossible', describe(e).detail);
} finally {
setSending(null);
}
}
if (locked) {
return (
<View style={{ padding: 20 }}>
<Banner tone="warn">Les statistiques et exports sont inclus dans la formule Pro. Contactez MonEspacePro pour changer de formule.</Banner>
</View>
);
}
const k = data?.kpis;
const max = Math.max(1, ...(data?.series.map((s) => s.visits) ?? [1]));
const tiles: [string, string, string?][] = k
? [
['Passages', String(k.visits), pctText(k.visitsChange)],
['Nouvelles cartes', String(k.newCards), `${k.cardsTotal} au total`],
['Clients actifs', String(k.activeCustomers), `${k.visitsPerCustomer} passage(s)/client`],
['Clients fidèles', k.returningRate === null ? '—' : `${k.returningRate} %`, 'venus 2 fois ou plus'],
...(data!.pointsMode === 'AMOUNT'
? ([['Achats', euros(k.revenueCents), k.averageBasketCents === null ? '' : `panier ${euros(k.averageBasketCents)}`]] as [string, string, string][])
: []),
['Récompenses', String(k.rewardsRedeemed)],
]
: [];
return (
<ScrollView
contentContainerStyle={{ padding: 20, gap: 16 }}
refreshControl={
<RefreshControl
refreshing={refreshing}
onRefresh={async () => {
setRefreshing(true);
await load(days);
setRefreshing(false);
}}
/>
}
>
<View style={{ flexDirection: 'row', gap: 8 }}>
{PERIODS.map(([d, label]) => (
<Pressable
key={d}
accessibilityRole="button"
accessibilityState={{ selected: days === d }}
onPress={() => setDays(d)}
style={{ paddingVertical: 10, paddingHorizontal: 16, borderRadius: 999, borderWidth: 1, borderColor: days === d ? c.primary : c.border, backgroundColor: days === d ? c.primarySoft : c.surface }}
>
<T style={{ fontFamily: font.semibold, color: days === d ? c.primary : c.text }}>{label}</T>
</Pressable>
))}
</View>
{error && <Banner tone="error">{error}</Banner>}
{!data ? (
!error && <T v="muted">Chargement…</T>
) : (
<>
<View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 12 }}>
{tiles.map(([label, value, hint]) => (
<Card key={label} style={{ width: '47%', flexGrow: 1, padding: 14, gap: 2 }}>
<T v="muted" style={{ fontSize: 13 }}>{label}</T>
<T style={{ fontFamily: font.extrabold, fontSize: 24 }}>{value}</T>
{!!hint && <T v="muted" style={{ fontSize: 12 }}>{hint}</T>}
</Card>
))}
</View>
<Card style={{ padding: 16, gap: 10 }}>
<T v="label">Passages</T>
<View style={{ flexDirection: 'row', alignItems: 'flex-end', height: 120, gap: 2 }} accessibilityLabel="Graphique des passages sur la période">
{data.series.map((s, i) => (
<View key={i} style={{ flex: 1, height: `${(s.visits / max) * 100}%`, minHeight: s.visits ? 3 : 0, backgroundColor: c.primary, borderRadius: 2 }} />
))}
</View>
<View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
<T v="muted" style={{ fontSize: 12 }}>{data.series[0]?.label}</T>
<T v="muted" style={{ fontSize: 12 }}>{data.series[data.series.length - 1]?.label}</T>
</View>
{data.busiest && <T v="muted">Créneau le plus fréquenté : {data.busiest}</T>}
</Card>
{data.top.length > 0 && (
<Card style={{ padding: 16, gap: 8 }}>
<T v="label">Meilleurs clients</T>
{data.top.slice(0, 5).map((t, i) => (
<View key={i} style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
<T>{i + 1}. {t.firstName}</T>
<T v="muted">
{t.visits} passage{t.visits > 1 ? 's' : ''}
{data.pointsMode === 'AMOUNT' ? ` · ${euros(t.amountCents)}` : ''}
</T>
</View>
))}
</Card>
)}
<T v="h2">Exports</T>
<T v="muted">Le fichier CSV (ouvrable avec Excel) est envoyé sur votre adresse e-mail.</T>
<Button label="Recevoir le fichier clients" variant="secondary" loading={sending === 'customers'} disabled={!!sending} onPress={() => exportCsv('customers')} />
<Button label="Recevoir les opérations de la période" variant="secondary" loading={sending === 'transactions'} disabled={!!sending} onPress={() => exportCsv('transactions')} />
</>
)}
</ScrollView>
);
}

View file

@ -29,7 +29,7 @@ const MARKETING = {
{ label: 'Offre d’anniversaire' },
{ label: 'Collecte d’avis Google' },
{ label: 'Parrainage' },
{ label: 'Statistiques avancées et export CSV', soon: true },
{ label: 'Statistiques avancées et export CSV' },
],
},
RESEAU: {

View file

@ -122,7 +122,7 @@
<li><svg class="ico"><use href="#i-check"/></svg><span>Offre d’anniversaire</span></li>
<li><svg class="ico"><use href="#i-check"/></svg><span>Collecte d’avis Google</span></li>
<li><svg class="ico"><use href="#i-check"/></svg><span>Parrainage</span></li>
<li class="soon"><svg class="ico"><use href="#i-check"/></svg><span>Statistiques avancées et export CSV <span class="soon-tag">Bientôt</span></span></li>
<li><svg class="ico"><use href="#i-check"/></svg><span>Statistiques avancées et export CSV</span></li>
</ul>
</div>
<div class="cd plan">