App Pro (Expo) et API du comptoir avec anti-triche

- API /staff : profil, scan d'une carte, crédit (montant ou tampon),
  récompenses, historique (gérant : tout le magasin, employé : le sien),
  résumé du jour
- Anti-triche côté serveur : carte du bon magasin, plafond de montant,
  délai minimum entre deux crédits (atomique, scans simultanés compris),
  tentatives refusées journalisées avec l'employé
- App Expo SDK 54 / Expo Router : connexion, accueil, scanner QR avec
  lampe, fiche client, pavé numérique, récompenses, confirmation, erreurs,
  historique ; icônes générées depuis le logo

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Tony AVERTY 2026-10-06 12:50:59 +02:00
parent eec67bbf86
commit 6725358a7c
31 changed files with 11098 additions and 0 deletions

View file

@ -145,6 +145,13 @@ enum TransactionType {
CREDIT
REDEEM
ADJUST /// correction manuelle (gérant)
REJECTED /// tentative refusée par l'anti-triche (0 point), visible dans les opérations
}
enum RejectReason {
AMOUNT_OVER_LIMIT
TOO_SOON
INSUFFICIENT_BALANCE
}
/// Journal immuable : chaque scan est enregistré avec l'employé.
@ -159,12 +166,16 @@ model Transaction {
type TransactionType
amountCents Int?
points Int /// positif (crédit) ou négatif (récompense)
/// Solde de la carte après l'opération (lecture de l'historique sans recalcul).
balanceAfter Int
rejectReason RejectReason?
rewardId String?
reward Reward? @relation(fields: [rewardId], references: [id])
createdAt DateTime @default(now())
@@index([storeId, createdAt])
@@index([cardId, createdAt])
@@index([staffId, createdAt])
}
// ── Apple Wallet (service web PassKit) ────────────────────────

View file

