import { ConflictException, Injectable, Logger, NotFoundException } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { randomBytes, timingSafeEqual } from 'crypto'; import { PrismaService } from '../prisma/prisma.service'; import { MailService } from '../mail/mail.service'; import { CARD_WITH_CONTEXT, CardWithContext } from '../wallet/wallet.types'; import { emailLayout, esc } from '../mail/email-layout'; /** Alphabet sans caractères ambigus : le numéro peut être lu à voix haute au comptoir. */ const SERIAL_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; function randomSerial() { const bytes = randomBytes(16); return 'MEP' + [...bytes].map((b) => SERIAL_ALPHABET[b % SERIAL_ALPHABET.length]).join(''); } const token = () => randomBytes(24).toString('base64url'); /** « tony.prive@gmail.com » → « t•••@g•••.com » */ export function maskEmail(email: string) { const [user, domain = ''] = email.split('@'); const dot = domain.lastIndexOf('.'); const host = dot > 0 ? domain.slice(0, dot) : domain; const tld = dot > 0 ? domain.slice(dot) : ''; return `${user[0]}•••@${host[0] ?? ''}•••${tld}`; } export type EnrollResult = { status: 'created'; cardUrl: string } | { status: 'exists'; maskedEmail: string }; @Injectable() export class EnrollmentService { private readonly logger = new Logger(EnrollmentService.name); constructor( private prisma: PrismaService, private mail: MailService, private config: ConfigService, ) {} findStore(slug: string) { return this.prisma.store.findUnique({ where: { slug }, include: CARD_WITH_CONTEXT.store.include, }); } /** Inscription ouverte uniquement si le magasin est actif et sa carte conçue. */ private async openStore(slug: string) { const store = await this.findStore(slug); if (!store) throw new NotFoundException('Programme introuvable'); if (store.status !== 'ACTIVE' || !store.cardDesign) throw new ConflictException('Programme indisponible'); return store; } async enroll(slug: string, firstName: string, rawEmail: string): Promise { const store = await this.openStore(slug); const email = rawEmail.toLowerCase(); const existing = await this.findCardByEmail(store.id, email); if (existing) return { status: 'exists', maskedEmail: maskEmail(email) }; const card = await this.prisma.loyaltyCard.create({ data: { serial: randomSerial(), authToken: token(), accessKey: token(), store: { connect: { id: store.id } }, customer: { create: { firstName, email, consentAt: new Date() } }, }, include: CARD_WITH_CONTEXT, }); this.sendCardLink(card, true).catch((e) => this.logger.error(`E-mail d'inscription non envoyé : ${e.message}`)); return { status: 'created', cardUrl: this.cardUrl(card) }; } /** Réponse identique que la carte existe ou non : rien n'est révélé. */ async resend(slug: string, rawEmail: string) { const store = await this.findStore(slug); if (!store) return; const card = await this.findCardByEmail(store.id, rawEmail.toLowerCase()); if (card) await this.sendCardLink(card, false); } /** Carte accessible par son lien secret ; null si le lien est faux. */ async findCard(serial: string, key: string | undefined): Promise { if (!key) return null; const card = await this.prisma.loyaltyCard.findUnique({ where: { serial }, include: CARD_WITH_CONTEXT }); if (!card || card.store.status === 'CLOSED') return null; const a = Buffer.from(card.accessKey); const b = Buffer.from(key); return a.length === b.length && timingSafeEqual(a, b) ? card : null; } /** Droit à l'effacement : la carte et les données du client disparaissent. */ async deleteCard(card: CardWithContext) { await this.prisma.$transaction(async (tx) => { await tx.loyaltyCard.delete({ where: { id: card.id } }); const others = await tx.loyaltyCard.count({ where: { customerId: card.customerId } }); if (others === 0) await tx.customer.delete({ where: { id: card.customerId } }); }); } cardUrl(card: { serial: string; accessKey: string }) { return `${this.config.get('webUrl')}/carte/${card.serial}?k=${card.accessKey}`; } private findCardByEmail(storeId: string, email: string) { return this.prisma.loyaltyCard.findFirst({ where: { storeId, customer: { email } }, include: CARD_WITH_CONTEXT }); } private async sendCardLink(card: CardWithContext, isNew: boolean) { const url = this.cardUrl(card); const program = card.store.cardDesign?.programName ?? card.store.name; const subject = isNew ? `Votre carte ${program}` : `Le lien de votre carte ${program}`; const intro = isNew ? `Bienvenue dans le programme ${program} de ${card.store.name} !` : `Voici le lien de votre carte ${program}, comme demandé.`; const text = `Bonjour ${card.customer.firstName},\n\n${intro}\n\nOuvrez ce lien sur votre téléphone pour ajouter la carte à Apple Wallet ou Google Wallet :\n${url}\n\nGardez cet e-mail : il vous permet de retrouver votre carte si vous changez de téléphone.\n\n${card.store.name}`; const unit = card.store.cardDesign?.pointsMode === 'STAMP' ? 'tampons' : 'points'; const reward = card.store.cardDesign?.rewards?.[0]; const html = emailLayout({ webUrl: this.config.get('webUrl')!, preheader: isNew ? `Ajoutez votre carte ${program} à votre téléphone.` : `Le lien de votre carte ${program}.`, eyebrow: card.store.name, title: isNew ? `Votre carte est prête, ${card.customer.firstName} !` : 'Voici le lien de votre carte', paragraphs: [ isNew ? `Bienvenue dans le programme ${esc(program)} de ${esc(card.store.name)}.` : `Comme demandé, voici le lien de votre carte ${esc(program)}.`, 'Ouvrez ce lien sur votre téléphone pour ajouter la carte à Apple Wallet ou Google Wallet, puis présentez-la au comptoir à chaque passage.', ], cta: { label: 'Ajouter ma carte à mon téléphone', url }, details: [ ['Programme', esc(program)], ['Solde', `${card.balance} ${unit}`], ...(reward ? ([['Récompense', `${esc(reward.label)} à ${reward.cost} ${unit}`]] as [string, string][]) : []), ], note: 'Gardez cet e-mail : il vous permet de retrouver votre carte si vous changez de téléphone.', footnote: `Vous recevez cet e-mail car vous vous êtes inscrit au programme de fidélité de ${esc(card.store.name)}. Vous pouvez supprimer votre carte à tout moment depuis le lien ci-dessus.`, }); await this.mail.send(card.customer.email, subject, text, html); } }