MonEspacePro/pro/app/history.tsx
Tony AVERTY 6725358a7c App Pro (Expo) et API du comptoir avec anti-triche
- API /staff : profil, scan d'une carte, crédit (montant ou tampon),
  récompenses, historique (gérant : tout le magasin, employé : le sien),
  résumé du jour
- Anti-triche côté serveur : carte du bon magasin, plafond de montant,
  délai minimum entre deux crédits (atomique, scans simultanés compris),
  tentatives refusées journalisées avec l'employé
- App Expo SDK 54 / Expo Router : connexion, accueil, scanner QR avec
  lampe, fiche client, pavé numérique, récompenses, confirmation, erreurs,
  historique ; icônes générées depuis le logo

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 12:50:59 +02:00

134 lines
5.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useCallback, useEffect, useState } from 'react';
import { ActivityIndicator, FlatList, Pressable, View } from 'react-native';
import { api, Operation } from '../src/api';
import { useSession, useStore } from '../src/session';
import { Banner, T, euros, unit } from '../src/ui';
import { font, useColors } from '../src/theme';
type Period = 'today' | 'week';
const REASON: Record<string, string> = {
AMOUNT_OVER_LIMIT: 'Refusé : plafond dépassé',
TOO_SOON: 'Refusé : délai entre deux crédits',
INSUFFICIENT_BALANCE: 'Refusé : solde insuffisant',
};
/** Historique (maquettes 9a/9b) : le gérant voit tout, l'employé ses opérations. */
export default function History() {
const c = useColors();
const { me } = useSession();
const store = useStore();
const isManager = me?.role === 'MANAGER';
const [period, setPeriod] = useState<Period>('today');
const [items, setItems] = useState<Operation[]>([]);
const [cursor, setCursor] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const load = useCallback(
async (reset: boolean) => {
setLoading(true);
setError(null);
try {
const q = new URLSearchParams({ period });
if (!reset && cursor) q.set('cursor', cursor);
const r = await api.get<{ items: Operation[]; nextCursor: string | null }>(`/api/staff/transactions?${q}`);
setItems((prev) => (reset ? r.items : [...prev, ...r.items]));
setCursor(r.nextCursor);
} catch (e) {
setError((e as Error).message);
} finally {
setLoading(false);
}
},
[period, cursor],
);
useEffect(() => {
load(true);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [period]);
const mode = store.design.pointsMode;
return (
<View style={{ flex: 1, backgroundColor: c.bg }}>
<View style={{ flexDirection: 'row', gap: 8, padding: 16, paddingBottom: 8 }}>
{(['today', 'week'] as const).map((p) => (
<Pressable
key={p}
accessibilityRole="button"
accessibilityState={{ selected: period === p }}
onPress={() => setPeriod(p)}
style={{
height: 44,
paddingHorizontal: 18,
borderRadius: 22,
justifyContent: 'center',
backgroundColor: period === p ? c.primary : c.surface,
borderWidth: 1,
borderColor: period === p ? c.primary : c.border,
}}
>
<T style={{ fontFamily: font.semibold, color: period === p ? c.onPrimary : c.text }}>{p === 'today' ? "Aujourd'hui" : '7 jours'}</T>
</Pressable>
))}
</View>
<T v="muted" style={{ paddingHorizontal: 16, paddingBottom: 8 }}>
{isManager ? 'Toutes les opérations du magasin' : 'Vos opérations'}
</T>
{error && <View style={{ paddingHorizontal: 16 }}><Banner tone="error">{error}</Banner></View>}
<FlatList
data={items}
keyExtractor={(o) => o.id}
contentContainerStyle={{ paddingHorizontal: 16, paddingBottom: 32 }}
onEndReached={() => cursor && !loading && load(false)}
onEndReachedThreshold={0.5}
refreshing={loading && items.length === 0}
onRefresh={() => load(true)}
ListEmptyComponent={!loading ? <T v="muted" style={{ textAlign: 'center', marginTop: 40 }}>Aucune opération sur la période.</T> : null}
ListFooterComponent={loading && items.length > 0 ? <ActivityIndicator style={{ margin: 16 }} /> : null}
ItemSeparatorComponent={() => <View style={{ height: 1, backgroundColor: c.border }} />}
renderItem={({ item: o }) => {
const rejected = o.type === 'REJECTED';
const time = new Date(o.createdAt).toLocaleString('fr-FR', {
...(period === 'week' && { weekday: 'short' }),
hour: '2-digit',
minute: '2-digit',
});
const what =
o.type === 'REDEEM'
? o.reward?.label ?? 'Récompense'
: rejected
? REASON[o.rejectReason ?? ''] ?? 'Refusé'
: o.amountCents
? euros(o.amountCents)
: 'Passage';
return (
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 12, paddingVertical: 14 }}>
<View style={{ width: 54 }}>
<T v="muted" style={{ fontSize: 14 }}>{time}</T>
</View>
<View style={{ flex: 1, gap: 2 }}>
<T v="label" numberOfLines={1}>{o.customerFirstName}</T>
<T v="muted" numberOfLines={1} style={{ fontSize: 14, color: rejected ? c.err : c.text3 }}>
{what}
{isManager ? ` · ${o.staff.displayName}` : ''}
</T>
</View>
<T
style={{
fontFamily: font.bold,
fontSize: 17,
color: rejected ? c.text3 : o.points > 0 ? c.ok : c.text,
}}
>
{rejected ? '—' : `${o.points > 0 ? '+' : '−'}${Math.abs(o.points)} ${unit(mode, Math.abs(o.points)).slice(0, 3)}.`}
</T>
</View>
);
}}
/>
</View>
);
}