@ -8,6 +8,7 @@ import { AuthModule } from './auth/auth.module';
import { AdminModule } from './admin.module';
import { MailModule } from './mail/mail.service';
import { EnrollmentModule } from './enrollment/enrollment.module';
import { CounterModule } from './counter/counter.module';
import { HealthController } from './health.controller';
@Module({
@ -19,6 +20,7 @@ import { HealthController } from './health.controller';
AdminModule,
MailModule,
EnrollmentModule,
CounterModule,
],
controllers: [HealthController],
providers: [{ provide: APP_GUARD, useClass: ThrottlerGuard }],

View file

@ -0,0 +1,70 @@
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 { CurrentUser, JwtAuthGuard, StaffGuard } from '../common/guards';
import { JwtPayload } from '../common/auth.types';
import { CounterService, StaffContext } from './counter.service';
class CreditDto {
/** Absent en mode tampons. */
@IsOptional() @IsInt() @Min(1) @Max(1_000_000)
amountCents?: number;
}
class RedeemDto {
@IsString()
rewardId!: string;
}
class HistoryQuery {
@IsOptional() @IsIn(['today', 'week'])
period?: 'today' | 'week';
@IsOptional() @IsString()
cursor?: string;
}
function ctx(user: JwtPayload): StaffContext {
if (user.kind !== 'staff') throw new Error('StaffGuard manquant');
return { staffId: user.sub, storeId: user.storeId, role: user.role };
}
/** API de l'app Pro (employés au comptoir). */
@Controller('staff')
@UseGuards(JwtAuthGuard, StaffGuard)
export class CounterController {
constructor(private counter: CounterService) {}
@Get('me')
me(@CurrentUser() user: JwtPayload) {
return this.counter.me(ctx(user));
}
@Get('summary')
summary(@CurrentUser() user: JwtPayload) {
return this.counter.summary(ctx(user));
}
@Get('cards/:serial')
@Throttle({ default: { limit: 60, ttl: 60_000 } })
lookup(@CurrentUser() user: JwtPayload, @Param('serial') serial: string) {
return this.counter.lookup(ctx(user), serial);
}
@Post('cards/:serial/credit')
@HttpCode(200)
credit(@CurrentUser() user: JwtPayload, @Param('serial') serial: string, @Body() dto: CreditDto) {
return this.counter.credit(ctx(user), serial, dto.amountCents);
}
@Post('cards/:serial/redeem')
@HttpCode(200)
redeem(@CurrentUser() user: JwtPayload, @Param('serial') serial: string, @Body() dto: RedeemDto) {
return this.counter.redeem(ctx(user), serial, dto.rewardId);
}
@Get('transactions')
history(@CurrentUser() user: JwtPayload, @Query() q: HistoryQuery) {
return this.counter.history(ctx(user), q.period ?? 'today', q.cursor);
}
}

View file

@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { CounterController } from './counter.controller';
import { CounterService } from './counter.service';
import { CardUpdatesService } from '../wallet/card-updates.service';
/** Comptoir : scan, crédit, récompenses, historique (app Pro). */
@Module({
controllers: [CounterController],
providers: [CounterService, CardUpdatesService],
})
export class CounterModule {}

View file

@ -0,0 +1,252 @@
import { BadRequestException, ForbiddenException, HttpException, HttpStatus, Injectable, NotFoundException } from '@nestjs/common';
import { Prisma, RejectReason, StaffRole } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { CardUpdatesService } from '../wallet/card-updates.service';
export type StaffContext = { staffId: string; storeId: string; role: StaffRole };
/** Erreur métier lisible par l'app Pro (`code`) avec un message prêt à afficher. */
class CounterError extends HttpException {
constructor(status: HttpStatus, code: string, message: string, extra: Record<string, unknown> = {}) {
super({ statusCode: status, code, message, ...extra }, status);
}
}
const euros = (cents: number) => (cents / 100).toLocaleString('fr-FR', { style: 'currency', currency: 'EUR' });
/**
* Opérations au comptoir. Le QR d'une carte Wallet est fixe : toute la
* protection est ici — carte du bon magasin, plafond de montant, délai
* minimum entre deux crédits, et chaque opération (même refusée) est
* journalisée avec l'employé qui l'a faite.
*/
@Injectable()
export class CounterService {
constructor(
private prisma: PrismaService,
private cardUpdates: CardUpdatesService,
) {}
async me(ctx: StaffContext) {
const staff = await this.prisma.staffUser.findUniqueOrThrow({
where: { id: ctx.staffId },
select: {
id: true,
displayName: true,
role: true,
store: {
select: {
id: true,
name: true,
city: true,
maxAmountCents: true,
minScanIntervalSec: true,
cardDesign: {
select: {
programName: true,
backgroundColor: true,
foregroundColor: true,
pointsMode: true,
pointsPerEuro: true,
logoPath: true,
rewards: { where: { active: true }, orderBy: { cost: 'asc' }, select: { id: true, label: true, cost: true } },
},
},
},
},
},
});
const design = staff.store.cardDesign;
return {
...staff,
store: {
...staff.store,
cardDesign: design && {
...design,
pointsPerEuro: design.pointsPerEuro.toNumber(),
logoUrl: design.logoPath ? `/uploads/${design.logoPath}` : null,
},
},
};
}
async lookup(ctx: StaffContext, serial: string) {
const card = await this.cardOfStore(ctx, serial);
return this.presentCard(card);
}
async credit(ctx: StaffContext, serial: string, amountCents: number | undefined) {
const card = await this.cardOfStore(ctx, serial);
const store = card.store;
const design = store.cardDesign!;
const stamp = design.pointsMode === 'STAMP';
if (!stamp && amountCents === undefined) throw new BadRequestException('Montant requis');
if (amountCents !== undefined && amountCents > store.maxAmountCents) {
await this.reject(ctx, card, 'AMOUNT_OVER_LIMIT', amountCents);
throw new CounterError(HttpStatus.UNPROCESSABLE_ENTITY, 'AMOUNT_OVER_LIMIT', `Montant supérieur au plafond (${euros(store.maxAmountCents)})`, {
maxAmountCents: store.maxAmountCents,
});
}
const points = stamp ? 1 : Math.floor(((amountCents ?? 0) * design.pointsPerEuro.toNumber()) / 100);
if (points <= 0) throw new BadRequestException('Montant trop faible pour gagner un point');
const now = new Date();
const threshold = new Date(now.getTime() - store.minScanIntervalSec * 1000);
const result = await this.prisma.$transaction(async (tx) => {
// Mise à jour conditionnelle : deux scans simultanés ne peuvent pas passer tous les deux.
const updated = await tx.loyaltyCard.updateMany({
where: {
id: card.id,
...(store.minScanIntervalSec > 0 && { OR: [{ lastCreditAt: null }, { lastCreditAt: { lte: threshold } }] }),
},
data: { balance: { increment: points }, lastCreditAt: now },
});
if (updated.count === 0) return null;
const { balance } = await tx.loyaltyCard.findUniqueOrThrow({ where: { id: card.id }, select: { balance: true } });
await tx.transaction.create({
data: { storeId: ctx.storeId, cardId: card.id, staffId: ctx.staffId, type: 'CREDIT', amountCents, points, balanceAfter: balance },
});
return balance;
});
if (result === null) {
await this.reject(ctx, card, 'TOO_SOON', amountCents);
const fresh = await this.prisma.loyaltyCard.findUniqueOrThrow({ where: { id: card.id }, select: { lastCreditAt: true } });
const elapsedSec = fresh.lastCreditAt ? Math.floor((now.getTime() - fresh.lastCreditAt.getTime()) / 1000) : 0;
const retryAfterSec = Math.max(store.minScanIntervalSec - elapsedSec, 1);
throw new CounterError(HttpStatus.TOO_MANY_REQUESTS, 'TOO_SOON', 'Carte déjà créditée récemment', {
elapsedSec,
retryAfterSec,
});
}
this.cardUpdates.notify(card.id);
return { points, balance: result, firstName: card.customer.firstName };
}
async redeem(ctx: StaffContext, serial: string, rewardId: string) {
const card = await this.cardOfStore(ctx, serial);
const reward = card.store.cardDesign!.rewards.find((r) => r.id === rewardId && r.active);
if (!reward) throw new NotFoundException('Récompense introuvable');
const balance = await this.prisma.$transaction(async (tx) => {
const updated = await tx.loyaltyCard.updateMany({
where: { id: card.id, balance: { gte: reward.cost } },
data: { balance: { decrement: reward.cost } },
});
if (updated.count === 0) return null;
const { balance } = await tx.loyaltyCard.findUniqueOrThrow({ where: { id: card.id }, select: { balance: true } });
await tx.transaction.create({
data: { storeId: ctx.storeId, cardId: card.id, staffId: ctx.staffId, type: 'REDEEM', points: -reward.cost, rewardId: reward.id, balanceAfter: balance },
});
return balance;
});
if (balance === null) {
await this.reject(ctx, card, 'INSUFFICIENT_BALANCE');
throw new CounterError(HttpStatus.UNPROCESSABLE_ENTITY, 'INSUFFICIENT_BALANCE', 'Solde insuffisant pour cette récompense', {
missing: reward.cost - card.balance,
});
}
this.cardUpdates.notify(card.id);
return { reward: { id: reward.id, label: reward.label, cost: reward.cost }, balance, firstName: card.customer.firstName };
}
/** Le gérant voit tout le magasin ; l'employé, seulement ses opérations. */
async history(ctx: StaffContext, period: 'today' | 'week', cursor?: string) {
const where = this.scope(ctx, period);
const items = await this.prisma.transaction.findMany({
where,
orderBy: { createdAt: 'desc' },
take: 51,
...(cursor && { cursor: { id: cursor }, skip: 1 }),
select: {
id: true,
type: true,
amountCents: true,
points: true,
balanceAfter: true,
rejectReason: true,
createdAt: true,
reward: { select: { label: true } },
staff: { select: { id: true, displayName: true } },
card: { select: { customer: { select: { firstName: true } } } },
},
});
const hasMore = items.length > 50;
return {
items: items.slice(0, 50).map(({ card, ...t }) => ({ ...t, customerFirstName: card.customer.firstName })),
nextCursor: hasMore ? items[49].id : null,
};
}
async summary(ctx: StaffContext) {
const where = this.scope(ctx, 'today');
const [credits, redeems] = await Promise.all([
this.prisma.transaction.aggregate({ where: { ...where, type: 'CREDIT' }, _count: true, _sum: { points: true } }),
this.prisma.transaction.count({ where: { ...where, type: 'REDEEM' } }),
]);
return { operations: credits._count + redeems, pointsGiven: credits._sum.points ?? 0, rewards: redeems };
}
private scope(ctx: StaffContext, period: 'today' | 'week'): Prisma.TransactionWhereInput {
const since = new Date();
since.setHours(0, 0, 0, 0);
if (period === 'week') since.setDate(since.getDate() - 6);
return {
storeId: ctx.storeId,
createdAt: { gte: since },
...(ctx.role !== 'MANAGER' && { staffId: ctx.staffId }),
};
}
private async cardOfStore(ctx: StaffContext, serial: string) {
const card = await this.prisma.loyaltyCard.findUnique({
where: { serial: serial.trim().toUpperCase() },
include: {
customer: { select: { firstName: true } },
store: { include: { cardDesign: { include: { rewards: true } } } },
},
});
if (!card) throw new CounterError(HttpStatus.NOT_FOUND, 'UNKNOWN_CARD', 'Carte inconnue');
// Rien sur la carte d'un autre magasin ne doit fuiter (ni prénom, ni solde).
if (card.storeId !== ctx.storeId) {
throw new CounterError(HttpStatus.FORBIDDEN, 'OTHER_STORE', 'Carte d’un autre magasin');
}
if (card.store.status !== 'ACTIVE' || !card.store.cardDesign) throw new ForbiddenException('Magasin inactif');
return card;
}
private presentCard(card: Awaited<ReturnType<CounterService['cardOfStore']>>) {
const s = card.store;
const nextCreditAt =
card.lastCreditAt && s.minScanIntervalSec > 0 ? new Date(card.lastCreditAt.getTime() + s.minScanIntervalSec * 1000) : null;
return {
serial: card.serial,
firstName: card.customer.firstName,
balance: card.balance,
memberSince: card.createdAt,
lastCreditAt: card.lastCreditAt,
nextCreditAt: nextCreditAt && nextCreditAt > new Date() ? nextCreditAt : null,
};
}
private async reject(
ctx: StaffContext,
card: { id: string; balance: number },
reason: RejectReason,
amountCents?: number,
) {
await this.prisma.transaction.create({
data: {
storeId: ctx.storeId,
cardId: card.id,
staffId: ctx.staffId,
type: 'REJECTED',
amountCents,
points: 0,
balanceAfter: card.balance,
rejectReason: reason,
},
});
}
}

View file

@ -0,0 +1,14 @@
import { Injectable, Logger } from '@nestjs/common';
/**
* Point d'entrée unique « le solde d'une carte a changé ».
* Étape 5 : pousse la mise à jour vers Apple (APNs) et Google Wallet.
*/
@Injectable()
export class CardUpdatesService {
private readonly logger = new Logger(CardUpdatesService.name);
notify(cardId: string) {
this.logger.debug(`Carte ${cardId} modifiée — mise à jour Wallet à brancher (étape 5)`);
}
}

2
pro/.env.example Normal file
View file

@ -0,0 +1,2 @@
# Adresse de l API vue depuis le téléphone (même Wi-Fi que le PC)
EXPO_PUBLIC_API_URL=http://192.168.1.10:3100

4
pro/.npmrc Normal file
View file

@ -0,0 +1,4 @@
# Tolère les conflits de peer dependencies de l'écosystème React Native / Expo
# (ex. react-dom transitif exigeant une version de react plus récente que celle du SDK).
# Respecté par npm en local ET par EAS Build (installation côté cloud).
legacy-peer-deps=true

53
pro/app.json Normal file
View file

@ -0,0 +1,53 @@
{
"expo": {
"name": "MonEspacePro Pro",
"slug": "monespacepro-pro",
"version": "0.1.0",
"orientation": "portrait",
"scheme": "mep-pro",
"userInterfaceStyle": "automatic",
"newArchEnabled": true,
"icon": "./assets/icon.png",
"ios": {
"supportsTablet": false,
"bundleIdentifier": "dev.tonyaverty.mep.pro",
"infoPlist": {
"NSCameraUsageDescription": "La caméra sert à scanner la carte de fidélité des clients.",
"ITSAppUsesNonExemptEncryption": false
}
},
"android": {
"package": "dev.tonyaverty.mep.pro",
"adaptiveIcon": {
"foregroundImage": "./assets/adaptive-icon.png",
"monochromeImage": "./assets/adaptive-monochrome.png",
"backgroundColor": "#0E7A66"
},
"permissions": ["android.permission.CAMERA"],
"blockedPermissions": ["android.permission.RECORD_AUDIO"]
},
"plugins": [
"expo-router",
"expo-secure-store",
"expo-font",
[
"expo-camera",
{
"cameraPermission": "La caméra sert à scanner la carte de fidélité des clients.",
"recordAudioAndroid": false
}
],
[
"expo-splash-screen",
{
"image": "./assets/splash-icon.png",
"imageWidth": 160,
"backgroundColor": "#0E7A66"
}
]
],
"experiments": {
"typedRoutes": true
}
}
}

67
pro/app/_layout.tsx Normal file
View file

@ -0,0 +1,67 @@
import { useEffect } from 'react';
import { Stack } from 'expo-router';
import { StatusBar } from 'expo-status-bar';
import * as SplashScreen from 'expo-splash-screen';
import {
useFonts,
Figtree_400Regular,
Figtree_500Medium,
Figtree_600SemiBold,
Figtree_700Bold,
Figtree_800ExtraBold,
} from '@expo-google-fonts/figtree';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { SessionProvider, useSession } from '../src/session';
import { font, useColors } from '../src/theme';
SplashScreen.preventAutoHideAsync();
function Navigator() {
const { status } = useSession();
const c = useColors();
useEffect(() => {
if (status !== 'loading') SplashScreen.hideAsync();
}, [status]);
if (status === 'loading') return null;
const signedIn = status === 'signed-in';
return (
<Stack
screenOptions={{
headerStyle: { backgroundColor: c.bg },
headerShadowVisible: false,
headerTintColor: c.text,
headerTitleStyle: { fontFamily: font.bold },
headerBackButtonDisplayMode: 'minimal',
contentStyle: { backgroundColor: c.bg },
}}
>
<Stack.Protected guard={!signedIn}>
<Stack.Screen name="login" options={{ headerShown: false }} />
</Stack.Protected>
<Stack.Protected guard={signedIn}>
<Stack.Screen name="index" options={{ headerShown: false }} />
<Stack.Screen name="scan" options={{ headerShown: false, presentation: 'fullScreenModal' }} />
<Stack.Screen name="client/[serial]/index" options={{ title: 'Client' }} />
<Stack.Screen name="client/[serial]/credit" options={{ title: 'Créditer' }} />
<Stack.Screen name="client/[serial]/rewards" options={{ title: 'Récompenses' }} />
<Stack.Screen name="done" options={{ headerShown: false, gestureEnabled: false }} />
<Stack.Screen name="history" options={{ title: 'Historique' }} />
</Stack.Protected>
</Stack>
);
}
export default function RootLayout() {
const [loaded] = useFonts({ Figtree_400Regular, Figtree_500Medium, Figtree_600SemiBold, Figtree_700Bold, Figtree_800ExtraBold });
if (!loaded) return null;
return (
<SafeAreaProvider>
<SessionProvider>
<StatusBar style="auto" />
<Navigator />
</SessionProvider>
</SafeAreaProvider>
);
}

View file

@ -0,0 +1,114 @@
import { useState } from 'react';
import { Pressable, View } from 'react-native';
import { router, useLocalSearchParams } from 'expo-router';
import * as Haptics from 'expo-haptics';
import { api } from '../../../src/api';
import { useStore } from '../../../src/session';
import { ErrorScreen } from '../../../src/errors';
import { Button, Screen, T, euros, unit } from '../../../src/ui';
import { font, useColors } from '../../../src/theme';
const KEYS = ['1', '2', '3', '4', '5', '6', '7', '8', '9', ',', '0', '⌫'];
type CreditResult = { points: number; balance: number; firstName: string };
/** Saisie du montant (maquette 5) ou confirmation d'un tampon (5b). */
export default function Credit() {
const c = useColors();
const store = useStore();
const { serial } = useLocalSearchParams<{ serial: string }>();
const stamp = store.design.pointsMode === 'STAMP';
const [input, setInput] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState<unknown>(null);
// « 23,5 » → 2350 centimes ; deux décimales maximum.
const cents = Math.round(parseFloat(input.replace(',', '.') || '0') * 100);
const points = stamp ? 1 : Math.floor((cents * store.design.pointsPerEuro) / 100);
const overLimit = cents > store.maxAmountCents;
function press(k: string) {
Haptics.selectionAsync();
if (k === '⌫') return setInput((v) => v.slice(0, -1));
setInput((v) => {
if (k === ',' && (v.includes(',') || v === '')) return v === '' ? '0,' : v;
if (v.includes(',') && v.split(',')[1].length >= 2) return v;
if (v === '0' && k !== ',') return k;
if (v.replace(',', '').length >= 7) return v;
return v + k;
});
}
async function submit() {
setBusy(true);
try {
const r = await api.post<CreditResult>(`/api/staff/cards/${encodeURIComponent(serial)}/credit`, stamp ? {} : { amountCents: cents });
Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
router.replace({
pathname: '/done',
params: { kind: 'credit', firstName: r.firstName, points: String(r.points), balance: String(r.balance) },
});
} catch (e) {
Haptics.notificationAsync(Haptics.NotificationFeedbackType.Error);
setError(e);
} finally {
setBusy(false);
}
}
if (error) return <ErrorScreen error={error} />;
if (stamp) {
return (
<Screen style={{ justifyContent: 'center' }}>
<T v="h1" style={{ textAlign: 'center' }}>+1 tampon</T>
<T v="muted" style={{ textAlign: 'center' }}>Un tampon par passage, quel que soit le montant.</T>
<View style={{ flex: 1 }} />
<Button large label="Valider le tampon" onPress={submit} loading={busy} />
</Screen>
);
}
return (
<Screen>
<View style={{ alignItems: 'center', gap: 6, paddingTop: 8 }}>
<T v="muted">Montant de la commande</T>
<T
accessibilityLabel={`Montant ${euros(cents)}`}
style={{ fontFamily: font.extrabold, fontSize: 52, lineHeight: 60, color: overLimit ? c.err : c.text }}
>
{input || '0'} €
</T>
<T style={{ fontFamily: font.semibold, fontSize: 18, color: overLimit ? c.err : c.primary }}>
{overLimit ? `Plafond : ${euros(store.maxAmountCents)}` : `+ ${points} ${unit('AMOUNT', points)}`}
</T>
</View>
<View style={{ flex: 1, flexDirection: 'row', flexWrap: 'wrap', gap: 10, alignContent: 'flex-end' }}>
{KEYS.map((k) => (
<Pressable
key={k}
accessibilityRole="button"
accessibilityLabel={k === '⌫' ? 'Effacer' : k === ',' ? 'Virgule' : k}
onPress={() => press(k)}
style={({ pressed }) => ({
width: '31%',
flexGrow: 1,
height: 64,
borderRadius: 14,
backgroundColor: pressed ? c.surface2 : c.surface,
borderWidth: 1,
borderColor: c.border,
alignItems: 'center',
justifyContent: 'center',
})}
>
<T style={{ fontFamily: font.semibold, fontSize: 26 }}>{k}</T>
</Pressable>
))}
</View>
<Button large label="Valider" onPress={submit} loading={busy} disabled={points <= 0 || overLimit} />
</Screen>
);
}

View file

@ -0,0 +1,77 @@
import { ActivityIndicator, View } from 'react-native';
import { router } from 'expo-router';
import { useStore } from '../../../src/session';
import { useCard } from '../../../src/useCard';
import { ErrorScreen } from '../../../src/errors';
import { Banner, Button, Card, Screen, T, unit } from '../../../src/ui';
import { font, useColors } from '../../../src/theme';
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, error, reload } = useCard();
if (error) return <ErrorScreen error={error} onRetry={reload} />;
if (!card) return <Screen style={{ justifyContent: 'center' }}><ActivityIndicator /></Screen>;
const mode = store.design.pointsMode;
const cheapest = store.design.rewards[0];
const reachable = store.design.rewards.filter((r) => r.cost <= card.balance).length;
return (
<Screen scroll>
<View style={{ gap: 4 }}>
<T v="h1">{card.firstName}</T>
<T v="muted">
{card.lastCreditAt ? `Dernière visite ${ago(card.lastCreditAt)}` : 'Première visite'} · client depuis le{' '}
{new Date(card.memberSince).toLocaleDateString('fr-FR', { day: 'numeric', month: 'short', year: 'numeric' })}
</T>
</View>
<Card style={{ alignItems: 'center', paddingVertical: 28, backgroundColor: store.design.backgroundColor, borderColor: store.design.backgroundColor }}>
<T style={{ color: store.design.foregroundColor, fontFamily: font.semibold, fontSize: 14, letterSpacing: 1 }}>SOLDE</T>
<T v="big" style={{ color: store.design.foregroundColor }}>{card.balance}</T>
<T style={{ color: store.design.foregroundColor, fontSize: 16 }}>{unit(mode, card.balance)}</T>
</Card>
{reachable > 0 ? (
<Banner tone="ok">{reachable === 1 ? '1 récompense disponible' : `${reachable} récompenses disponibles`}</Banner>
) : cheapest ? (
<T v="muted" style={{ textAlign: 'center' }}>
Encore {cheapest.cost - card.balance} {unit(mode, cheapest.cost - card.balance)} avant « {cheapest.label} »
</T>
) : null}
{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>
)}
<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="Utiliser une récompense"
variant="secondary"
disabled={store.design.rewards.length === 0}
onPress={() => router.push({ pathname: '/client/[serial]/rewards', params: { serial } })}
/>
<T v="muted" style={{ textAlign: 'center', color: c.text3, fontSize: 13 }}>Carte {serial}</T>
</Screen>
);
}

