MonEspacePro/pro/app/history.tsx

154 lines
7.1 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, Card, T, euros, unit } from '../src/ui';
import { font, useColors } from '../src/theme';
import { Icon, IconName } from '../src/icons';
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 dirigeant 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;
// Résumé de la période (opérations chargées).
const done = items.filter((o) => o.type !== 'REJECTED');
const given = done.filter((o) => o.points > 0).reduce((n, o) => n + o.points, 0);
const rewards = done.filter((o) => o.type === 'REDEEM').length;
const dayOf = (iso: string) => new Date(iso).toLocaleDateString('fr-FR', { weekday: 'long', day: 'numeric', month: 'long' });
return (
<View style={{ flex: 1, backgroundColor: c.bg }}>
<View style={{ padding: 16, paddingBottom: 8, gap: 12 }}>
{/* Période : contrôle segmenté */}
<View accessibilityRole="tablist" style={{ flexDirection: 'row', backgroundColor: c.surface, borderRadius: 14, padding: 4, borderWidth: 1, borderColor: c.border }}>
{(['today', 'week'] as const).map((p) => (
<Pressable
key={p}
accessibilityRole="tab"
accessibilityState={{ selected: period === p }}
onPress={() => setPeriod(p)}
style={{ flex: 1, paddingVertical: 10, borderRadius: 10, alignItems: 'center', backgroundColor: period === p ? c.primary : 'transparent' }}
>
<T style={{ fontFamily: font.bold, fontSize: 15, color: period === p ? c.onPrimary : c.text }}>{p === 'today' ? "Aujourd'hui" : '7 jours'}</T>
</Pressable>
))}
</View>
<View style={{ flexDirection: 'row', gap: 10 }}>
{[
[done.length, 'opérations'],
[given, `${unit(mode)} donnés`],
[rewards, 'récompenses'],
].map(([n, l]) => (
<View key={String(l)} style={{ flex: 1, backgroundColor: c.primarySoft, borderRadius: 14, paddingVertical: 10, paddingHorizontal: 12 }}>
<T style={{ fontFamily: font.extrabold, fontSize: 20, color: c.primary }}>{n}</T>
<T v="muted" style={{ fontSize: 12 }}>{l}</T>
</View>
))}
</View>
<T v="muted" style={{ fontSize: 13 }}>{isManager ? 'Toutes les opérations du magasin' : 'Vos opérations'}</T>
</View>
{error && <View style={{ paddingHorizontal: 16 }}><Banner tone="error">{error}</Banner></View>}
<FlatList
data={items}
keyExtractor={(o) => o.id}
contentContainerStyle={{ paddingHorizontal: 16, paddingBottom: 32, gap: 8 }}
onEndReached={() => cursor && !loading && load(false)}
onEndReachedThreshold={0.5}
bounces={false}
overScrollMode="never"
ListEmptyComponent={
!loading ? (
<View style={{ alignItems: 'center', marginTop: 48, gap: 6 }}>
<Icon name="list" size={36} color={c.text3} />
<T v="muted" style={{ textAlign: 'center' }}>Aucune opération sur la période.</T>
</View>
) : null
}
ListFooterComponent={loading ? <ActivityIndicator style={{ margin: 16 }} /> : null}
renderItem={({ item: o, index }) => {
const rejected = o.type === 'REJECTED';
const redeem = o.type === 'REDEEM';
const time = new Date(o.createdAt).toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' });
// Sur 7 jours : un intertitre à chaque nouveau jour.
const newDay = period === 'week' && (index === 0 || dayOf(items[index - 1].createdAt) !== dayOf(o.createdAt));
const what = redeem
? o.reward?.label ?? 'Récompense'
: rejected
? REASON[o.rejectReason ?? ''] ?? 'Refusé'
: o.amountCents
? euros(o.amountCents)
: 'Passage';
const [iconBg, iconFg, icon] = (rejected ? [c.errBg, c.err, 'alert'] : redeem ? [c.warnBg, c.warn, 'star'] : [c.okBg, c.ok, 'plus']) as [string, string, IconName];
return (
<View style={{ gap: 8 }}>
{newDay && (
<T v="label" style={{ marginTop: index === 0 ? 0 : 10, color: c.text3, textTransform: 'capitalize' }}>
{dayOf(o.createdAt)}
</T>
)}
<Card style={{ flexDirection: 'row', alignItems: 'center', gap: 12, padding: 12, opacity: rejected ? 0.85 : 1 }}>
<View style={{ width: 40, height: 40, borderRadius: 20, backgroundColor: iconBg, alignItems: 'center', justifyContent: 'center' }}>
<Icon name={icon} size={20} color={iconFg} strokeWidth={2.4} />
</View>
<View style={{ flex: 1, gap: 2 }}>
<T v="label" numberOfLines={1}>{o.customerFirstName}</T>
<T v="muted" numberOfLines={1} style={{ fontSize: 13, color: rejected ? c.err : c.text3 }}>
{time} · {what}
{isManager ? ` · ${o.staff.displayName}` : ''}
</T>
</View>
<View style={{ paddingHorizontal: 10, paddingVertical: 4, borderRadius: 999, backgroundColor: rejected ? c.surface2 : o.points > 0 ? c.okBg : c.warnBg }}>
<T style={{ fontFamily: font.bold, fontSize: 15, color: rejected ? c.text3 : o.points > 0 ? c.ok : c.warn }}>
{rejected ? '—' : `${o.points > 0 ? '+' : '−'}${Math.abs(o.points)}`}
</T>
</View>
</Card>
</View>
);
}}
/>
</View>
);
}