MonEspacePro/pro/app/stats.tsx

214 lines
9.8 KiB
TypeScript

import { useCallback, useState } from 'react';
import { ActivityIndicator, 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, Card, T } from '../src/ui';
import { font, useColors } from '../src/theme';
import { Icon, IconName } from '../src/icons';
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 jours'], [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]));
// Le passage est mis en avant ; les autres indicateurs en tuiles.
const tiles: [IconName, string, string, string?][] = k
? [
['sparkle', 'Nouvelles cartes', String(k.newCards), `${k.cardsTotal} au total`],
['users', 'Clients actifs', String(k.activeCustomers), `${k.visitsPerCustomer} passage(s) / client`],
['repeat', 'Clients fidèles', k.returningRate === null ? '—' : `${k.returningRate} %`, 'venus 2 fois ou plus'],
['gift', 'Récompenses', String(k.rewardsRedeemed), 'utilisées'],
...(data!.pointsMode === 'AMOUNT'
? ([
['euro', 'Achats', euros(k.revenueCents), k.averageBasketCents === null ? '' : `panier moyen ${euros(k.averageBasketCents)}`],
] as [IconName, string, string, string][])
: []),
]
: [];
const trend = k?.visitsChange ?? null;
return (
<ScrollView contentContainerStyle={{ padding: 20, gap: 18 }} bounces={false} overScrollMode="never">
{/* Période : contrôle segmenté */}
<View accessibilityRole="tablist" style={{ flexDirection: 'row', backgroundColor: c.surface, borderRadius: 14, padding: 4, borderWidth: 1, borderColor: c.border }}>
{PERIODS.map(([d, label]) => (
<Pressable
key={d}
accessibilityRole="tab"
accessibilityState={{ selected: days === d }}
onPress={() => setDays(d)}
style={{ flex: 1, paddingVertical: 10, borderRadius: 10, alignItems: 'center', backgroundColor: days === d ? c.primary : 'transparent' }}
>
<T style={{ fontFamily: font.bold, fontSize: 15, color: days === d ? c.onPrimary : c.text }}>{label}</T>
</Pressable>
))}
</View>
{error && <Banner tone="error">{error}</Banner>}
{!data || !k ? (
!error && <T v="muted">Chargement…</T>
) : (
<>
{/* Passages : chiffre clé, évolution et graphique */}
<View style={{ backgroundColor: c.primary, borderRadius: 22, padding: 20, gap: 14 }}>
<View style={{ flexDirection: 'row', alignItems: 'flex-start', justifyContent: 'space-between' }}>
<View>
<T style={{ color: c.onPrimary, opacity: 0.85, fontFamily: font.semibold, fontSize: 14 }}>Passages en magasin</T>
<T v="big" style={{ color: c.onPrimary }}>{k.visits}</T>
</View>
{trend !== null && (
<View style={{ paddingHorizontal: 10, paddingVertical: 4, borderRadius: 999, backgroundColor: 'rgba(255,255,255,0.18)' }}>
<T style={{ color: c.onPrimary, fontFamily: font.bold, fontSize: 14 }}>{pctText(trend)}</T>
</View>
)}
</View>
<View style={{ flexDirection: 'row', alignItems: 'flex-end', height: 90, 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 : 1,
backgroundColor: i === data.series.length - 1 ? c.accent : 'rgba(255,255,255,0.55)',
borderRadius: 2,
}}
/>
))}
</View>
<View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
<T style={{ color: c.onPrimary, opacity: 0.8, fontSize: 12 }}>{data.series[0]?.label}</T>
<T style={{ color: c.onPrimary, opacity: 0.8, fontSize: 12 }}>{data.series[data.series.length - 1]?.label}</T>
</View>
{data.busiest && (
<T style={{ color: c.onPrimary, fontSize: 14 }}>
Créneau le plus fréquenté : <T style={{ color: c.onPrimary, fontFamily: font.bold, fontSize: 14 }}>{data.busiest}</T>
</T>
)}
</View>
<View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 12 }}>
{tiles.map(([icon, label, value, hint]) => (
<Card key={label} style={{ width: '47%', flexGrow: 1, padding: 14, gap: 4 }}>
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 6 }}>
<Icon name={icon} size={16} color={c.primary} />
<T v="muted" style={{ fontSize: 13 }} numberOfLines={1}>{label}</T>
</View>
<T style={{ fontFamily: font.extrabold, fontSize: 26 }}>{value}</T>
{!!hint && <T v="muted" style={{ fontSize: 12 }}>{hint}</T>}
</Card>
))}
</View>
{data.top.length > 0 && (
<Card style={{ padding: 16, gap: 12 }}>
<T v="h2">Meilleurs clients</T>
{data.top.slice(0, 5).map((t, i) => (
<View key={i} style={{ flexDirection: 'row', alignItems: 'center', gap: 12 }}>
<View style={{ width: 36, height: 36, borderRadius: 18, backgroundColor: i < 3 ? c.warnBg : c.surface2, alignItems: 'center', justifyContent: 'center' }}>
<T style={{ fontSize: i < 3 ? 18 : 14, fontFamily: font.bold, color: c.text3 }}>{i + 1}</T>
</View>
<T v="label" style={{ flex: 1 }} numberOfLines={1}>{t.firstName}</T>
<T v="muted" style={{ fontSize: 14 }}>
{t.visits} passage{t.visits > 1 ? 's' : ''}
{data.pointsMode === 'AMOUNT' ? ` · ${euros(t.amountCents)}` : ''}
</T>
</View>
))}
</Card>
)}
<Card style={{ padding: 16, gap: 12 }}>
<T v="h2">Exports</T>
<T v="muted" style={{ fontSize: 14 }}>Fichier CSV (ouvrable avec Excel), envoyé uniquement par e-mail au dirigeant de la société.</T>
{(
[
['customers', 'idCard', 'Fichier clients', 'Tous les clients et leur solde'],
['transactions', 'receipt', 'Opérations de la période', `Les ${PERIODS.find(([d]) => d === days)?.[1]} sélectionnés`],
] as const
).map(([kind, icon, title, sub]) => (
<Pressable key={kind} accessibilityRole="button" disabled={!!sending} onPress={() => exportCsv(kind)}>
{({ pressed }) => (
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 12, padding: 12, borderRadius: 14, backgroundColor: pressed ? c.primarySoft : c.surface2 }}>
<Icon name={icon} size={22} color={c.primary} />
<View style={{ flex: 1 }}>
<T v="label">{title}</T>
<T v="muted" style={{ fontSize: 13 }}>{sub}</T>
</View>
{sending === kind ? <ActivityIndicator /> : <T style={{ color: c.primary, fontFamily: font.bold }}>Recevoir</T>}
</View>
)}
</Pressable>
))}
</Card>
</>
)}
</ScrollView>
);
}