View file

@ -0,0 +1,93 @@
import { useState } from 'react';
import { ActivityIndicator, Alert, Pressable, View } from 'react-native';
import { router } from 'expo-router';
import * as Haptics from 'expo-haptics';
import { api, Reward } from '../../../src/api';
import { useStore } from '../../../src/session';
import { useCard } from '../../../src/useCard';
import { ErrorScreen } from '../../../src/errors';
import { Screen, T, unit } from '../../../src/ui';
import { font, useColors } from '../../../src/theme';
/** Choix d'une récompense (maquette 6) : les accessibles d'abord, les autres grisées. */
export default function Rewards() {
const c = useColors();
const store = useStore();
const { serial, card, error: loadError, reload } = useCard();
const [busy, setBusy] = useState<string | null>(null);
const [error, setError] = useState<unknown>(null);
if (loadError || error) return <ErrorScreen error={loadError ?? error} onRetry={loadError ? reload : undefined} />;
if (!card) return <Screen style={{ justifyContent: 'center' }}><ActivityIndicator /></Screen>;
const mode = store.design.pointsMode;
function confirm(r: Reward) {
Alert.alert(r.label, `Déduire ${r.cost} ${unit(mode, r.cost)} du solde de ${card!.firstName} ?`, [
{ text: 'Annuler', style: 'cancel' },
{ text: 'Valider', onPress: () => redeem(r) },
]);
}
async function redeem(r: Reward) {
setBusy(r.id);
try {
const res = await api.post<{ balance: number; firstName: string }>(`/api/staff/cards/${encodeURIComponent(serial)}/redeem`, {
rewardId: r.id,
});
Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
router.replace({
pathname: '/done',
params: { kind: 'redeem', firstName: res.firstName, reward: r.label, points: String(r.cost), balance: String(res.balance) },
});
} catch (e) {
Haptics.notificationAsync(Haptics.NotificationFeedbackType.Error);
setError(e);
} finally {
setBusy(null);
}
}
const sorted = [...store.design.rewards].sort((a, b) => Number(b.cost <= card.balance) - Number(a.cost <= card.balance) || a.cost - b.cost);
return (
<Screen scroll>
<T v="muted">
Solde de {card.firstName} : <T style={{ fontFamily: font.bold }}>{card.balance} {unit(mode, card.balance)}</T>
</T>
<View style={{ gap: 12 }}>
{sorted.map((r) => {
const ok = r.cost <= card.balance;
return (
<Pressable
key={r.id}
accessibilityRole="button"
accessibilityState={{ disabled: !ok || !!busy }}
disabled={!ok || !!busy}
onPress={() => confirm(r)}
style={({ pressed }) => ({
minHeight: 72,
padding: 16,
borderRadius: 16,
borderWidth: ok ? 2 : 1,
borderColor: ok ? c.primary : c.border,
backgroundColor: ok ? (pressed ? c.primarySoft : c.surface) : c.surface2,
flexDirection: 'row',
alignItems: 'center',
gap: 12,
})}
>
<View style={{ flex: 1, gap: 2 }}>
<T v="label" style={{ fontSize: 17, color: ok ? c.text : c.text3 }}>{r.label}</T>
<T v="muted" style={{ fontSize: 14 }}>
{ok ? `${r.cost} ${unit(mode, r.cost)}` : `Encore ${r.cost - card.balance} ${unit(mode, r.cost - card.balance)}`}
</T>
</View>
{busy === r.id ? <ActivityIndicator /> : ok && <T style={{ color: c.primary, fontFamily: font.bold }}>Utiliser</T>}
</Pressable>
);
})}
</View>
</Screen>
);
}

