import { Injectable, Logger, NotFoundException, OnApplicationBootstrap, OnApplicationShutdown } from '@nestjs/common'; import { PrismaService } from '../prisma/prisma.service'; import { parisDate } from '../birthdays/birthdays.service'; import { EntitlementsService } from '../billing/entitlements.service'; import { CardUpdatesService } from '../wallet/card-updates.service'; import { CARD_WITH_CONTEXT, DEFAULT_REMINDER, reminderText } from '../wallet/wallet.types'; export const REMINDER_DAYS = [30, 45, 60, 90]; /** Envois seulement entre 10 h et 19 h (heure de Paris) : pas de notification la nuit. */ const SEND_HOURS = { from: 10, to: 19 }; /** Plafond par magasin et par passage horaire, pour étaler les envois. */ const BATCH = 200; const DAY = 24 * 3600_000; export interface ReminderSettings { enabled: boolean; days: number; message: string | null; } /** * Relance automatique : un client sans crédit depuis N jours reçoit une notification * sur sa carte Wallet. Une seule relance par période d'inactivité : il faut qu'il * revienne (nouveau crédit) pour pouvoir être relancé à nouveau. */ @Injectable() export class RemindersService implements OnApplicationBootstrap, OnApplicationShutdown { private readonly logger = new Logger(RemindersService.name); private timer?: NodeJS.Timeout; private running = false; constructor( private prisma: PrismaService, private entitlements: EntitlementsService, private cardUpdates: CardUpdatesService, ) {} onApplicationBootstrap() { this.timer = setInterval(() => void this.tick(), 3600_000); setTimeout(() => void this.tick(), 60_000); } onApplicationShutdown() { clearInterval(this.timer); } async overview(storeId: string) { const store = await this.prisma.store.findUnique({ where: { id: storeId } }); if (!store) throw new NotFoundException('Magasin introuvable'); const since = new Date(Date.now() - 30 * DAY); const [allowed, pending, sentLast30Days, reminded] = await Promise.all([ this.entitlements.can(storeId, 'inactiveReminders'), this.candidates(storeId, store.reminderDays, Number.MAX_SAFE_INTEGER), this.prisma.loyaltyCard.count({ where: { storeId, reminderSentAt: { gte: since } } }), this.prisma.loyaltyCard.findMany({ where: { storeId, reminderSentAt: { not: null } }, select: { reminderSentAt: true, lastCreditAt: true }, }), ]); return { allowed, settings: { enabled: store.reminderEnabled, days: store.reminderDays, message: store.reminderMessage } as ReminderSettings, defaultMessage: DEFAULT_REMINDER, dayChoices: REMINDER_DAYS, stats: { /** Clients actuellement inactifs et pas encore relancés. */ pending: pending.length, sentLast30Days, /** Clients relancés revenus depuis (nouveau crédit après la relance). */ cameBack: reminded.filter((c) => c.lastCreditAt && c.lastCreditAt > c.reminderSentAt!).length, totalReminded: reminded.length, }, }; } async update(storeId: string, settings: ReminderSettings) { if (settings.enabled) await this.entitlements.require(storeId, 'inactiveReminders'); await this.prisma.store.update({ where: { id: storeId }, data: { reminderEnabled: settings.enabled, reminderDays: settings.days, reminderMessage: settings.message?.replace(/\s+/g, ' ').trim() || null, }, }); return this.overview(storeId); } /** Cartes inactives depuis `days` jours et pas encore relancées depuis leur dernière visite. */ private async candidates(storeId: string, days: number, take: number) { const cutoff = new Date(Date.now() - days * DAY); const cards = await this.prisma.loyaltyCard.findMany({ where: { storeId, OR: [{ lastCreditAt: { lt: cutoff } }, { lastCreditAt: null, createdAt: { lt: cutoff } }], }, select: { id: true, lastCreditAt: true, createdAt: true, reminderSentAt: true }, orderBy: { createdAt: 'asc' }, }); return cards.filter((c) => !c.reminderSentAt || c.reminderSentAt < (c.lastCreditAt ?? c.createdAt)).slice(0, take); } /** Passage horaire. */ async tick(now = new Date()) { if (this.running) return; const { hour } = parisDate(now); if (hour < SEND_HOURS.from || hour >= SEND_HOURS.to) return; this.running = true; try { const stores = await this.prisma.store.findMany({ where: { reminderEnabled: true, status: 'ACTIVE', billingSuspended: false }, select: { id: true, name: true, reminderDays: true }, }); for (const store of stores) { if (!(await this.entitlements.can(store.id, 'inactiveReminders'))) continue; const sent = await this.runStore(store); if (sent) this.logger.log(`Relance : ${sent} client(s) de ${store.name}`); } } catch (e) { this.logger.error(`Relance des inactifs : ${(e as Error).message}`); } finally { this.running = false; } } private async runStore(store: { id: string; name: string; reminderDays: number }) { let sent = 0; for (const { id } of await this.candidates(store.id, store.reminderDays, BATCH)) { // reminderSentAt + passUpdatedAt d'abord : l'iPhone qui redemande la carte y trouve le texte de relance. const card = await this.prisma.loyaltyCard.update({ where: { id }, data: { reminderSentAt: new Date(), passUpdatedAt: new Date() }, include: CARD_WITH_CONTEXT, }); try { await this.cardUpdates.remind(card.id, reminderText(card), store.name); sent++; } catch (e) { this.logger.warn(`Relance carte ${card.serial} : ${(e as Error).message}`); } } return sent; } }