diff --git a/backend/src/counter/counter.controller.ts b/backend/src/counter/counter.controller.ts index 91a918e..80b1417 100644 --- a/backend/src/counter/counter.controller.ts +++ b/backend/src/counter/counter.controller.ts @@ -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) { diff --git a/backend/src/counter/counter.service.ts b/backend/src/counter/counter.service.ts index 80933fe..141e50a 100644 --- a/backend/src/counter/counter.service.ts +++ b/backend/src/counter/counter.service.ts @@ -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 ?? ''}`; +} diff --git a/docs/app-ios/app-store.md b/docs/app-ios/app-store.md index 3b0f152..e7de7cc 100644 --- a/docs/app-ios/app-store.md +++ b/docs/app-ios/app-store.md @@ -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]. > diff --git a/docs/app-ios/test-app-ios.md b/docs/app-ios/test-app-ios.md index 1792e32..f41ba54 100644 --- a/docs/app-ios/test-app-ios.md +++ b/docs/app-ios/test-app-ios.md @@ -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. diff --git a/pro/app/scan.tsx b/pro/app/scan.tsx index 9a87272..c889810 100644 --- a/pro/app/scan.tsx +++ b/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(null); + const [searching, setSearching] = useState(false); + const [searchError, setSearchError] = useState(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(`/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 = ( - setManual(false)} accessibilityLabel="Fermer la saisie" /> - - Numéro de la carte - Inscrit sous le QR code de la carte du client : MEP suivi de 16 caractères. + setManual(false)} accessibilityLabel="Fermer la recherche" /> + + Rechercher un client + Prénom, e-mail, ou numéro inscrit sous le QR code de sa carte. 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 && {normalize(typed).length} / 19 caractères} -