51
pro/app/done.tsx Normal file
View file

@ -0,0 +1,51 @@
import { useEffect, useRef } from 'react';
import { Animated, View } from 'react-native';
import { router, useLocalSearchParams } from 'expo-router';
import Svg, { Path } from 'react-native-svg';
import { useStore } from '../src/session';
import { Button, Card, Screen, T, unit } from '../src/ui';
import { font, useColors } from '../src/theme';
/** Confirmation (maquette 7) : nouveau solde, Wallet mis à jour. */
export default function Done() {
const c = useColors();
const store = useStore();
const p = useLocalSearchParams<{ kind: 'credit' | 'redeem'; firstName: string; points: string; balance: string; reward?: string }>();
const scale = useRef(new Animated.Value(0.4)).current;
const mode = store.design.pointsMode;
const n = Number(p.points);
useEffect(() => {
Animated.spring(scale, { toValue: 1, friction: 5, useNativeDriver: true }).start();
}, [scale]);
return (
<Screen style={{ justifyContent: 'center', alignItems: 'stretch' }}>
<View style={{ alignItems: 'center', gap: 16 }}>
<Animated.View
style={{ width: 96, height: 96, borderRadius: 48, backgroundColor: c.ok, alignItems: 'center', justifyContent: 'center', transform: [{ scale }] }}
>
<Svg width={48} height={48} viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth={2.6} strokeLinecap="round" strokeLinejoin="round">
<Path d="M5 12.5l4.5 4.5L19 7.5" />
</Svg>
</Animated.View>
<T v="h1" accessibilityRole="alert" style={{ textAlign: 'center' }}>
{p.kind === 'redeem' ? `${p.reward} validé` : `+ ${n} ${unit(mode, n)}`}
</T>
<T v="muted" style={{ textAlign: 'center' }}>
{p.kind === 'redeem' ? `− ${n} ${unit(mode, n)} pour ${p.firstName}` : `pour ${p.firstName}`}
</T>
</View>
<Card style={{ alignItems: 'center' }}>
<T v="muted">Nouveau solde</T>
<T style={{ fontFamily: font.extrabold, fontSize: 44, lineHeight: 50 }}>
{p.balance} <T style={{ fontSize: 20 }}>{unit(mode, Number(p.balance))}</T>
</T>
<T v="muted" style={{ fontSize: 14, textAlign: 'center' }}>Le Wallet du client est mis à jour.</T>
</Card>
<View style={{ flex: 1 }} />
<Button large label="Scanner une autre carte" onPress={() => router.replace('/scan')} />
<Button label="Accueil" variant="secondary" onPress={() => router.dismissTo('/')} />
</Screen>
);
}

