MonEspacePro/pro/app/scan.tsx

267 lines
12 KiB
TypeScript

import { useEffect, useRef, useState } from 'react';
import { ActivityIndicator, Animated, Easing, KeyboardAvoidingView, Platform, Pressable, ScrollView, StyleSheet, TextInput, View } from 'react-native';
import { CameraView, useCameraPermissions } from 'expo-camera';
import { router } from 'expo-router';
import * as Haptics from 'expo-haptics';
import { useKeepAwake } from 'expo-keep-awake';
import { playScanOk } from '../src/sounds';
import { SafeAreaView } from 'react-native-safe-area-context';
import { api } from '../src/api';
import { describe } from '../src/errors';
import { Button, Screen, T } from '../src/ui';
import { font, useColors } from '../src/theme';
import { Icon } from '../src/icons';
/** Les numéros de carte commencent par « MEP » (voir le back-end). */
const SERIAL = /^MEP(?:[A-Z2-9]{8}|[A-Z2-9]{16})$/;
const FRAME = 260;
const DIM = 'rgba(0,0,0,0.55)';
/** Saisie manuelle : espaces et tirets ignorés (« MEP ABCD EFGH… » est affiché sous le QR de la carte). */
const normalize = (v: string) => v.toUpperCase().replace(/[\s-]/g, '');
/** Résultat de la recherche d'un client (e-mail masqué par le serveur). */
interface Found {
serial: string;
firstName: string;
email: string;
balance: number;
}
export default function Scan() {
const c = useColors();
const [permission, requestPermission] = useCameraPermissions();
const [torch, setTorch] = useState(false);
const [invalid, setInvalid] = useState(false);
const handled = useRef(false);
// Mode comptoir : l'écran ne se met pas en veille pendant le scan.
useKeepAwake();
const [manual, setManual] = useState(false);
const [typed, setTyped] = useState('');
const [found, setFound] = useState<Found[] | null>(null);
const [searching, setSearching] = useState(false);
const [searchError, setSearchError] = useState<string | null>(null);
const typedOk = SERIAL.test(normalize(typed));
const term = typed.trim();
const isSearch = !typedOk && !/^MEP[A-Z0-9s-]*$/i.test(term) && term.length >= 2;
// Recherche par prénom ou e-mail, au fil de la frappe (300 ms après la dernière touche).
useEffect(() => {
if (!manual || !isSearch) {
setFound(null);
setSearchError(null);
return;
}
let cancelled = false;
setSearching(true);
const t = setTimeout(async () => {
try {
const list = await api.get<Found[]>(`/api/staff/cards?q=${encodeURIComponent(term)}`);
if (!cancelled) {
setFound(list);
setSearchError(null);
}
} catch (e) {
if (!cancelled) setSearchError(describe(e).detail);
} finally {
if (!cancelled) setSearching(false);
}
}, 300);
return () => {
cancelled = true;
clearTimeout(t);
};
}, [manual, isSearch, term]);
function openCard(serial: string) {
handled.current = true;
Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
playScanOk();
router.replace({ pathname: '/client/[serial]', params: { serial } });
}
/** Recherche d'un client : numéro de carte, prénom ou e-mail (si le scan échoue ou sans caméra). */
const manualPanel = (
<KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : undefined} style={StyleSheet.absoluteFill}>
<Pressable style={{ flex: 1, backgroundColor: 'rgba(0,0,0,0.5)' }} onPress={() => setManual(false)} accessibilityLabel="Fermer la recherche" />
<View style={{ backgroundColor: c.surface, padding: 20, paddingBottom: 36, gap: 12, borderTopLeftRadius: 24, borderTopRightRadius: 24, maxHeight: '85%' }}>
<T v="h2">Rechercher un client</T>
<T v="muted" style={{ fontSize: 14 }}>Prénom, e-mail, ou numéro inscrit sous le QR code de sa carte.</T>
<TextInput
autoFocus
value={typed}
onChangeText={setTyped}
placeholder="Camille, camille@… ou MEP XXXX…"
placeholderTextColor={c.text3}
autoCapitalize="none"
autoCorrect={false}
maxLength={60}
returnKeyType={typedOk ? 'go' : 'search'}
onSubmitEditing={() => typedOk && openCard(normalize(typed))}
accessibilityLabel="Prénom, e-mail ou numéro de carte"
style={{ borderWidth: 1, borderColor: c.border, borderRadius: 14, padding: 14, fontSize: 17, color: c.text, backgroundColor: c.bg, fontFamily: font.semibold }}
/>
{typedOk && <Button large label="Ouvrir la carte" onPress={() => openCard(normalize(typed))} />}
{!typedOk && /^MEP/i.test(term) && <T style={{ color: c.text3, fontSize: 13 }}>{normalize(typed).length} / 11 caractères</T>}
{isSearch && (
<ScrollView style={{ maxHeight: 320 }} keyboardShouldPersistTaps="handled">
{searching && !found && <ActivityIndicator style={{ marginVertical: 12 }} />}
{searchError && <T style={{ color: c.err, fontSize: 14 }}>{searchError}</T>}
{found && found.length === 0 && <T v="muted" style={{ fontSize: 14, paddingVertical: 8 }}>Aucun client ne correspond à « {term} ».</T>}
{found?.map((f) => (
<Pressable
key={f.serial}
accessibilityRole="button"
accessibilityLabel={`${f.firstName}, ${f.email}, solde ${f.balance}`}
onPress={() => openCard(f.serial)}
style={({ pressed }) => ({ flexDirection: 'row', alignItems: 'center', gap: 12, paddingVertical: 12, borderBottomWidth: 1, borderBottomColor: c.border, opacity: pressed ? 0.6 : 1 })}
>
<View style={{ width: 40, height: 40, borderRadius: 20, backgroundColor: c.primarySoft, alignItems: 'center', justifyContent: 'center' }}>
<T style={{ fontFamily: font.bold, color: c.primary }}>{f.firstName.charAt(0).toUpperCase()}</T>
</View>
<View style={{ flex: 1 }}>
<T style={{ fontFamily: font.semibold, fontSize: 16 }}>{f.firstName}</T>
<T v="muted" style={{ fontSize: 13 }}>{f.email}</T>
</View>
<T style={{ fontFamily: font.bold, fontSize: 16 }}>{f.balance}</T>
</Pressable>
))}
</ScrollView>
)}
<Button label="Annuler" variant="secondary" onPress={() => setManual(false)} />
</View>
</KeyboardAvoidingView>
);
const line = useRef(new Animated.Value(0)).current;
// Ligne de balayage : montre que la lecture est en cours.
useEffect(() => {
const anim = Animated.loop(
Animated.sequence([
Animated.timing(line, { toValue: 1, duration: 1600, easing: Easing.inOut(Easing.quad), useNativeDriver: true }),
Animated.timing(line, { toValue: 0, duration: 1600, easing: Easing.inOut(Easing.quad), useNativeDriver: true }),
]),
);
anim.start();
return () => anim.stop();
}, [line]);
// Le message « QR code inconnu » disparaît tout seul.
useEffect(() => {
if (!invalid) return;
const t = setTimeout(() => setInvalid(false), 2500);
return () => clearTimeout(t);
}, [invalid]);
if (!permission) return null;
if (!permission.granted) {
return (
<Screen noHeader style={{ justifyContent: 'center', alignItems: 'stretch' }}>
<View style={{ alignItems: 'center', gap: 14 }}>
<View style={{ width: 96, height: 96, borderRadius: 48, backgroundColor: c.primarySoft, alignItems: 'center', justifyContent: 'center' }}>
<Icon name="camera" size={44} color={c.primary} />
</View>
<T v="h1" style={{ textAlign: 'center' }}>Accès à la caméra</T>
<T v="muted" style={{ textAlign: 'center' }}>La caméra sert uniquement à lire le QR code de la carte de fidélité du client.</T>
</View>
{permission.canAskAgain ? (
<Button large label="Autoriser la caméra" onPress={requestPermission} />
) : (
<T style={{ textAlign: 'center' }}>Autorisez la caméra pour MonEspacePro dans les réglages du téléphone.</T>
)}
<Button label="Rechercher un client" variant="secondary" onPress={() => setManual(true)} />
<Button label="Retour" variant="secondary" onPress={() => router.back()} />
{manual && manualPanel}
</Screen>
);
}
const corner = (pos: object) => <View style={[styles.corner, pos]} />;
return (
<View style={{ flex: 1, backgroundColor: '#000' }}>
<CameraView
style={StyleSheet.absoluteFill}
facing="back"
enableTorch={torch}
barcodeScannerSettings={{ barcodeTypes: ['qr'] }}
onBarcodeScanned={({ data }) => {
if (handled.current) return;
const serial = data.trim().toUpperCase();
if (!SERIAL.test(serial)) {
if (!invalid) Haptics.notificationAsync(Haptics.NotificationFeedbackType.Warning);
setInvalid(true);
return;
}
openCard(serial);
}}
/>
{/* Voile sombre autour du cadre de visée */}
<View style={StyleSheet.absoluteFill} pointerEvents="none">
<View style={{ flex: 1, backgroundColor: DIM }} />
<View style={{ flexDirection: 'row', height: FRAME }}>
<View style={{ flex: 1, backgroundColor: DIM }} />
<View style={{ width: FRAME, height: FRAME }}>
{corner({ top: 0, left: 0, borderTopWidth: 5, borderLeftWidth: 5, borderTopLeftRadius: 24 })}
{corner({ top: 0, right: 0, borderTopWidth: 5, borderRightWidth: 5, borderTopRightRadius: 24 })}
{corner({ bottom: 0, left: 0, borderBottomWidth: 5, borderLeftWidth: 5, borderBottomLeftRadius: 24 })}
{corner({ bottom: 0, right: 0, borderBottomWidth: 5, borderRightWidth: 5, borderBottomRightRadius: 24 })}
<Animated.View
style={{
position: 'absolute',
left: 18,
right: 18,
height: 3,
borderRadius: 2,
backgroundColor: invalid ? '#F08A80' : '#F2B544',
transform: [{ translateY: line.interpolate({ inputRange: [0, 1], outputRange: [18, FRAME - 21] }) }],
}}
/>
</View>
<View style={{ flex: 1, backgroundColor: DIM }} />
</View>
<View style={{ flex: 1, backgroundColor: DIM }} />
</View>
<SafeAreaView style={{ flex: 1, justifyContent: 'space-between', padding: 20 }}>
{/* Barre du haut : fermer + consigne */}
<View style={{ gap: 18 }}>
<Pressable accessibilityRole="button" accessibilityLabel="Fermer" onPress={() => router.back()} style={styles.round} hitSlop={8}>
<Icon name="close" size={22} color="#FFFFFF" />
</Pressable>
<View style={{ alignItems: 'center', gap: 4 }}>
<T style={{ color: '#fff', fontFamily: font.bold, fontSize: 22, textAlign: 'center' }}>Scannez la carte du client</T>
<T style={{ color: 'rgba(255,255,255,0.8)', fontSize: 15, textAlign: 'center' }}>QR code affiché dans son Wallet</T>
</View>
</View>
<View style={{ alignItems: 'center', gap: 16 }}>
{invalid && (
<View style={{ backgroundColor: 'rgba(184,50,42,0.92)', paddingVertical: 10, paddingHorizontal: 16, borderRadius: 999 }}>
<T style={{ color: '#fff', fontFamily: font.semibold, fontSize: 15 }}>Ce QR code n'est pas une carte MonEspacePro</T>
</View>
)}
<Pressable
accessibilityRole="button"
accessibilityLabel={torch ? 'Éteindre la lampe' : 'Allumer la lampe'}
accessibilityState={{ selected: torch }}
onPress={() => setTorch((t) => !t)}
style={[styles.round, { width: 64, height: 64, borderRadius: 32 }, torch && { backgroundColor: '#F2B544' }]}
>
<Icon name="flashlight" size={26} color={torch ? '#1C1C19' : '#FFFFFF'} />
</Pressable>
<T style={{ color: 'rgba(255,255,255,0.8)', fontSize: 13 }}>{torch ? 'Lampe allumée' : 'Lampe'}</T>
<Pressable accessibilityRole="button" onPress={() => setManual(true)} hitSlop={10} style={{ paddingVertical: 8, paddingHorizontal: 16, borderRadius: 999, backgroundColor: 'rgba(255,255,255,0.2)' }}>
<T style={{ color: '#fff', fontFamily: font.semibold, fontSize: 15 }}>Rechercher un client</T>
</Pressable>
</View>
</SafeAreaView>
{manual && manualPanel}
</View>
);
}
const styles = StyleSheet.create({
corner: { position: 'absolute', width: 44, height: 44, borderColor: '#FFFFFF' },
round: { width: 44, height: 44, borderRadius: 22, backgroundColor: 'rgba(255,255,255,0.2)', alignItems: 'center', justifyContent: 'center' },
});