import { Injectable, Logger } from '@nestjs/common'; import { PrismaService } from '../prisma/prisma.service'; import { ApnsService } from './apns.service'; import { GoogleWalletService } from './google-wallet.service'; import { CARD_WITH_CONTEXT } from './wallet.types'; /** * Point d'entrée unique « une carte a changé » : pousse la mise à jour vers * Apple Wallet (notification APNs → l'iPhone redemande la carte) et Google * Wallet (mise à jour de l'objet). Jamais bloquant : appelé après la réponse * à l'employé, une erreur ici n'annule pas l'opération au comptoir. */ @Injectable() export class CardUpdatesService { private readonly logger = new Logger(CardUpdatesService.name); constructor( private prisma: PrismaService, private apns: ApnsService, private google: GoogleWalletService, ) {} /** Solde ou récompense d'une carte modifiés. */ notify(cardId: string) { void this.run(`carte ${cardId}`, async () => { const card = await this.prisma.loyaltyCard.update({ where: { id: cardId }, data: { passUpdatedAt: new Date() }, include: { ...CARD_WITH_CONTEXT, devices: { include: { device: true } } }, }); await Promise.all([ this.pushApple(card.devices.map((r) => r.device.pushToken)), this.google.updateObject(card), ]); }); } /** Design du magasin modifié (logo, couleurs, récompenses) : toutes ses cartes. */ notifyStore(storeId: string) { void this.run(`magasin ${storeId}`, async () => { await this.prisma.loyaltyCard.updateMany({ where: { storeId }, data: { passUpdatedAt: new Date() } }); const store = await this.prisma.store.findUniqueOrThrow({ where: { id: storeId }, include: CARD_WITH_CONTEXT.store.include, }); const devices = await this.prisma.appleDevice.findMany({ where: { registrations: { some: { card: { storeId } } } }, select: { pushToken: true }, }); await Promise.all([this.pushApple(devices.map((d) => d.pushToken)), this.google.updateClass(store)]); // Les récompenses apparaissent sur chaque carte Google (objet) : on les met à jour aussi. const cards = await this.prisma.loyaltyCard.findMany({ where: { storeId }, include: CARD_WITH_CONTEXT }); for (const card of cards) await this.google.updateObject(card).catch((e) => this.logger.warn(e.message)); }); } private async pushApple(tokens: string[]) { const gone = await this.apns.push([...new Set(tokens)]); if (gone.length) await this.prisma.appleDevice.deleteMany({ where: { pushToken: { in: gone } } }); } private async run(label: string, task: () => Promise) { try { await task(); } catch (e) { this.logger.error(`Mise à jour Wallet (${label}) : ${(e as Error).message}`); } } }