134
pro/app/history.tsx Normal file
View file

@ -0,0 +1,134 @@
import { useCallback, useEffect, useState } from 'react';
import { ActivityIndicator, FlatList, Pressable, View } from 'react-native';
import { api, Operation } from '../src/api';
import { useSession, useStore } from '../src/session';
import { Banner, T, euros, unit } from '../src/ui';
import { font, useColors } from '../src/theme';
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 gérant 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;
return (
<View style={{ flex: 1, backgroundColor: c.bg }}>
<View style={{ flexDirection: 'row', gap: 8, padding: 16, paddingBottom: 8 }}>
{(['today', 'week'] as const).map((p) => (
<Pressable
key={p}
accessibilityRole="button"
accessibilityState={{ selected: period === p }}
onPress={() => setPeriod(p)}
style={{
height: 44,
paddingHorizontal: 18,
borderRadius: 22,
justifyContent: 'center',
backgroundColor: period === p ? c.primary : c.surface,
borderWidth: 1,
borderColor: period === p ? c.primary : c.border,
}}
>
<T style={{ fontFamily: font.semibold, color: period === p ? c.onPrimary : c.text }}>{p === 'today' ? "Aujourd'hui" : '7 jours'}</T>
</Pressable>
))}
</View>
<T v="muted" style={{ paddingHorizontal: 16, paddingBottom: 8 }}>
{isManager ? 'Toutes les opérations du magasin' : 'Vos opérations'}
</T>
{error && <View style={{ paddingHorizontal: 16 }}><Banner tone="error">{error}</Banner></View>}
<FlatList
data={items}
keyExtractor={(o) => o.id}
contentContainerStyle={{ paddingHorizontal: 16, paddingBottom: 32 }}
onEndReached={() => cursor && !loading && load(false)}
onEndReachedThreshold={0.5}
refreshing={loading && items.length === 0}
onRefresh={() => load(true)}
ListEmptyComponent={!loading ? <T v="muted" style={{ textAlign: 'center', marginTop: 40 }}>Aucune opération sur la période.</T> : null}
ListFooterComponent={loading && items.length > 0 ? <ActivityIndicator style={{ margin: 16 }} /> : null}
ItemSeparatorComponent={() => <View style={{ height: 1, backgroundColor: c.border }} />}
renderItem={({ item: o }) => {
const rejected = o.type === 'REJECTED';
const time = new Date(o.createdAt).toLocaleString('fr-FR', {
...(period === 'week' && { weekday: 'short' }),
hour: '2-digit',
minute: '2-digit',
});
const what =
o.type === 'REDEEM'
? o.reward?.label ?? 'Récompense'
: rejected
? REASON[o.rejectReason ?? ''] ?? 'Refusé'
: o.amountCents
? euros(o.amountCents)
: 'Passage';
return (
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 12, paddingVertical: 14 }}>
<View style={{ width: 54 }}>
<T v="muted" style={{ fontSize: 14 }}>{time}</T>
</View>
<View style={{ flex: 1, gap: 2 }}>
<T v="label" numberOfLines={1}>{o.customerFirstName}</T>
<T v="muted" numberOfLines={1} style={{ fontSize: 14, color: rejected ? c.err : c.text3 }}>
{what}
{isManager ? ` · ${o.staff.displayName}` : ''}
</T>
</View>
<T
style={{
fontFamily: font.bold,
fontSize: 17,
color: rejected ? c.text3 : o.points > 0 ? c.ok : c.text,
}}
>
{rejected ? '—' : `${o.points > 0 ? '+' : '−'}${Math.abs(o.points)} ${unit(mode, Math.abs(o.points)).slice(0, 3)}.`}
</T>
</View>
);
}}
/>
</View>
);
}

119
pro/app/index.tsx Normal file
View file

@ -0,0 +1,119 @@
import { useCallback, useState } from 'react';
import { Alert, Pressable, RefreshControl, ScrollView, View } from 'react-native';
import { router, useFocusEffect } from 'expo-router';
import { SafeAreaView } from 'react-native-safe-area-context';
import Svg, { Path } from 'react-native-svg';
import { api, Summary } from '../src/api';
import { useSession, useStore } from '../src/session';
import { BrandSymbol, Button, Card, T, unit } from '../src/ui';
import { font, useColors } from '../src/theme';
function ScanIcon({ color }: { color: string }) {
return (
<Svg width={30} height={30} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth={2} strokeLinecap="round">
<Path d="M4 8V5a1 1 0 0 1 1-1h3M16 4h3a1 1 0 0 1 1 1v3M20 16v3a1 1 0 0 1-1 1h-3M8 20H5a1 1 0 0 1-1-1v-3M7 12h10" />
</Svg>
);
}
export default function Home() {
const c = useColors();
const { me, logout } = useSession();
const store = useStore();
const [summary, setSummary] = useState<Summary | null>(null);
const [refreshing, setRefreshing] = useState(false);
const load = useCallback(async () => {
try {
setSummary(await api.get<Summary>('/api/staff/summary'));
} catch {
/* résumé indicatif : on garde l'ancien */
}
}, []);
useFocusEffect(
useCallback(() => {
load();
}, [load]),
);
const isManager = me?.role === 'MANAGER';
const u = unit(store.design.pointsMode);
return (
<SafeAreaView style={{ flex: 1, backgroundColor: c.bg }}>
<ScrollView
contentContainerStyle={{ padding: 20, gap: 20, flexGrow: 1 }}
refreshControl={
<RefreshControl
refreshing={refreshing}
onRefresh={async () => {
setRefreshing(true);
await load();
setRefreshing(false);
}}
/>
}
>
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 12 }}>
<BrandSymbol size={36} />
<View style={{ flex: 1 }}>
<T v="label" numberOfLines={1}>{store.name}</T>
<T v="muted" numberOfLines={1}>
{me?.displayName} · {isManager ? 'Gérant' : 'Employé'}
</T>
</View>
<Pressable
accessibilityRole="button"
hitSlop={12}
onPress={() =>
Alert.alert('Se déconnecter ?', undefined, [
{ text: 'Annuler', style: 'cancel' },
{ text: 'Se déconnecter', style: 'destructive', onPress: logout },
])
}
>
<T v="label" style={{ color: c.primary }}>Déconnexion</T>
</Pressable>
</View>
<Pressable
accessibilityRole="button"
accessibilityLabel="Scanner une carte"
onPress={() => router.push('/scan')}
style={({ pressed }) => ({
backgroundColor: pressed ? c.primaryPressed : c.primary,
borderRadius: 24,
paddingVertical: 48,
alignItems: 'center',
gap: 14,
})}
>
<View style={{ width: 64, height: 64, borderRadius: 32, backgroundColor: 'rgba(255,255,255,0.18)', alignItems: 'center', justifyContent: 'center' }}>
<ScanIcon color={c.onPrimary} />
</View>
<T style={{ color: c.onPrimary, fontFamily: font.bold, fontSize: 24 }}>Scanner une carte</T>
<T style={{ color: c.onPrimary, opacity: 0.85, fontSize: 15 }}>QR code du Wallet du client</T>
</Pressable>
<View style={{ gap: 10 }}>
<T v="h2">{isManager ? "Aujourd'hui au magasin" : "Mes opérations aujourd'hui"}</T>
<View style={{ flexDirection: 'row', gap: 12 }}>
{[
[summary?.operations ?? '—', 'opérations'],
[summary?.pointsGiven ?? '—', `${u} donnés`],
[summary?.rewards ?? '—', 'récompenses'],
].map(([n, l]) => (
<Card key={String(l)} style={{ flex: 1, padding: 14, gap: 2 }}>
<T style={{ fontFamily: font.extrabold, fontSize: 26 }}>{n}</T>
<T v="muted" style={{ fontSize: 13 }}>{l}</T>
</Card>
))}
</View>
</View>
<View style={{ flex: 1 }} />
<Button label="Historique des opérations" variant="secondary" onPress={() => router.push('/history')} />
</ScrollView>
</SafeAreaView>
);
}

