188 lines
8.9 KiB
TypeScript
188 lines
8.9 KiB
TypeScript
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<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' && 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 (
|
||
<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 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 (
|
||
<View style={{ gap: 8 }}>
|
||
{newDay && (
|
||
<T v="label" style={{ marginTop: index === 0 ? 0 : 10, color: c.text3, textTransform: 'capitalize' }}>
|
||
{dayOf(o.createdAt)}
|
||
</T>
|
||
)}
|
||
<Pressable accessibilityRole={o.cancellable ? 'button' : undefined} accessibilityHint={o.cancellable ? 'Annuler cette opération' : undefined} disabled={!o.cancellable} onPress={() => askCancel(o)}>
|
||
<Card style={{ flexDirection: 'row', alignItems: 'center', gap: 12, padding: 12, opacity: rejected || cancelled ? 0.6 : 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>
|
||
{cancelled && <T style={{ fontSize: 12, color: c.err, fontFamily: font.semibold }}>Annulée par {o.cancelled!.by}</T>}
|
||
{o.cancellable && <T style={{ fontSize: 12, color: c.text3 }}>Toucher pour annuler</T>}
|
||
</View>
|
||
<View style={{ paddingHorizontal: 10, paddingVertical: 4, borderRadius: 999, backgroundColor: rejected || adjust || cancelled ? c.surface2 : o.points > 0 ? c.okBg : c.warnBg }}>
|
||
<T style={{ fontFamily: font.bold, fontSize: 15, color: rejected || adjust || cancelled ? c.text3 : o.points > 0 ? c.ok : c.warn, textDecorationLine: cancelled ? 'line-through' : 'none' }}>
|
||
{rejected ? '—' : `${o.points > 0 ? '+' : '−'}${Math.abs(o.points)}`}
|
||
</T>
|
||
</View>
|
||
</Card>
|
||
</Pressable>
|
||
</View>
|
||
);
|
||
}}
|
||
/>
|
||
</View>
|
||
);
|
||
}
|