diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index 9a97ade..8bb687d 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -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) ──────────────────────── diff --git a/backend/src/app.module.ts b/backend/src/app.module.ts index fd11f93..52d96c6 100644 --- a/backend/src/app.module.ts +++ b/backend/src/app.module.ts @@ -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 }], diff --git a/backend/src/counter/counter.controller.ts b/backend/src/counter/counter.controller.ts new file mode 100644 index 0000000..2c8911c --- /dev/null +++ b/backend/src/counter/counter.controller.ts @@ -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); + } +} diff --git a/backend/src/counter/counter.module.ts b/backend/src/counter/counter.module.ts new file mode 100644 index 0000000..fe55c46 --- /dev/null +++ b/backend/src/counter/counter.module.ts @@ -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 {} diff --git a/backend/src/counter/counter.service.ts b/backend/src/counter/counter.service.ts new file mode 100644 index 0000000..fb70ca2 --- /dev/null +++ b/backend/src/counter/counter.service.ts @@ -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 = {}) { + 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>) { + 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, + }, + }); + } +} diff --git a/backend/src/wallet/card-updates.service.ts b/backend/src/wallet/card-updates.service.ts new file mode 100644 index 0000000..30b0f62 --- /dev/null +++ b/backend/src/wallet/card-updates.service.ts @@ -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)`); + } +} diff --git a/pro/.env.example b/pro/.env.example new file mode 100644 index 0000000..ea175f2 --- /dev/null +++ b/pro/.env.example @@ -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 diff --git a/pro/.npmrc b/pro/.npmrc new file mode 100644 index 0000000..bef8c5c --- /dev/null +++ b/pro/.npmrc @@ -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 diff --git a/pro/app.json b/pro/app.json new file mode 100644 index 0000000..36173f8 --- /dev/null +++ b/pro/app.json @@ -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 + } + } +} diff --git a/pro/app/_layout.tsx b/pro/app/_layout.tsx new file mode 100644 index 0000000..079c4a7 --- /dev/null +++ b/pro/app/_layout.tsx @@ -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 ( + + + + + + + + + + + + + + + ); +} + +export default function RootLayout() { + const [loaded] = useFonts({ Figtree_400Regular, Figtree_500Medium, Figtree_600SemiBold, Figtree_700Bold, Figtree_800ExtraBold }); + if (!loaded) return null; + return ( + + + + + + + ); +} diff --git a/pro/app/client/[serial]/credit.tsx b/pro/app/client/[serial]/credit.tsx new file mode 100644 index 0000000..ae56082 --- /dev/null +++ b/pro/app/client/[serial]/credit.tsx @@ -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(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(`/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 ; + + if (stamp) { + return ( + + +1 tampon + Un tampon par passage, quel que soit le montant. + +