84
pro/app/login.tsx Normal file
View file

@ -0,0 +1,84 @@
import { useState } from 'react';
import { KeyboardAvoidingView, Platform, TextInput, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useSession } from '../src/session';
import { Banner, BrandSymbol, Button, T } from '../src/ui';
import { font, useColors } from '../src/theme';
export default function Login() {
const c = useColors();
const { login } = useSession();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
async function submit() {
setBusy(true);
setError(null);
try {
await login(email.trim(), password);
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(false);
}
}
const input = {
height: 56,
borderWidth: 1,
borderColor: '#8A897F',
borderRadius: 12,
paddingHorizontal: 16,
fontSize: 17,
fontFamily: font.regular,
color: c.text,
backgroundColor: c.surface,
};
return (
<SafeAreaView style={{ flex: 1, backgroundColor: c.bg }}>
<KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : undefined} style={{ flex: 1, padding: 24, justifyContent: 'center', gap: 28 }}>
<View style={{ alignItems: 'center', gap: 12 }}>
<BrandSymbol size={64} />
<T v="h1" style={{ textAlign: 'center' }}>
MonEspace<T v="h1" style={{ color: c.primary }}>Pro</T>
</T>
<T v="muted">Espace employés</T>
</View>
{error && <Banner tone="error">{error}</Banner>}
<View style={{ gap: 6 }}>
<T v="label" nativeID="l-email">E-mail</T>
<TextInput
accessibilityLabelledBy="l-email"
style={input}
value={email}
onChangeText={setEmail}
autoCapitalize="none"
autoComplete="email"
keyboardType="email-address"
textContentType="username"
returnKeyType="next"
/>
</View>
<View style={{ gap: 6 }}>
<T v="label" nativeID="l-pwd">Mot de passe</T>
<TextInput
accessibilityLabelledBy="l-pwd"
style={input}
value={password}
onChangeText={setPassword}
secureTextEntry
autoComplete="current-password"
textContentType="password"
returnKeyType="go"
onSubmitEditing={submit}
/>
</View>
<Button label="Se connecter" onPress={submit} loading={busy} disabled={!email || password.length < 8} />
<T v="muted" style={{ textAlign: 'center' }}>Identifiants fournis par votre gérant.</T>
</KeyboardAvoidingView>
</SafeAreaView>
);
}

86
pro/app/scan.tsx Normal file
View file

@ -0,0 +1,86 @@
import { useRef, useState } from 'react';
import { Pressable, StyleSheet, 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 { Button, Screen, T } from '../src/ui';
import { font } from '../src/theme';
/** Les numéros de carte commencent par « MEP » (voir le back-end). */
const SERIAL = /^MEP[A-Z2-9]{16}$/;
export default function Scan() {
const [permission, requestPermission] = useCameraPermissions();
const [torch, setTorch] = useState(false);
const [invalid, setInvalid] = useState(false);
const handled = useRef(false);
if (!permission) return null;
if (!permission.granted) {
return (
<Screen style={{ justifyContent: 'center' }}>
<T v="h1">Accès à la caméra</T>
<T v="muted">La caméra sert uniquement à lire le QR code de la carte de fidélité du client.</T>
{permission.canAskAgain ? (
<Button label="Autoriser la caméra" onPress={requestPermission} />
) : (
<T>Autorisez la caméra pour MonEspacePro Pro dans les réglages du téléphone.</T>
)}
<Button label="Retour" variant="secondary" onPress={() => router.back()} />
</Screen>
);
}
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)) {
setInvalid(true);
return;
}
handled.current = true;
Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
router.replace({ pathname: '/client/[serial]', params: { serial } });
}}
/>
<SafeAreaView style={{ flex: 1, justifyContent: 'space-between', padding: 20 }}>
<T style={{ color: '#fff', fontFamily: font.bold, fontSize: 22, textAlign: 'center' }}>Visez le QR code de la carte</T>
<View style={styles.frame} accessibilityElementsHidden />
<View style={{ gap: 12 }}>
{invalid && (
<T style={{ color: '#fff', textAlign: 'center', backgroundColor: 'rgba(184,50,42,0.9)', padding: 10, borderRadius: 10, overflow: 'hidden' }}>
Ce QR code n'est pas une carte MonEspacePro.
</T>
)}
<View style={{ flexDirection: 'row', gap: 12 }}>
<Pressable accessibilityRole="button" onPress={() => router.back()} style={styles.chip}>
<T style={styles.chipText}>Annuler</T>
</Pressable>
<Pressable
accessibilityRole="button"
accessibilityState={{ selected: torch }}
onPress={() => setTorch((t) => !t)}
style={[styles.chip, torch && { backgroundColor: '#F2B544' }]}
>
<T style={[styles.chipText, torch && { color: '#1C1C19' }]}>{torch ? 'Lampe allumée' : 'Lampe'}</T>
</Pressable>
</View>
</View>
</SafeAreaView>
</View>
);
}
const styles = StyleSheet.create({
frame: { alignSelf: 'center', width: 260, height: 260, borderRadius: 24, borderWidth: 4, borderColor: '#FFFFFF' },
chip: { flex: 1, height: 56, borderRadius: 14, backgroundColor: 'rgba(255,255,255,0.2)', alignItems: 'center', justifyContent: 'center' },
chipText: { color: '#fff', fontFamily: font.bold, fontSize: 17 },
});

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

BIN
pro/assets/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

BIN
pro/assets/splash-icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.1 KiB

9333
pro/package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

36
pro/package.json Normal file
View file

@ -0,0 +1,36 @@
{
"name": "@mep/pro",
"version": "0.1.0",
"private": true,
"main": "expo-router/entry",
"scripts": {
"start": "expo start",
"android": "expo start --android",
"ios": "expo start --ios",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@expo-google-fonts/figtree": "^0.4.1",
"expo": "^54.0.0",
"expo-camera": "~17.0.10",
"expo-constants": "~18.0.14",
"expo-font": "~14.0.12",
"expo-haptics": "~15.0.8",
"expo-linking": "~8.0.12",
"expo-router": "~6.0.24",
"expo-secure-store": "~15.0.8",
"expo-splash-screen": "~31.0.13",
"expo-status-bar": "~3.0.9",
"expo-system-ui": "~6.0.9",
"react": "19.1.0",
"react-dom": "^19.1.0",
"react-native": "0.81.5",
"react-native-safe-area-context": "~5.6.0",
"react-native-screens": "~4.16.0",
"react-native-svg": "15.12.1"
},
"devDependencies": {
"@types/react": "~19.1.10",
"typescript": "~5.9.2"
}
}

166
pro/src/api.ts Normal file
View file

