App : recherche d'un client par prénom ou e-mail (en plus du numéro de carte), clients du magasin uniquement, e-mail masqué
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
6dd8492978
commit
fb658ad460
5 changed files with 138 additions and 22 deletions
|
|
@ -1,6 +1,6 @@
|
|||
import { Body, Controller, Get, HttpCode, Param, Post, Query, UseGuards } from '@nestjs/common';
|
||||
import { Throttle } from '@nestjs/throttler';
|
||||
import { IsIn, IsInt, IsOptional, IsString, Max, Min } from 'class-validator';
|
||||
import { IsIn, IsInt, IsOptional, IsString, Length, Max, Min } from 'class-validator';
|
||||
import { CurrentUser, JwtAuthGuard, StaffGuard } from '../common/guards';
|
||||
import { JwtPayload } from '../common/auth.types';
|
||||
import { CounterService, StaffContext } from './counter.service';
|
||||
|
|
@ -16,6 +16,11 @@ class RedeemDto {
|
|||
rewardId!: string;
|
||||
}
|
||||
|
||||
class SearchQuery {
|
||||
@IsString() @Length(2, 60, { message: 'Saisissez au moins 2 caractères' })
|
||||
q!: string;
|
||||
}
|
||||
|
||||
class HistoryQuery {
|
||||
@IsOptional() @IsIn(['today', 'week'])
|
||||
period?: 'today' | 'week';
|
||||
|
|
@ -45,6 +50,13 @@ export class CounterController {
|
|||
return this.counter.summary(ctx(user));
|
||||
}
|
||||
|
||||
/** Recherche d'un client du magasin par prénom ou e-mail (si le QR ne se scanne pas). */
|
||||
@Get('cards')
|
||||
@Throttle({ default: { limit: 60, ttl: 60_000 } })
|
||||
search(@CurrentUser() user: JwtPayload, @Query() q: SearchQuery) {
|
||||
return this.counter.search(ctx(user), q.q);
|
||||
}
|
||||
|
||||
@Get('cards/:serial')
|
||||
@Throttle({ default: { limit: 60, ttl: 60_000 } })
|
||||
lookup(@CurrentUser() user: JwtPayload, @Param('serial') serial: string) {
|
||||
|
|
|
|||
|
|
@ -220,6 +220,30 @@ export class CounterService {
|
|||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Clients du magasin dont le prénom ou l'e-mail contient la recherche (insensible à la casse et aux accents).
|
||||
* L'e-mail est renvoyé masqué : il sert seulement à distinguer deux homonymes au comptoir.
|
||||
*/
|
||||
async search(ctx: StaffContext, q: string) {
|
||||
const store = await this.prisma.store.findUniqueOrThrow({ where: { id: ctx.storeId }, select: { status: true } });
|
||||
if (store.status !== 'ACTIVE') throw new ForbiddenException('Magasin inactif');
|
||||
const term = q.trim();
|
||||
const cards = await this.prisma.loyaltyCard.findMany({
|
||||
where: { storeId: ctx.storeId, OR: [{ customer: { firstName: { contains: term } } }, { customer: { email: { contains: term } } }] },
|
||||
select: { serial: true, balance: true, lastCreditAt: true, createdAt: true, customer: { select: { firstName: true, email: true } } },
|
||||
orderBy: [{ lastCreditAt: 'desc' }, { createdAt: 'desc' }],
|
||||
take: 20,
|
||||
});
|
||||
return cards.map((c) => ({
|
||||
serial: c.serial,
|
||||
firstName: c.customer.firstName,
|
||||
email: maskEmail(c.customer.email),
|
||||
balance: c.balance,
|
||||
lastCreditAt: c.lastCreditAt,
|
||||
memberSince: c.createdAt,
|
||||
}));
|
||||
}
|
||||
|
||||
private async cardOfStore(ctx: StaffContext, serial: string) {
|
||||
const card = await this.prisma.loyaltyCard.findUnique({
|
||||
where: { serial: serial.trim().toUpperCase() },
|
||||
|
|
@ -271,3 +295,9 @@ export class CounterService {
|
|||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** « camille.martin@gmail.com » → « ca•••@gmail.com ». */
|
||||
function maskEmail(email: string) {
|
||||
const [user, domain] = email.split('@');
|
||||
return `${user.slice(0, 2)}•••@${domain ?? ''}`;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ AU COMPTOIR, EN UN SCAN
|
|||
• Ajoutez un tampon, ou saisissez le montant de l’achat pour créditer des points.
|
||||
• Validez une récompense quand le client y a droit.
|
||||
• Le solde se met à jour automatiquement dans le Wallet du client.
|
||||
• Le scan ne fonctionne pas ? Saisissez le numéro inscrit sous le QR code.
|
||||
• Le scan ne fonctionne pas ? Retrouvez le client par son prénom, son e-mail ou le numéro de sa carte.
|
||||
|
||||
ANTI-TRICHE INTÉGRÉ
|
||||
• Délai minimum entre deux crédits sur une même carte.
|
||||
|
|
@ -69,7 +69,7 @@ fidélité,carte,wallet,commerçant,tampon,points,client,boutique,boulangerie,ca
|
|||
>
|
||||
> The demo account is the owner (« Dirigeant ») of a demo shop, « Café Démo ».
|
||||
>
|
||||
> **To test the main feature without a second device:** tap « Scanner », then « Saisir le numéro » and type this loyalty card number: **[MEP XXXX XXXX XXXX XXXX]**. You can also scan the QR code in the attached screenshot. Then tap « Ajouter un tampon ». Note: the same card can only be credited again after 5 minutes (anti-fraud rule); « Historique » shows refused attempts.
|
||||
> **To test the main feature without a second device:** tap « Scanner », then « Rechercher un client » and type the demo customer's first name **[prénom du client de démo]**, or this loyalty card number: **[MEP XXXX XXXX XXXX XXXX]**. You can also scan the QR code in the attached screenshot. Then tap « Ajouter un tampon ». Note: the same card can only be credited again after 5 minutes (anti-fraud rule); « Historique » shows refused attempts.
|
||||
>
|
||||
> **Account deletion (Guideline 5.1.1(v)):** « Mon compte » (top right of the home screen) → « Supprimer mon compte ». Owners can also delete employee accounts in « Employés ». Please do not delete the demo owner account; you can create an employee account in « Employés » and delete it, or log in with this employee account and delete it: [e-mail employé de démo] / [mot de passe].
|
||||
>
|
||||
|
|
|
|||
|
|
@ -22,15 +22,21 @@ Cochez chaque ligne ; notez à côté tout ce qui surprend (texte, lenteur, bout
|
|||
|
||||
## 2. Scan
|
||||
- [ ] Premier scan : iOS demande l'accès à la caméra avec le texte « La caméra sert à scanner la carte de fidélité des clients. »
|
||||
- [ ] Refuser l'accès → écran « Accès à la caméra » avec « Saisir le numéro de la carte » et « Retour ».
|
||||
- [ ] Refuser l'accès → écran « Accès à la caméra » avec « Rechercher un client » et « Retour ».
|
||||
- [ ] Autoriser (Réglages → MonEspacePro → Caméra) → la caméra s'affiche.
|
||||
- [ ] Scanner une carte Apple Wallet → fiche client.
|
||||
- [ ] Scanner une carte Google Wallet → fiche client.
|
||||
- [ ] Scanner un QR quelconque (site web) → « Ce QR code n'est pas une carte MonEspacePro », puis le message disparaît.
|
||||
- [ ] Lampe : s'allume et s'éteint.
|
||||
- [ ] **Saisir le numéro** : taper le numéro affiché sous le QR de la carte (avec ou sans espaces) → fiche client.
|
||||
- [ ] Numéro incomplet → bouton « Ouvrir la carte » grisé, compteur « x / 19 caractères ».
|
||||
- [ ] **Rechercher un client → numéro** : taper le numéro affiché sous le QR (avec ou sans espaces) → bouton « Ouvrir la carte » → fiche client.
|
||||
- [ ] Numéro incomplet → compteur « x / 19 caractères », pas de bouton.
|
||||
- [ ] Numéro d'une carte d'un **autre magasin** → message d'erreur clair.
|
||||
- [ ] **Rechercher un client → prénom** (ex. « cam ») → liste des clients du magasin correspondants, avec e-mail masqué et solde ; toucher un client → fiche client.
|
||||
- [ ] **Rechercher un client → e-mail** (ex. « gmail ») → idem.
|
||||
- [ ] Majuscules, minuscules et accents indifférents (« Helene » trouve « Hélène »).
|
||||
- [ ] Recherche sans résultat → « Aucun client ne correspond à … ».
|
||||
- [ ] Un client d'un **autre magasin** n'apparaît jamais dans les résultats.
|
||||
- [ ] Recherche faite par un **Employé** → fonctionne aussi.
|
||||
|
||||
## 3. Créditer — carte à tampons
|
||||
- [ ] Fiche client : prénom, solde, prochaine récompense.
|
||||
|
|
|
|||
100
pro/app/scan.tsx
100
pro/app/scan.tsx
|
|
@ -1,9 +1,11 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Animated, Easing, KeyboardAvoidingView, Platform, Pressable, StyleSheet, TextInput, View } from 'react-native';
|
||||
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 { 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';
|
||||
|
||||
|
|
@ -14,6 +16,14 @@ 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();
|
||||
|
|
@ -22,7 +32,40 @@ export default function Scan() {
|
|||
const handled = useRef(false);
|
||||
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;
|
||||
|
|
@ -30,29 +73,54 @@ export default function Scan() {
|
|||
router.replace({ pathname: '/client/[serial]', params: { serial } });
|
||||
}
|
||||
|
||||
/** Panneau de saisie du numéro de carte (si le scan échoue ou sans caméra). */
|
||||
/** 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 saisie" />
|
||||
<View style={{ backgroundColor: c.surface, padding: 20, paddingBottom: 36, gap: 12, borderTopLeftRadius: 24, borderTopRightRadius: 24 }}>
|
||||
<T v="h2">Numéro de la carte</T>
|
||||
<T v="muted" style={{ fontSize: 14 }}>Inscrit sous le QR code de la carte du client : MEP suivi de 16 caractères.</T>
|
||||
<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="MEP XXXX XXXX XXXX XXXX"
|
||||
placeholder="Camille, camille@… ou MEP XXXX…"
|
||||
placeholderTextColor={c.text3}
|
||||
autoCapitalize="characters"
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
maxLength={30}
|
||||
returnKeyType="go"
|
||||
maxLength={60}
|
||||
returnKeyType={typedOk ? 'go' : 'search'}
|
||||
onSubmitEditing={() => typedOk && openCard(normalize(typed))}
|
||||
accessibilityLabel="Numéro de la carte"
|
||||
style={{ borderWidth: 1, borderColor: c.border, borderRadius: 14, padding: 14, fontSize: 18, letterSpacing: 1, color: c.text, backgroundColor: c.bg, fontFamily: font.semibold }}
|
||||
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 }}
|
||||
/>
|
||||
{typed.length > 0 && !typedOk && <T style={{ color: c.text3, fontSize: 13 }}>{normalize(typed).length} / 19 caractères</T>}
|
||||
<Button large label="Ouvrir la carte" disabled={!typedOk} onPress={() => openCard(normalize(typed))} />
|
||||
{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} / 19 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>
|
||||
|
|
@ -94,7 +162,7 @@ export default function Scan() {
|
|||
) : (
|
||||
<T style={{ textAlign: 'center' }}>Autorisez la caméra pour MonEspacePro dans les réglages du téléphone.</T>
|
||||
)}
|
||||
<Button label="Saisir le numéro de la carte" variant="secondary" onPress={() => setManual(true)} />
|
||||
<Button label="Rechercher un client" variant="secondary" onPress={() => setManual(true)} />
|
||||
<Button label="Retour" variant="secondary" onPress={() => router.back()} />
|
||||
{manual && manualPanel}
|
||||
</Screen>
|
||||
|
|
@ -178,7 +246,7 @@ export default function Scan() {
|
|||
</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 }}>Saisir le numéro</T>
|
||||
<T style={{ color: '#fff', fontFamily: font.semibold, fontSize: 15 }}>Rechercher un client</T>
|
||||
</Pressable>
|
||||
</View>
|
||||
</SafeAreaView>
|
||||
|
|
|
|||
Loading…
Reference in a new issue