Les données se rechargent à l'ouverture de chaque écran. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
164 lines
6.9 KiB
TypeScript
164 lines
6.9 KiB
TypeScript
import { useCallback, useState } from 'react';
|
|
import { Alert, Pressable, 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 (dirigeants, 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 [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' || e.code === 'MODULE_DISABLED')) 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">Le module Statistiques & export n'est pas actif : activez-le dans Modules, ou contactez MonEspacePro s'il n'est pas inclus dans votre 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 }}
|
|
bounces={false}
|
|
overScrollMode="never"
|
|
>
|
|
<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é uniquement par e-mail au dirigeant de la société.</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>
|
|
);
|
|
}
|