@ -0,0 +1,166 @@
import * as SecureStore from 'expo-secure-store';
/**
* Client de l'API MonEspacePro. Le jeton de rafraîchissement est rangé dans
* le trousseau (SecureStore) ; le jeton d'accès reste en mémoire.
* En développement : EXPO_PUBLIC_API_URL=http://<IP du PC>:3100 dans pro/.env
*/
export const API_URL = (process.env.EXPO_PUBLIC_API_URL ?? 'http://localhost:3100').replace(/\/$/, '');
const REFRESH_KEY = 'mep.refresh';
let accessToken: string | null = null;
let onLogout: () => void = () => undefined;
export class ApiError extends Error {
constructor(
public status: number,
message: string,
public code?: string,
public data: Record<string, unknown> = {},
) {
super(message);
}
}
export function setLogoutHandler(fn: () => void) {
onLogout = fn;
}
export async function hasSession() {
return !!(await SecureStore.getItemAsync(REFRESH_KEY));
}
async function storeTokens(t: { accessToken: string; refreshToken: string }) {
accessToken = t.accessToken;
await SecureStore.setItemAsync(REFRESH_KEY, t.refreshToken);
}
export async function logout() {
accessToken = null;
await SecureStore.deleteItemAsync(REFRESH_KEY);
onLogout();
}
export async function login(email: string, password: string) {
const res = await request<{ accessToken: string; refreshToken: string }>('POST', '/api/auth/staff/login', { email, password }, false);
await storeTokens(res);
}
let refreshing: Promise<boolean> | null = null;
function refresh(): Promise<boolean> {
refreshing ??= (async () => {
const token = await SecureStore.getItemAsync(REFRESH_KEY);
if (!token) return false;
try {
const r = await fetch(`${API_URL}/api/auth/refresh`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ refreshToken: token }),
});
if (!r.ok) return false;
await storeTokens(await r.json());
return true;
} catch {
return false;
}
})().finally(() => {
refreshing = null;
});
return refreshing;
}
async function request<T>(method: string, path: string, body?: unknown, auth = true, retry = true): Promise<T> {
if (auth && !accessToken) await refresh();
let res: Response;
try {
res = await fetch(`${API_URL}${path}`, {
method,
headers: {
...(body !== undefined && { 'Content-Type': 'application/json' }),
...(auth && accessToken && { Authorization: `Bearer ${accessToken}` }),
},
body: body === undefined ? undefined : JSON.stringify(body),
});
} catch {
throw new ApiError(0, 'Pas de connexion au serveur. Vérifiez le réseau.', 'NETWORK');
}
if (res.status === 401 && auth) {
if (retry && (await refresh())) return request(method, path, body, auth, false);
await logout();
}
const text = await res.text();
const data = text ? JSON.parse(text) : null;
if (!res.ok) {
const msg = Array.isArray(data?.message) ? data.message.join(' · ') : data?.message;
throw new ApiError(res.status, msg || 'Une erreur est survenue', data?.code, data ?? {});
}
return data as T;
}
export const api = {
get: <T>(path: string) => request<T>('GET', path),
post: <T>(path: string, body: unknown = {}) => request<T>('POST', path, body),
};
// ── Types de l'API ─────────────────────────────────────────────
export type StaffRole = 'MANAGER' | 'EMPLOYEE';
export type PointsMode = 'AMOUNT' | 'STAMP';
export interface Reward {
id: string;
label: string;
cost: number;
}
export interface Me {
id: string;
displayName: string;
role: StaffRole;
store: {
id: string;
name: string;
city: string;
maxAmountCents: number;
minScanIntervalSec: number;
cardDesign: {
programName: string;
backgroundColor: string;
foregroundColor: string;
pointsMode: PointsMode;
pointsPerEuro: number;
logoUrl: string | null;
rewards: Reward[];
} | null;
};
}
export interface CardInfo {
serial: string;
firstName: string;
balance: number;
memberSince: string;
lastCreditAt: string | null;
nextCreditAt: string | null;
}
export interface Summary {
operations: number;
pointsGiven: number;
rewards: number;
}
export type TransactionType = 'CREDIT' | 'REDEEM' | 'ADJUST' | 'REJECTED';
export type RejectReason = 'AMOUNT_OVER_LIMIT' | 'TOO_SOON' | 'INSUFFICIENT_BALANCE';
export interface Operation {
id: string;
type: TransactionType;
amountCents: number | null;
points: number;
balanceAfter: number;
rejectReason: RejectReason | null;
createdAt: string;
reward: { label: string } | null;
staff: { id: string; displayName: string };
customerFirstName: string;
}

54
pro/src/errors.tsx Normal file
View file

@ -0,0 +1,54 @@
import { View } from 'react-native';
import { router } from 'expo-router';
import { ApiError } from './api';
import { Button, Screen, T, euros } from './ui';
import { useColors } from './theme';
function minutes(sec: number) {
const m = Math.ceil(sec / 60);
return m <= 1 ? '1 min' : `${m} min`;
}
/** Message et conseil pour chaque refus de l'anti-triche (maquettes 8a/8b/8c). */
export function describe(e: unknown): { title: string; detail: string } {
if (!(e instanceof ApiError)) return { title: 'Erreur inattendue', detail: String(e) };
const d = e.data as Record<string, number>;
switch (e.code) {
case 'AMOUNT_OVER_LIMIT':
return {
title: `Montant supérieur au plafond (${euros(d.maxAmountCents)})`,
detail: "Vérifiez le montant saisi. Pour une commande exceptionnelle, contactez votre gérant. La tentative a été enregistrée.",
};
case 'TOO_SOON':
return {
title: `Carte déjà créditée il y a ${minutes(d.elapsedSec || 60)}`,
detail: `Réessayez dans ${minutes(d.retryAfterSec)}. Ce délai évite les doubles crédits. La tentative a été enregistrée.`,
};
case 'OTHER_STORE':
return { title: "Carte d'un autre magasin", detail: "Ce client n'est pas inscrit au programme de votre magasin. Il peut s'inscrire avec le QR du comptoir." };
case 'UNKNOWN_CARD':
return { title: 'Carte inconnue', detail: "Cette carte n'existe plus (supprimée par le client ?). Il peut se réinscrire avec le QR du comptoir." };
case 'INSUFFICIENT_BALANCE':
return { title: 'Solde insuffisant', detail: `Il manque ${d.missing} pour cette récompense.` };
default:
return { title: 'Opération impossible', detail: e.message };
}
}
export function ErrorScreen({ error, onRetry }: { error: unknown; onRetry?: () => void }) {
const c = useColors();
const { title, detail } = describe(error);
return (
<Screen style={{ justifyContent: 'center' }}>
<View style={{ width: 64, height: 64, borderRadius: 32, backgroundColor: c.errBg, alignItems: 'center', justifyContent: 'center' }}>
<T style={{ color: c.err, fontSize: 32, lineHeight: 36 }} accessibilityElementsHidden>!</T>
</View>
<T v="h1" accessibilityRole="alert">{title}</T>
<T v="muted">{detail}</T>
<View style={{ flex: 1 }} />
{onRetry && <Button label="Réessayer" onPress={onRetry} />}
<Button label="Scanner une autre carte" variant={onRetry ? 'secondary' : 'primary'} onPress={() => router.replace('/scan')} />
<Button label="Accueil" variant="secondary" onPress={() => router.dismissTo('/')} />
</Screen>
);
}

60
pro/src/session.tsx Normal file
View file

@ -0,0 +1,60 @@
import { createContext, ReactNode, useCallback, useContext, useEffect, useState } from 'react';
import { api, hasSession, login as apiLogin, logout as apiLogout, Me, setLogoutHandler } from './api';
type Session = {
status: 'loading' | 'signed-out' | 'signed-in';
me: Me | null;
login: (email: string, password: string) => Promise<void>;
logout: () => Promise<void>;
reload: () => Promise<void>;
};
const SessionContext = createContext<Session | null>(null);
export function SessionProvider({ children }: { children: ReactNode }) {
const [status, setStatus] = useState<Session['status']>('loading');
const [me, setMe] = useState<Me | null>(null);
const reload = useCallback(async () => {
try {
setMe(await api.get<Me>('/api/staff/me'));
setStatus('signed-in');
} catch {
// 401 → logout() a déjà été appelé ; erreur réseau → on garde l'écran de connexion.
setStatus((s) => (s === 'signed-in' ? s : 'signed-out'));
}
}, []);
useEffect(() => {
setLogoutHandler(() => {
setMe(null);
setStatus('signed-out');
});
hasSession().then((ok) => (ok ? reload() : setStatus('signed-out')));
}, [reload]);
const login = useCallback(
async (email: string, password: string) => {
await apiLogin(email, password);
await reload();
},
[reload],
);
return (
<SessionContext.Provider value={{ status, me, login, logout: apiLogout, reload }}>{children}</SessionContext.Provider>
);
}
export function useSession() {
const s = useContext(SessionContext);
if (!s) throw new Error('SessionProvider manquant');
return s;
}
/** Le design de la carte est garanti côté serveur pour un magasin actif. */
export function useStore() {
const { me } = useSession();
if (!me?.store.cardDesign) throw new Error('Magasin sans carte');
return { ...me.store, design: me.store.cardDesign };
}

