MonEspacePro/pro/app/client/[serial]/index.tsx

149 lines
6.8 KiB
TypeScript

import { useState } from 'react';
import { ActivityIndicator, Alert, Pressable, View } from 'react-native';
import { router } from 'expo-router';
import { useStore } from '../../../src/session';
import { useCard } from '../../../src/useCard';
import { api, CardInfo } from '../../../src/api';
import { describe, ErrorScreen } from '../../../src/errors';
import { Banner, Button, Card, Screen, T, unit } from '../../../src/ui';
import { font, useColors } from '../../../src/theme';
import { Icon } from '../../../src/icons';
function ago(iso: string) {
const min = Math.round((Date.now() - new Date(iso).getTime()) / 60000);
if (min < 1) return "à l'instant";
if (min < 60) return `il y a ${min} min`;
const h = Math.round(min / 60);
if (h < 24) return `il y a ${h} h`;
return `le ${new Date(iso).toLocaleDateString('fr-FR', { day: 'numeric', month: 'long' })}`;
}
/** Fiche client après scan (maquette 4). */
export default function ClientCard() {
const c = useColors();
const store = useStore();
const { serial, card, setCard, error, reload } = useCard();
const [giving, setGiving] = useState<string | null>(null);
if (error) return <ErrorScreen error={error} onRetry={reload} />;
if (!card) return <Screen style={{ justifyContent: 'center' }}><ActivityIndicator /></Screen>;
const mode = store.design.pointsMode;
const reachable = store.design.rewards.filter((r) => r.cost <= card.balance).length;
const SOURCE = { BIRTHDAY: 'Anniversaire', REFERRAL: 'Parrainage', REFERRAL_FRIEND: 'Bienvenue (parrainage)' } as const;
const give = (g: CardInfo['gifts'][number]) =>
Alert.alert('Remettre le cadeau ?', `« ${g.label} » à ${card.firstName}`, [
{ text: 'Annuler', style: 'cancel' },
{
text: 'Remis',
onPress: async () => {
setGiving(g.id);
try {
setCard(await api.post<CardInfo>(`/api/staff/cards/${encodeURIComponent(serial)}/gifts/${g.id}/use`));
} catch (e) {
Alert.alert('Impossible', describe(e).detail);
} finally {
setGiving(null);
}
},
},
]);
// Prochain palier : la première récompense pas encore atteinte (sinon la plus chère).
const sortedRewards = [...store.design.rewards].sort((a, b) => a.cost - b.cost);
const target = sortedRewards.find((r) => r.cost > card.balance) ?? sortedRewards[sortedRewards.length - 1];
const progress = target ? Math.min(card.balance / target.cost, 1) : 0;
const fg = store.design.foregroundColor;
const memberSince = new Date(card.memberSince).toLocaleDateString('fr-FR', { month: 'short', year: 'numeric' });
return (
<Screen scroll>
{/* En-tête : initiale, prénom, ancienneté */}
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 14 }}>
<View style={{ width: 56, height: 56, borderRadius: 28, backgroundColor: c.primarySoft, alignItems: 'center', justifyContent: 'center' }}>
<T style={{ fontFamily: font.extrabold, fontSize: 24, color: c.primary }}>{card.firstName.charAt(0).toUpperCase()}</T>
</View>
<View style={{ flex: 1, gap: 2 }}>
<T v="h1" numberOfLines={1}>{card.firstName}</T>
<T v="muted" style={{ fontSize: 14 }}>
{card.lastCreditAt ? `Dernière visite ${ago(card.lastCreditAt)}` : 'Première visite'} · client depuis {memberSince}
</T>
</View>
</View>
{/* Carte aux couleurs du magasin : solde et progression */}
<View style={{ backgroundColor: store.design.backgroundColor, borderRadius: 22, padding: 22, gap: 14 }}>
<T style={{ color: fg, opacity: 0.8, fontFamily: font.semibold, fontSize: 13, letterSpacing: 1 }} numberOfLines={1}>
{store.design.programName.toUpperCase()}
</T>
<View style={{ flexDirection: 'row', alignItems: 'flex-end', gap: 8 }}>
<T v="big" style={{ color: fg }}>{card.balance}</T>
<T style={{ color: fg, fontFamily: font.semibold, fontSize: 18, marginBottom: 10 }}>{unit(mode, card.balance)}</T>
</View>
{target && (
<View style={{ gap: 8 }}>
<View style={{ height: 8, borderRadius: 4, backgroundColor: fg.length === 7 ? `${fg}40` : 'rgba(127,127,127,0.3)', overflow: 'hidden' }}>
<View style={{ width: `${Math.round(progress * 100)}%`, height: 8, borderRadius: 4, backgroundColor: c.accent }} />
</View>
<T style={{ color: fg, fontSize: 14 }}>
{reachable > 0
? reachable === 1
? '1 récompense disponible'
: `${reachable} récompenses disponibles`
: `Encore ${target.cost - card.balance} ${unit(mode, target.cost - card.balance)} avant « ${target.label} »`}
</T>
</View>
)}
</View>
{card.nextCreditAt && (
<Banner tone="warn">
Déjà créditée récemment : nouveau crédit possible à{' '}
{new Date(card.nextCreditAt).toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' })}.
</Banner>
)}
{/* Cadeaux en nature à remettre en caisse */}
{card.gifts?.length > 0 && (
<View style={{ gap: 10 }}>
<T v="h2">Cadeaux à remettre</T>
{card.gifts.map((g) => (
<Card key={g.id} style={{ padding: 14, flexDirection: 'row', alignItems: 'center', gap: 12 }}>
<View style={{ width: 44, height: 44, borderRadius: 22, backgroundColor: c.warnBg, alignItems: 'center', justifyContent: 'center' }}>
<Icon name="gift" size={22} color={c.warn} />
</View>
<View style={{ flex: 1, gap: 2 }}>
<T v="label">{g.label}</T>
<T v="muted" style={{ fontSize: 13 }}>
{SOURCE[g.source]} · {new Date(g.createdAt).toLocaleDateString('fr-FR', { day: 'numeric', month: 'short' })}
</T>
</View>
{giving === g.id ? (
<ActivityIndicator />
) : (
<Pressable accessibilityRole="button" hitSlop={8} onPress={() => give(g)}>
<T style={{ color: c.primary, fontFamily: font.bold }}>Remettre</T>
</Pressable>
)}
</Card>
))}
</View>
)}
<View style={{ flex: 1 }} />
<Button
large
label={mode === 'STAMP' ? 'Ajouter un tampon' : 'Créditer'}
onPress={() => router.push({ pathname: '/client/[serial]/credit', params: { serial } })}
/>
<Button
label={reachable > 0 ? 'Utiliser une récompense' : 'Voir les récompenses'}
variant="secondary"
disabled={store.design.rewards.length === 0}
onPress={() => router.push({ pathname: '/client/[serial]/rewards', params: { serial } })}
/>
<T v="muted" style={{ textAlign: 'center', fontSize: 12 }}>Carte {serial}</T>
</Screen>
);
}