import { useCallback, useEffect, useState } from 'react'; import { ActivityIndicator, Alert, 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'; import { describe } from '../src/errors'; type Period = 'today' | 'week'; const REASON: Record = { 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('today'); const [items, setItems] = useState([]); const [cursor, setCursor] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(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' && o.type !== 'ADJUST' && !o.cancelled); const given = done.filter((o) => o.points > 0).reduce((n, o) => n + o.points, 0); const rewards = done.filter((o) => o.type === 'REDEEM').length; /** Annulation depuis l'historique (auteur ou dirigeant, moins de 30 minutes). */ function askCancel(o: Operation) { Alert.alert( o.type === 'REDEEM' ? 'Annuler cette récompense ?' : 'Annuler ce crédit ?', `${o.customerFirstName} · ${o.points > 0 ? '+' : '−'}${Math.abs(o.points)} ${unit(mode, Math.abs(o.points))}. L’annulation reste visible dans l’historique.`, [ { text: 'Non', style: 'cancel' }, { text: 'Annuler l’opération', style: 'destructive', onPress: async () => { try { await api.post(`/api/staff/transactions/${o.id}/cancel`); load(true); } catch (e) { Alert.alert('Annulation impossible', describe(e).detail); } }, }, ], ); } const dayOf = (iso: string) => new Date(iso).toLocaleDateString('fr-FR', { weekday: 'long', day: 'numeric', month: 'long' }); return ( {/* Période : contrôle segmenté */} {(['today', 'week'] as const).map((p) => ( setPeriod(p)} style={{ flex: 1, paddingVertical: 10, borderRadius: 10, alignItems: 'center', backgroundColor: period === p ? c.primary : 'transparent' }} > {p === 'today' ? "Aujourd'hui" : '7 jours'} ))} {[ [done.length, 'opérations'], [given, `${unit(mode)} donnés`], [rewards, 'récompenses'], ].map(([n, l]) => ( {n} {l} ))} {isManager ? 'Toutes les opérations du magasin' : 'Vos opérations'} {error && {error}} o.id} contentContainerStyle={{ paddingHorizontal: 16, paddingBottom: 32, gap: 8 }} onEndReached={() => cursor && !loading && load(false)} onEndReachedThreshold={0.5} bounces={false} overScrollMode="never" ListEmptyComponent={ !loading ? ( Aucune opération sur la période. ) : null } ListFooterComponent={loading ? : null} renderItem={({ item: o, index }) => { const rejected = o.type === 'REJECTED'; const redeem = o.type === 'REDEEM'; const adjust = o.type === 'ADJUST'; const cancelled = !!o.cancelled; 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 = adjust ? o.cancelOf ? `Annulation${o.reward ? ` · ${o.reward.label}` : ''}` : 'Correction' : 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'] : adjust ? [c.surface2, c.text3, 'repeat'] : redeem ? [c.warnBg, c.warn, 'star'] : [c.okBg, c.ok, 'plus']) as [string, string, IconName]; return ( {newDay && ( {dayOf(o.createdAt)} )} askCancel(o)}> {o.customerFirstName} {time} · {what} {isManager ? ` · ${o.staff.displayName}` : ''} {cancelled && Annulée par {o.cancelled!.by}} {o.cancellable && Toucher pour annuler} 0 ? c.okBg : c.warnBg }}> 0 ? c.ok : c.warn, textDecorationLine: cancelled ? 'line-through' : 'none' }}> {rejected ? '—' : `${o.points > 0 ? '+' : '−'}${Math.abs(o.points)}`} ); }} /> ); }