58
pro/src/theme.ts Normal file
View file

@ -0,0 +1,58 @@
import { useColorScheme } from 'react-native';
/** Tokens du design system MonEspacePro (mêmes valeurs que l'admin). */
const light = {
primary: '#0E7A66',
primaryPressed: '#0B6253',
primarySoft: '#EAF6F2',
onPrimary: '#FFFFFF',
accent: '#F2B544',
bg: '#F6F6F3',
surface: '#FFFFFF',
surface2: '#EEEDE8',
border: '#DEDDD6',
text: '#1C1C19',
text2: '#45443E',
text3: '#5F5E56',
ok: '#1E7A3C',
okBg: '#E5F3E9',
warn: '#8F5300',
warnBg: '#FCEFD6',
err: '#B8322A',
errBg: '#FBE7E5',
};
const dark: typeof light = {
primary: '#3CB59C',
primaryPressed: '#5CC7B0',
primarySoft: '#143A33',
onPrimary: '#0B1F1B',
accent: '#F2B544',
bg: '#141412',
surface: '#1D1D1A',
surface2: '#272723',
border: '#34342F',
text: '#F2F1EC',
text2: '#CFCEC6',
text3: '#A5A49B',
ok: '#6FCF8F',
okBg: '#173523',
warn: '#F2B544',
warnBg: '#3A2B10',
err: '#F08A80',
errBg: '#3D1A17',
};
export type Colors = typeof light;
export function useColors(): Colors {
return useColorScheme() === 'dark' ? dark : light;
}
export const font = {
regular: 'Figtree_400Regular',
medium: 'Figtree_500Medium',
semibold: 'Figtree_600SemiBold',
bold: 'Figtree_700Bold',
extrabold: 'Figtree_800ExtraBold',
};

115
pro/src/ui.tsx Normal file
View file

@ -0,0 +1,115 @@
import { ReactNode } from 'react';
import { ActivityIndicator, Pressable, ScrollView, StyleSheet, Text, TextProps, View, ViewStyle } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import Svg, { Circle, Path } from 'react-native-svg';
import { font, useColors } from './theme';
export function Screen({ children, scroll = false, style }: { children: ReactNode; scroll?: boolean; style?: ViewStyle }) {
const c = useColors();
const inner = <View style={[{ padding: 20, gap: 20, flexGrow: 1 }, style]}>{children}</View>;
return (
<SafeAreaView style={{ flex: 1, backgroundColor: c.bg }} edges={['bottom', 'left', 'right']}>
{scroll ? <ScrollView contentContainerStyle={{ flexGrow: 1 }}>{inner}</ScrollView> : inner}
</SafeAreaView>
);
}
type Variant = 'h1' | 'h2' | 'body' | 'label' | 'muted' | 'big';
export function T({ v = 'body', style, ...props }: TextProps & { v?: Variant }) {
const c = useColors();
const s = {
h1: { fontFamily: font.bold, fontSize: 28, lineHeight: 34, color: c.text },
h2: { fontFamily: font.bold, fontSize: 20, lineHeight: 26, color: c.text },
body: { fontFamily: font.regular, fontSize: 17, lineHeight: 24, color: c.text },
label: { fontFamily: font.semibold, fontSize: 15, lineHeight: 20, color: c.text },
muted: { fontFamily: font.regular, fontSize: 15, lineHeight: 21, color: c.text3 },
big: { fontFamily: font.extrabold, fontSize: 56, lineHeight: 62, color: c.text },
}[v];
return <Text {...props} style={[s, style]} />;
}
export function Button({
label,
onPress,
variant = 'primary',
disabled,
loading,
icon,
large,
}: {
label: string;
onPress: () => void;
variant?: 'primary' | 'secondary' | 'danger';
disabled?: boolean;
loading?: boolean;
icon?: ReactNode;
large?: boolean;
}) {
const c = useColors();
const bg = { primary: c.primary, secondary: c.surface, danger: c.err }[variant];
const fg = variant === 'secondary' ? c.text : c.onPrimary;
return (
<Pressable
accessibilityRole="button"
accessibilityState={{ disabled: !!disabled || !!loading }}
disabled={disabled || loading}
onPress={onPress}
style={({ pressed }) => [
styles.btn,
{
backgroundColor: variant === 'primary' && pressed ? c.primaryPressed : bg,
borderColor: variant === 'secondary' ? c.border : bg,
minHeight: large ? 72 : 56,
opacity: disabled ? 0.5 : pressed && variant !== 'primary' ? 0.8 : 1,
},
]}
>
{loading ? (
<ActivityIndicator color={fg} />
) : (
<>
{icon}
<Text style={{ fontFamily: font.bold, fontSize: large ? 20 : 17, color: fg }}>{label}</Text>
</>
)}
</Pressable>
);
}
export function Card({ children, style }: { children: ReactNode; style?: ViewStyle }) {
const c = useColors();
return <View style={[{ backgroundColor: c.surface, borderColor: c.border, borderWidth: 1, borderRadius: 16, padding: 18, gap: 8 }, style]}>{children}</View>;
}
export function Banner({ tone, children }: { tone: 'error' | 'warn' | 'ok'; children: ReactNode }) {
const c = useColors();
const [bg, fg] = { error: [c.errBg, c.err], warn: [c.warnBg, c.warn], ok: [c.okBg, c.ok] }[tone];
return (
<View accessibilityRole="alert" style={{ backgroundColor: bg, borderRadius: 12, padding: 14 }}>
<Text style={{ color: fg, fontFamily: font.semibold, fontSize: 15, lineHeight: 21 }}>{children}</Text>
</View>
);
}
/** Symbole officiel MonEspacePro. */
export function BrandSymbol({ size = 32, arch }: { size?: number; arch?: string }) {
const c = useColors();
return (
<Svg width={size} height={size} viewBox="0.5 -2 64 64">
<Path d="M12 54V32a9 9 0 0 1 18 0v22M30 32a9 9 0 0 1 18 0v22" fill="none" stroke={arch ?? c.primary} strokeWidth={8} />
<Circle cx={51} cy={12} r={6} fill="#F2B544" />
</Svg>
);
}
export const euros = (cents: number) => (cents / 100).toLocaleString('fr-FR', { style: 'currency', currency: 'EUR' });
export function unit(mode: 'AMOUNT' | 'STAMP', n = 2) {
if (mode === 'STAMP') return n > 1 ? 'tampons' : 'tampon';
return n > 1 ? 'points' : 'point';
}
const styles = StyleSheet.create({
btn: { borderRadius: 14, borderWidth: 1, paddingHorizontal: 20, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: 10 },
});

25
pro/src/useCard.ts Normal file
View file

@ -0,0 +1,25 @@
import { useCallback, useEffect, useState } from 'react';
import { useLocalSearchParams } from 'expo-router';
import { api, CardInfo } from './api';
/** Carte scannée (paramètre de route `serial`), rechargeable. */
export function useCard() {
const { serial } = useLocalSearchParams<{ serial: string }>();
const [card, setCard] = useState<CardInfo | null>(null);
const [error, setError] = useState<unknown>(null);
const load = useCallback(async () => {
setError(null);
try {
setCard(await api.get<CardInfo>(`/api/staff/cards/${encodeURIComponent(serial)}`));
} catch (e) {
setError(e);
}
}, [serial]);
useEffect(() => {
load();
}, [load]);
return { serial, card, error, reload: load };
}

7
pro/tsconfig.json Normal file
View file

@ -0,0 +1,7 @@
{
"extends": "expo/tsconfig.base",
"compilerOptions": {
"strict": true
},
"include": ["**/*.ts", "**/*.tsx", ".expo/types/**/*.ts", "expo-env.d.ts"]
}