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'; import { ReferralsService } from '../referrals/referrals.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, private referrals: ReferralsService, ) {} 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); // Premier passage d'un filleul : récompenses du parrainage (en arrière-plan). this.referrals.onCredit(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, }, }); } }