Compare commits

..

2 commits

Author SHA1 Message Date
166f7888cd Offre d'anniversaire (formule Pro)
- Anniversaire facultatif (jour + mois) à l'inscription ou sur la page de la carte
- Réglages par magasin : activation, points/tampons offerts, message {prenom} {cadeau}
- Passage horaire 9 h–19 h (Paris), un cadeau par an, 29 février fêté le 28
- Notification Apple (Actualité) et Google, solde mis à jour
- Admin : onglet Fidélisation ; app Pro : écran gérant
- Politique de confidentialité mise à jour
- Migration manuelle 2026-10-07-anniversaire.sql

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 10:33:15 +02:00
699853d7c0 Relance automatique des clients inactifs (formule Pro)
- Réglages par magasin : activation, délai (30/45/60/90 j), message avec {prenom} et {solde}
- Passage horaire entre 10 h et 19 h (Paris), une relance par période d'inactivité
- Apple : rubrique « Actualité » personnalisée ; Google : message sur la carte du client
- Admin : carte Relance dans l'onglet Campagnes et relances ; app Pro : écran gérant
- Statistiques : à relancer, relances sur 30 j, clients revenus
- Migration manuelle 2026-10-07-relance-inactifs.sql

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 10:26:51 +02:00
27 changed files with 1104 additions and 42 deletions

View file

@ -0,0 +1,106 @@
import { useCallback, useEffect, useState } from 'react';
import { api } from '../api';
interface Birthday {
allowed: boolean;
settings: { enabled: boolean; points: number; message: string | null };
defaultMessage: string;
maxPoints: number;
stats: { cards: number; known: number; giftedThisYear: number };
}
/** Offre d'anniversaire (formule Pro). */
export function BirthdayCard({ storeId }: { storeId: string }) {
const [data, setData] = useState<Birthday | null>(null);
const [enabled, setEnabled] = useState(false);
const [points, setPoints] = useState(0);
const [message, setMessage] = useState('');
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const apply = (d: Birthday) => {
setData(d);
setEnabled(d.settings.enabled);
setPoints(d.settings.points);
setMessage(d.settings.message ?? '');
};
const load = useCallback(() => {
api.get<Birthday>(`/api/admin/stores/${storeId}/birthday`).then(apply).catch((e) => setError(e.message));
}, [storeId]);
useEffect(load, [load]);
if (!data) return error ? <div className="alert error">{error}</div> : null;
async function save() {
setBusy(true);
setError(null);
setNotice(null);
try {
apply(await api.put<Birthday>(`/api/admin/stores/${storeId}/birthday`, { enabled, points, message: message.trim() || null }));
setNotice("Offre d'anniversaire enregistrée.");
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(false);
}
}
const s = data.stats;
return (
<section className="card" style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
<div>
<h2>Offre d'anniversaire</h2>
<p className="muted" style={{ margin: 0 }}>
Les clients peuvent indiquer leur anniversaire (jour et mois) à l'inscription ou sur la page de leur carte.
Le jour J, ils reçoivent une notification et, si vous le souhaitez, des points ou tampons offerts. Un cadeau par an.
</p>
</div>
{error && <div className="alert error" role="alert">{error}</div>}
{notice && <div className="alert ok" role="status">{notice}</div>}
{!data.allowed && <div className="alert warn">L'offre d'anniversaire est réservée aux formules Pro et Réseau (abonnement actif).</div>}
<label style={{ display: 'flex', alignItems: 'center', gap: 10, fontWeight: 600 }}>
<input type="checkbox" checked={enabled} disabled={!data.allowed && !enabled} onChange={(e) => setEnabled(e.target.checked)} />
Offre d'anniversaire activée
</label>
<div style={{ maxWidth: 260 }}>
<label htmlFor="birthday-points" style={{ fontWeight: 600 }}>Points ou tampons offerts</label>
<input
id="birthday-points"
className="input"
type="number"
min={0}
max={data.maxPoints}
value={points}
onChange={(e) => setPoints(Math.max(0, Math.min(data.maxPoints, Math.floor(Number(e.target.value) || 0))))}
/>
<span className="muted" style={{ fontSize: 14 }}>0 = message seulement.</span>
</div>
<div>
<label htmlFor="birthday-msg" style={{ fontWeight: 600 }}>Message</label>
<textarea
id="birthday-msg"
className="input"
rows={2}
maxLength={160}
placeholder={data.defaultMessage}
value={message}
onChange={(e) => setMessage(e.target.value)}
/>
<span className="muted" style={{ fontSize: 14 }}>
Laissez vide pour le texte par défaut. <code>{'{prenom}'}</code> = prénom du client, <code>{'{cadeau}'}</code> = « 3 tampons offerts sur votre carte. »
</span>
</div>
<div className="row between">
<span className="muted" style={{ fontSize: 14 }}>
{s.known} / {s.cards} client(s) ont indiqué leur anniversaire · {s.giftedThisYear} cadeau(x) sur 12 mois
</span>
<button className="btn" disabled={busy} onClick={save}>{busy ? 'Enregistrement…' : 'Enregistrer'}</button>
</div>
</section>
);
}

View file

@ -1,5 +1,7 @@
import { useCallback, useEffect, useState } from 'react'; import { useCallback, useEffect, useState } from 'react';
import { api } from '../api'; import { api } from '../api';
import { RemindersCard } from './RemindersCard';
import { BirthdayCard } from './BirthdayCard';
interface Campaign { interface Campaign {
id: string; id: string;
@ -88,6 +90,9 @@ export function CampaignsTab({ storeId, storeName }: { storeId: string; storeNam
{data.nextAllowedAt && <div className="alert warn">Prochain envoi possible le {when(data.nextAllowedAt)}.</div>} {data.nextAllowedAt && <div className="alert warn">Prochain envoi possible le {when(data.nextAllowedAt)}.</div>}
</section> </section>
<RemindersCard storeId={storeId} />
<BirthdayCard storeId={storeId} />
<section className="card"> <section className="card">
<h2>Historique</h2> <h2>Historique</h2>
{data.items.length === 0 ? ( {data.items.length === 0 ? (

View file

@ -0,0 +1,101 @@
import { useCallback, useEffect, useState } from 'react';
import { api } from '../api';
interface Reminders {
allowed: boolean;
settings: { enabled: boolean; days: number; message: string | null };
defaultMessage: string;
dayChoices: number[];
stats: { pending: number; sentLast30Days: number; cameBack: number; totalReminded: number };
}
/** Relance automatique des clients inactifs (formule Pro). */
export function RemindersCard({ storeId }: { storeId: string }) {
const [data, setData] = useState<Reminders | null>(null);
const [enabled, setEnabled] = useState(false);
const [days, setDays] = useState(45);
const [message, setMessage] = useState('');
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const apply = (d: Reminders) => {
setData(d);
setEnabled(d.settings.enabled);
setDays(d.settings.days);
setMessage(d.settings.message ?? '');
};
const load = useCallback(() => {
api.get<Reminders>(`/api/admin/stores/${storeId}/reminders`).then(apply).catch((e) => setError(e.message));
}, [storeId]);
useEffect(load, [load]);
if (!data) return error ? <div className="alert error">{error}</div> : null;
async function save() {
setBusy(true);
setError(null);
setNotice(null);
try {
apply(await api.put<Reminders>(`/api/admin/stores/${storeId}/reminders`, { enabled, days, message: message.trim() || null }));
setNotice('Réglages de relance enregistrés.');
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(false);
}
}
const s = data.stats;
return (
<section className="card" style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
<div>
<h2>Relance des clients inactifs</h2>
<p className="muted" style={{ margin: 0 }}>
Un client qui n'est pas revenu depuis le délai choisi reçoit automatiquement une notification sur sa carte (entre 10 h et 19 h).
Une seule relance par absence : il doit revenir pour pouvoir être relancé à nouveau.
</p>
</div>
{error && <div className="alert error" role="alert">{error}</div>}
{notice && <div className="alert ok" role="status">{notice}</div>}
{!data.allowed && <div className="alert warn">La relance automatique est réservée aux formules Pro et Réseau (abonnement actif).</div>}
<label style={{ display: 'flex', alignItems: 'center', gap: 10, fontWeight: 600 }}>
<input type="checkbox" checked={enabled} disabled={!data.allowed && !enabled} onChange={(e) => setEnabled(e.target.checked)} />
Relance automatique activée
</label>
<div role="group" aria-label="Délai d'inactivité" className="row" style={{ gap: 8, alignItems: 'center' }}>
<span>Relancer après</span>
{data.dayChoices.map((d) => (
<button key={d} type="button" className="chip" aria-pressed={days === d} onClick={() => setDays(d)}>
{d} jours
</button>
))}
</div>
<div>
<label htmlFor="reminder-msg" style={{ fontWeight: 600 }}>Message</label>
<textarea
id="reminder-msg"
className="input"
rows={2}
maxLength={160}
placeholder={data.defaultMessage}
value={message}
onChange={(e) => setMessage(e.target.value)}
/>
<span className="muted" style={{ fontSize: 14 }}>
Laissez vide pour le texte par défaut. <code>{'{prenom}'}</code> et <code>{'{solde}'}</code> sont remplacés par le prénom et le solde du client.
</span>
</div>
<div className="row between">
<span className="muted" style={{ fontSize: 14 }}>
{s.pending} client(s) inactif(s) à relancer · {s.sentLast30Days} relance(s) sur 30 jours · {s.cameBack} / {s.totalReminded} client(s) relancé(s) revenu(s)
</span>
<button className="btn" disabled={busy} onClick={save}>{busy ? 'Enregistrement…' : 'Enregistrer'}</button>
</div>
</section>
);
}

View file

@ -12,7 +12,7 @@ const TABS = [
['infos', 'Infos'], ['infos', 'Infos'],
['carte', 'Carte de fidélité'], ['carte', 'Carte de fidélité'],
['employes', 'Employés'], ['employes', 'Employés'],
['campagnes', 'Campagnes'], ['campagnes', 'Fidélisation'],
['facturation', 'Facturation'], ['facturation', 'Facturation'],
] as const; ] as const;

View file

@ -0,0 +1,9 @@
-- Offre d'anniversaire (formule Pro).
ALTER TABLE `Customer`
ADD COLUMN `birthMonth` TINYINT NULL,
ADD COLUMN `birthDay` TINYINT NULL;
ALTER TABLE `Store`
ADD COLUMN `birthdayEnabled` BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN `birthdayPoints` INTEGER NOT NULL DEFAULT 0,
ADD COLUMN `birthdayMessage` VARCHAR(160) NULL;
ALTER TABLE `LoyaltyCard` ADD COLUMN `birthdayGiftAt` DATETIME(3) NULL;

View file

@ -0,0 +1,6 @@
-- Relance automatique des clients inactifs (formule Pro).
ALTER TABLE `Store`
ADD COLUMN `reminderEnabled` BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN `reminderDays` INTEGER NOT NULL DEFAULT 45,
ADD COLUMN `reminderMessage` VARCHAR(160) NULL;
ALTER TABLE `LoyaltyCard` ADD COLUMN `reminderSentAt` DATETIME(3) NULL;

View file

@ -48,6 +48,19 @@ model Store {
maxAmountCents Int @default(50000) /// plafond d'un montant saisi maxAmountCents Int @default(50000) /// plafond d'un montant saisi
minScanIntervalSec Int @default(300) /// délai minimum entre deux crédits d'un même client minScanIntervalSec Int @default(300) /// délai minimum entre deux crédits d'un même client
// Relance automatique des clients inactifs (formule Pro)
reminderEnabled Boolean @default(false)
reminderDays Int @default(45)
/// Texte de la relance ; {prenom} et {solde} sont remplacés. Vide = texte par défaut.
reminderMessage String? @db.VarChar(160)
// Offre d'anniversaire (formule Pro)
birthdayEnabled Boolean @default(false)
/// Points ou tampons offerts le jour de l'anniversaire (0 = message seulement).
birthdayPoints Int @default(0)
/// Texte du message ; {prenom} et {cadeau} sont remplacés. Vide = texte par défaut.
birthdayMessage String? @db.VarChar(160)
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
@ -114,34 +127,41 @@ model StaffUser {
// ── Clients finaux ──────────────────────────────────────────── // ── Clients finaux ────────────────────────────────────────────
model Customer { model Customer {
id String @id @default(cuid()) id String @id @default(cuid())
firstName String firstName String
email String email String
consentAt DateTime /// consentement RGPD horodaté consentAt DateTime /// consentement RGPD horodaté
createdAt DateTime @default(now()) /// Anniversaire facultatif (jour et mois seulement : l'année n'est pas demandée).
cards LoyaltyCard[] birthMonth Int? @db.TinyInt
birthDay Int? @db.TinyInt
createdAt DateTime @default(now())
cards LoyaltyCard[]
} }
model LoyaltyCard { model LoyaltyCard {
id String @id @default(cuid()) id String @id @default(cuid())
storeId String storeId String
store Store @relation(fields: [storeId], references: [id], onDelete: Cascade) store Store @relation(fields: [storeId], references: [id], onDelete: Cascade)
customerId String customerId String
customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade) customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade)
/// Numéro de série du pass Wallet ; contenu du QR (non devinable). /// Numéro de série du pass Wallet ; contenu du QR (non devinable).
serial String @unique serial String @unique
/// Jeton d'authentification du service web Apple Wallet. /// Jeton d'authentification du service web Apple Wallet.
authToken String authToken String
/// Clé secrète des liens client (page de la carte, téléchargement du pass). /// Clé secrète des liens client (page de la carte, téléchargement du pass).
accessKey String @unique accessKey String @unique
balance Int @default(0) balance Int @default(0)
/// Dernière modification visible dans le Wallet (solde, design du magasin) : sert aux mises à jour Apple. /// Dernière modification visible dans le Wallet (solde, design du magasin) : sert aux mises à jour Apple.
passUpdatedAt DateTime @default(now()) passUpdatedAt DateTime @default(now())
lastCreditAt DateTime? lastCreditAt DateTime?
createdAt DateTime @default(now()) /// Dernière relance « client inactif » envoyée (une seule par période d'inactivité).
updatedAt DateTime @updatedAt reminderSentAt DateTime?
transactions Transaction[] /// Dernier cadeau d'anniversaire (un par an).
devices AppleRegistration[] birthdayGiftAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
transactions Transaction[]
devices AppleRegistration[]
@@unique([storeId, customerId]) @@unique([storeId, customerId])
} }

View file

@ -14,6 +14,8 @@ import { BillingModule } from './billing/billing.controller';
import { EntitlementsModule } from './billing/entitlements.service'; import { EntitlementsModule } from './billing/entitlements.service';
import { WalletModule } from './wallet/wallet.module'; import { WalletModule } from './wallet/wallet.module';
import { CampaignsModule } from './campaigns/campaigns.controller'; import { CampaignsModule } from './campaigns/campaigns.controller';
import { RemindersModule } from './reminders/reminders.controller';
import { BirthdaysModule } from './birthdays/birthdays.controller';
import { HealthController } from './health.controller'; import { HealthController } from './health.controller';
@Module({ @Module({
@ -31,6 +33,8 @@ import { HealthController } from './health.controller';
BillingModule, BillingModule,
EntitlementsModule, EntitlementsModule,
CampaignsModule, CampaignsModule,
RemindersModule,
BirthdaysModule,
], ],
controllers: [HealthController], controllers: [HealthController],
providers: [{ provide: APP_GUARD, useClass: ThrottlerGuard }], providers: [{ provide: APP_GUARD, useClass: ThrottlerGuard }],

View file

@ -0,0 +1,87 @@
import { Body, Controller, Get, HttpCode, Module, NotFoundException, Param, Post, Put, Query, UseGuards } from '@nestjs/common';
import { Throttle } from '@nestjs/throttler';
import { IsBoolean, IsInt, IsOptional, IsString, Max, MaxLength, Min } from 'class-validator';
import { JwtPayload } from '../common/auth.types';
import { AdminGuard, CurrentUser, JwtAuthGuard, StaffGuard, StaffRoles } from '../common/guards';
import { EnrollmentModule } from '../enrollment/enrollment.module';
import { EnrollmentService } from '../enrollment/enrollment.service';
import { BirthdaysService, MAX_BIRTHDAY_POINTS } from './birthdays.service';
class BirthdaySettingsDto {
@IsBoolean()
enabled!: boolean;
@IsInt() @Min(0) @Max(MAX_BIRTHDAY_POINTS)
points!: number;
@IsOptional() @IsString() @MaxLength(160)
message?: string | null;
}
class CustomerBirthdayDto {
@IsInt() @Min(1) @Max(12)
month!: number;
@IsInt() @Min(1) @Max(31)
day!: number;
}
@Controller('admin/stores/:id/birthday')
@UseGuards(JwtAuthGuard, AdminGuard)
export class AdminBirthdaysController {
constructor(private birthdays: BirthdaysService) {}
@Get()
get(@Param('id') id: string) {
return this.birthdays.overview(id);
}
@Put()
update(@Param('id') id: string, @Body() dto: BirthdaySettingsDto) {
return this.birthdays.update(id, { enabled: dto.enabled, points: dto.points, message: dto.message ?? null });
}
}
/** App Pro : réservé aux gérants. */
@Controller('staff/birthday')
@UseGuards(JwtAuthGuard, StaffGuard)
@StaffRoles('MANAGER')
export class StaffBirthdaysController {
constructor(private birthdays: BirthdaysService) {}
@Get()
get(@CurrentUser() user: JwtPayload) {
if (user.kind !== 'staff') throw new Error('StaffGuard manquant');
return this.birthdays.overview(user.storeId);
}
@Put()
update(@CurrentUser() user: JwtPayload, @Body() dto: BirthdaySettingsDto) {
if (user.kind !== 'staff') throw new Error('StaffGuard manquant');
return this.birthdays.update(user.storeId, { enabled: dto.enabled, points: dto.points, message: dto.message ?? null });
}
}
/** Le client renseigne son anniversaire depuis la page de sa carte (lien secret). */
@Controller('public/cards/:serial/birthday')
export class PublicBirthdayController {
constructor(private birthdays: BirthdaysService, private enrollment: EnrollmentService) {}
@Post()
@HttpCode(200)
@Throttle({ default: { limit: 5, ttl: 60_000 } })
async set(@Param('serial') serial: string, @Query('k') key: string | undefined, @Body() dto: CustomerBirthdayDto) {
const card = await this.enrollment.findCard(serial, key);
if (!card) throw new NotFoundException();
await this.birthdays.setCustomerBirthday(card.customerId, dto.month, dto.day);
return { ok: true };
}
}
@Module({
imports: [EnrollmentModule],
controllers: [AdminBirthdaysController, StaffBirthdaysController, PublicBirthdayController],
providers: [BirthdaysService],
exports: [BirthdaysService],
})
export class BirthdaysModule {}

View file

@ -0,0 +1,153 @@
import { BadRequestException, Injectable, Logger, NotFoundException, OnApplicationBootstrap, OnApplicationShutdown } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { EntitlementsService } from '../billing/entitlements.service';
import { CardUpdatesService } from '../wallet/card-updates.service';
import { birthdayText, CARD_WITH_CONTEXT, DEFAULT_BIRTHDAY } from '../wallet/wallet.types';
/** Envois seulement entre 9 h et 19 h (heure de Paris). */
const SEND_HOURS = { from: 9, to: 19 };
/** Un cadeau par an : un cadeau de moins de 300 jours bloque le suivant. */
const MIN_GAP_MS = 300 * 24 * 3600_000;
export const MAX_BIRTHDAY_POINTS = 100;
export interface BirthdaySettings {
enabled: boolean;
points: number;
message: string | null;
}
/** Jour et mois à Paris. */
export function parisDate(now: Date) {
const parts = new Intl.DateTimeFormat('fr-FR', { timeZone: 'Europe/Paris', year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', hour12: false }).formatToParts(now);
const get = (t: string) => Number(parts.find((p) => p.type === t)!.value);
return { year: get('year'), month: get('month'), day: get('day'), hour: get('hour') };
}
/** Anniversaires fêtés aujourd'hui ; le 29 février est fêté le 28 les années non bissextiles. */
export function birthdaysOn(year: number, month: number, day: number) {
const leap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
const days = [{ birthMonth: month, birthDay: day }];
if (!leap && month === 2 && day === 28) days.push({ birthMonth: 2, birthDay: 29 });
return days;
}
export function isValidBirthday(month: number, day: number) {
if (!Number.isInteger(month) || !Number.isInteger(day) || month < 1 || month > 12 || day < 1) return false;
return day <= [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1];
}
/**
* Offre d'anniversaire : le jour J, le client reçoit une notification sur sa carte
* et, si le magasin le souhaite, des points ou tampons offerts.
*/
@Injectable()
export class BirthdaysService implements OnApplicationBootstrap, OnApplicationShutdown {
private readonly logger = new Logger(BirthdaysService.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(), 90_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 yearAgo = new Date(Date.now() - 365 * 24 * 3600_000);
const [allowed, cards, known, giftedThisYear] = await Promise.all([
this.entitlements.can(storeId, 'birthday'),
this.prisma.loyaltyCard.count({ where: { storeId } }),
this.prisma.loyaltyCard.count({ where: { storeId, customer: { birthMonth: { not: null } } } }),
this.prisma.loyaltyCard.count({ where: { storeId, birthdayGiftAt: { gte: yearAgo } } }),
]);
return {
allowed,
settings: { enabled: store.birthdayEnabled, points: store.birthdayPoints, message: store.birthdayMessage } as BirthdaySettings,
defaultMessage: DEFAULT_BIRTHDAY,
maxPoints: MAX_BIRTHDAY_POINTS,
stats: { cards, known, giftedThisYear },
};
}
async update(storeId: string, settings: BirthdaySettings) {
if (settings.enabled) await this.entitlements.require(storeId, 'birthday');
await this.prisma.store.update({
where: { id: storeId },
data: {
birthdayEnabled: settings.enabled,
birthdayPoints: settings.points,
birthdayMessage: settings.message?.replace(/\s+/g, ' ').trim() || null,
},
});
return this.overview(storeId);
}
/** Le client renseigne son anniversaire (inscription ou page de sa carte). */
async setCustomerBirthday(customerId: string, month: number, day: number) {
if (!isValidBirthday(month, day)) throw new BadRequestException('Date invalide');
await this.prisma.customer.update({ where: { id: customerId }, data: { birthMonth: month, birthDay: day } });
}
/** Passage horaire. */
async tick(now = new Date()) {
if (this.running) return;
const today = parisDate(now);
if (today.hour < SEND_HOURS.from || today.hour >= SEND_HOURS.to) return;
this.running = true;
try {
const stores = await this.prisma.store.findMany({
where: { birthdayEnabled: true, status: 'ACTIVE', billingSuspended: false },
select: { id: true, name: true, birthdayPoints: true },
});
for (const store of stores) {
if (!(await this.entitlements.can(store.id, 'birthday'))) continue;
const sent = await this.runStore(store, today, now);
if (sent) this.logger.log(`Anniversaire : ${sent} client(s) de ${store.name}`);
}
} catch (e) {
this.logger.error(`Offre d'anniversaire : ${(e as Error).message}`);
} finally {
this.running = false;
}
}
private async runStore(store: { id: string; name: string; birthdayPoints: number }, today: ReturnType<typeof parisDate>, now: Date) {
const notBefore = new Date(now.getTime() - MIN_GAP_MS);
const cards = await this.prisma.loyaltyCard.findMany({
where: {
storeId: store.id,
customer: { OR: birthdaysOn(today.year, today.month, today.day) },
OR: [{ birthdayGiftAt: null }, { birthdayGiftAt: { lt: notBefore } }],
},
select: { id: true },
});
let sent = 0;
for (const { id } of cards) {
// Mise à jour conditionnelle : jamais deux cadeaux, même si deux passages se chevauchent.
const { count } = await this.prisma.loyaltyCard.updateMany({
where: { id, OR: [{ birthdayGiftAt: null }, { birthdayGiftAt: { lt: notBefore } }] },
data: { birthdayGiftAt: now, passUpdatedAt: now, ...(store.birthdayPoints > 0 && { balance: { increment: store.birthdayPoints } }) },
});
if (!count) continue;
const card = await this.prisma.loyaltyCard.findUniqueOrThrow({ where: { id }, include: CARD_WITH_CONTEXT });
try {
await this.cardUpdates.remind(card.id, birthdayText(card), store.name);
sent++;
} catch (e) {
this.logger.warn(`Anniversaire carte ${card.serial} : ${(e as Error).message}`);
}
}
return sent;
}
}

View file

@ -15,7 +15,7 @@ import { Throttle } from '@nestjs/throttler';
import { Response } from 'express'; import { Response } from 'express';
import QRCode from 'qrcode'; import QRCode from 'qrcode';
import { Transform } from 'class-transformer'; import { Transform } from 'class-transformer';
import { Equals, IsEmail, IsString, Length } from 'class-validator'; import { Equals, IsEmail, IsInt, IsOptional, IsString, Length, Max, Min } from 'class-validator';
import { EnrollmentService } from './enrollment.service'; import { EnrollmentService } from './enrollment.service';
import { ApplePassService } from '../wallet/apple-pass.service'; import { ApplePassService } from '../wallet/apple-pass.service';
import { GoogleWalletService } from '../wallet/google-wallet.service'; import { GoogleWalletService } from '../wallet/google-wallet.service';
@ -33,6 +33,13 @@ class EnrollDto {
/** Le consentement RGPD est obligatoire ; sa date est enregistrée. */ /** Le consentement RGPD est obligatoire ; sa date est enregistrée. */
@Equals(true) @Equals(true)
consent!: boolean; consent!: boolean;
/** Anniversaire facultatif (offre d'anniversaire du magasin). */
@IsOptional() @IsInt() @Min(1) @Max(12)
birthMonth?: number;
@IsOptional() @IsInt() @Min(1) @Max(31)
birthDay?: number;
} }
class ResendDto { class ResendDto {
@ -107,7 +114,7 @@ export class EnrollmentApiController {
@HttpCode(200) @HttpCode(200)
@Throttle({ default: { limit: 10, ttl: 60_000 } }) @Throttle({ default: { limit: 10, ttl: 60_000 } })
enroll(@Param('slug') slug: string, @Body() dto: EnrollDto) { enroll(@Param('slug') slug: string, @Body() dto: EnrollDto) {
return this.enrollment.enroll(slug, dto.firstName, dto.email); return this.enrollment.enroll(slug, dto.firstName, dto.email, dto.birthMonth && dto.birthDay ? { month: dto.birthMonth, day: dto.birthDay } : null);
} }
@Post('stores/:slug/resend') @Post('stores/:slug/resend')

View file

@ -6,5 +6,6 @@ import { EnrollmentService } from './enrollment.service';
@Module({ @Module({
controllers: [EnrollmentPagesController, EnrollmentApiController], controllers: [EnrollmentPagesController, EnrollmentApiController],
providers: [EnrollmentService], providers: [EnrollmentService],
exports: [EnrollmentService],
}) })
export class EnrollmentModule {} export class EnrollmentModule {}

View file

@ -5,6 +5,8 @@ import { PrismaService } from '../prisma/prisma.service';
import { MailService } from '../mail/mail.service'; import { MailService } from '../mail/mail.service';
import { CARD_WITH_CONTEXT, CardWithContext } from '../wallet/wallet.types'; import { CARD_WITH_CONTEXT, CardWithContext } from '../wallet/wallet.types';
import { emailLayout, esc } from '../mail/email-layout'; import { emailLayout, esc } from '../mail/email-layout';
import { isValidBirthday } from '../birthdays/birthdays.service';
import { birthdayOffered } from './pages';
/** Alphabet sans caractères ambigus : le numéro peut être lu à voix haute au comptoir. */ /** Alphabet sans caractères ambigus : le numéro peut être lu à voix haute au comptoir. */
const SERIAL_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; const SERIAL_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
@ -52,7 +54,7 @@ export class EnrollmentService {
return store; return store;
} }
async enroll(slug: string, firstName: string, rawEmail: string): Promise<EnrollResult> { async enroll(slug: string, firstName: string, rawEmail: string, birthday: { month: number; day: number } | null = null): Promise<EnrollResult> {
const store = await this.openStore(slug); const store = await this.openStore(slug);
const email = rawEmail.toLowerCase(); const email = rawEmail.toLowerCase();
const existing = await this.findCardByEmail(store.id, email); const existing = await this.findCardByEmail(store.id, email);
@ -64,7 +66,15 @@ export class EnrollmentService {
authToken: token(), authToken: token(),
accessKey: token(), accessKey: token(),
store: { connect: { id: store.id } }, store: { connect: { id: store.id } },
customer: { create: { firstName, email, consentAt: new Date() } }, customer: {
create: {
firstName,
email,
consentAt: new Date(),
// Gardé seulement si le magasin propose l'offre et que la date existe.
...(birthday && birthdayOffered(store) && isValidBirthday(birthday.month, birthday.day) && { birthMonth: birthday.month, birthDay: birthday.day }),
},
},
}, },
include: CARD_WITH_CONTEXT, include: CARD_WITH_CONTEXT,
}); });

View file

@ -13,6 +13,30 @@ export type StoreWithDesign = Store & {
const whiteLabel = (s: StoreWithDesign) => s.subscription?.status === 'ACTIVE' && hasFeature(s.subscription.plan, 'whiteLabel'); const whiteLabel = (s: StoreWithDesign) => s.subscription?.status === 'ACTIVE' && hasFeature(s.subscription.plan, 'whiteLabel');
export type Platform = 'apple' | 'google' | 'other'; export type Platform = 'apple' | 'google' | 'other';
/** Offre d'anniversaire active (formule Pro) : on propose alors au client d'indiquer son anniversaire. */
export const birthdayOffered = (s: StoreWithDesign) =>
s.birthdayEnabled && s.subscription?.status === 'ACTIVE' && hasFeature(s.subscription.plan, 'birthday');
const MONTHS = ['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'];
function birthdaySelects() {
const days = Array.from({ length: 31 }, (_, i) => `<option value="${i + 1}">${i + 1}</option>`).join('');
const months = MONTHS.map((m, i) => `<option value="${i + 1}">${m}</option>`).join('');
return `<div style="display:flex;gap:10px">
<select id="bday" aria-label="Jour" style="width:96px;flex:none"><option value="">Jour</option>${days}</select>
<select id="bmonth" aria-label="Mois" style="flex:1;min-width:0"><option value="">Mois</option>${months}</select>
</div>`;
}
/** Lecture des listes jour / mois côté navigateur : null si vide, false si incomplet ou impossible. */
const BIRTHDAY_JS = `function readBirthday(){var d=+document.getElementById('bday').value,m=+document.getElementById('bmonth').value;if(!d&&!m)return null;if(!d||!m||d>[31,29,31,30,31,30,31,31,30,31,30,31][m-1])return false;return {day:d,month:m}}`;
function birthdayGiftLine(store: StoreWithDesign) {
const n = store.birthdayPoints;
const unit = store.cardDesign?.pointsMode === 'STAMP' ? 'tampon' : 'point';
return n > 0 ? `${n} ${unit}${n > 1 ? 's' : ''} offert${n > 1 ? 's' : ''} le jour de votre anniversaire.` : 'Une surprise le jour de votre anniversaire.';
}
export function escapeHtml(value: unknown) { export function escapeHtml(value: unknown) {
return String(value ?? '') return String(value ?? '')
.replace(/&/g, '&amp;') .replace(/&/g, '&amp;')
@ -87,7 +111,7 @@ form{display:flex;flex-direction:column;gap:16px}
label{font-weight:600} label{font-weight:600}
.hint{font-size:14px;color:var(--muted)} .hint{font-size:14px;color:var(--muted)}
.error{font-size:14px;color:var(--err);font-weight:500} .error{font-size:14px;color:var(--err);font-weight:500}
input[type=text],input[type=email]{height:52px;padding:0 14px;border:1px solid #8A897F;border-radius:12px;background:var(--surface);color:var(--text);font:400 17px 'Figtree',sans-serif;width:100%} input[type=text],input[type=email],select{height:52px;padding:0 14px;border:1px solid #8A897F;border-radius:12px;background:var(--surface);color:var(--text);font:400 17px 'Figtree',sans-serif;width:100%}
input:focus{outline:2px solid var(--brand);outline-offset:1px} input:focus{outline:2px solid var(--brand);outline-offset:1px}
.consent{display:flex;gap:12px;align-items:flex-start;font-weight:400;font-size:15px} .consent{display:flex;gap:12px;align-items:flex-start;font-weight:400;font-size:15px}
.consent input{width:22px;height:22px;margin-top:2px;flex:none;accent-color:var(--brand)} .consent input{width:22px;height:22px;margin-top:2px;flex:none;accent-color:var(--brand)}
@ -182,10 +206,19 @@ export function enrollPage(store: StoreWithDesign) {
<input id="email" name="email" type="email" inputmode="email" autocomplete="email" placeholder="vous@exemple.fr" required> <input id="email" name="email" type="email" inputmode="email" autocomplete="email" placeholder="vous@exemple.fr" required>
<span class="hint" id="h-email">Pour retrouver votre carte si vous changez de téléphone.</span> <span class="hint" id="h-email">Pour retrouver votre carte si vous changez de téléphone.</span>
<span class="error" id="e-email" hidden>Vérifiez votre adresse e-mail.</span> <span class="error" id="e-email" hidden>Vérifiez votre adresse e-mail.</span>
</div> </div>${
birthdayOffered(store)
? `<div class="field">
<label for="bday">Anniversaire <span class="hint">(facultatif)</span></label>
${birthdaySelects()}
<span class="hint">${e(birthdayGiftLine(store))}</span>
<span class="error" id="e-birthday" hidden>Choisissez le jour et le mois, ou laissez les deux vides.</span>
</div>`
: ''
}
<div class="field"> <div class="field">
<label class="consent"><input id="consent" type="checkbox" required> <label class="consent"><input id="consent" type="checkbox" required>
<span>J'accepte que ${e(store.name)} utilise mon prénom et mon e-mail pour gérer ma carte de fidélité. <a href="/c/${e(store.slug)}/confidentialite">Politique de confidentialité</a></span> <span>J'accepte que ${e(store.name)} utilise mon prénom${birthdayOffered(store) ? ', mon e-mail et mon anniversaire (si je l’indique)' : ' et mon e-mail'} pour gérer ma carte de fidélité. <a href="/c/${e(store.slug)}/confidentialite">Politique de confidentialité</a></span>
</label> </label>
<span class="error" id="e-consent" hidden>Cochez la case pour créer votre carte.</span> <span class="error" id="e-consent" hidden>Cochez la case pour créer votre carte.</span>
</div> </div>
@ -207,16 +240,20 @@ export function enrollPage(store: StoreWithDesign) {
var slug=${JSON.stringify(store.slug)}; var slug=${JSON.stringify(store.slug)};
var $=function(id){return document.getElementById(id)}; var $=function(id){return document.getElementById(id)};
var lastEmail=''; var lastEmail='';
var hasBirthday=${birthdayOffered(store) ? 'true' : 'false'};
${BIRTHDAY_JS}
function show(id,on){$(id).hidden=!on} function show(id,on){$(id).hidden=!on}
$('f').addEventListener('submit',async function(ev){ $('f').addEventListener('submit',async function(ev){
ev.preventDefault(); ev.preventDefault();
var firstName=$('firstName').value.trim(),email=$('email').value.trim(),consent=$('consent').checked; var firstName=$('firstName').value.trim(),email=$('email').value.trim(),consent=$('consent').checked;
var okName=firstName.length>0,okMail=/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email); var okName=firstName.length>0,okMail=/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email);
show('e-firstName',!okName);show('e-email',!okMail);show('h-email',okMail);show('e-consent',!consent);show('e-global',false); show('e-firstName',!okName);show('e-email',!okMail);show('h-email',okMail);show('e-consent',!consent);show('e-global',false);
if(!okName||!okMail||!consent)return; var bd=hasBirthday?readBirthday():null;
if(hasBirthday)show('e-birthday',bd===false);
if(!okName||!okMail||!consent||bd===false)return;
$('submit').disabled=true; $('submit').disabled=true;
try{ try{
var r=await fetch('/api/public/stores/'+slug+'/enroll',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({firstName:firstName,email:email,consent:true})}); var r=await fetch('/api/public/stores/'+slug+'/enroll',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(Object.assign({firstName:firstName,email:email,consent:true},bd?{birthMonth:bd.month,birthDay:bd.day}:{}))});
var data=await r.json().catch(function(){return {}}); var data=await r.json().catch(function(){return {}});
if(!r.ok){throw new Error(r.status===409?'Le programme est momentanément indisponible.':r.status===429?'Trop de tentatives, réessayez dans une minute.':'Une erreur est survenue, réessayez.')} if(!r.ok){throw new Error(r.status===409?'Le programme est momentanément indisponible.':r.status===429?'Trop de tentatives, réessayez dans une minute.':'Une erreur est survenue, réessayez.')}
if(data.status==='created'){location.href=data.cardUrl+'&nouveau=1';return} if(data.status==='created'){location.href=data.cardUrl+'&nouveau=1';return}
@ -290,6 +327,7 @@ export function cardPage(
? appleBtn + (googleBtn && `<a class="small" href="/api/public/cards/${e(card.serial)}/google${e(q)}">Vous avez un Android ? Google Wallet</a>`) ? appleBtn + (googleBtn && `<a class="small" href="/api/public/cards/${e(card.serial)}/google${e(q)}">Vous avez un Android ? Google Wallet</a>`)
: appleBtn + googleBtn; : appleBtn + googleBtn;
const none = !opts.apple && !opts.google; const none = !opts.apple && !opts.google;
const askBirthday = birthdayOffered(store) && card.customer.birthMonth === null;
const body = ` const body = `
<div style="display:flex;flex-direction:column;gap:8px"> <div style="display:flex;flex-direction:column;gap:8px">
@ -305,6 +343,13 @@ export function cardPage(
</div> </div>
<p class="hint" style="text-align:center">Présentez ce QR code au comptoir à chaque passage.</p> <p class="hint" style="text-align:center">Présentez ce QR code au comptoir à chaque passage.</p>
${rewardsList(d.rewards, card.balance, d.pointsMode === 'STAMP')} ${rewardsList(d.rewards, card.balance, d.pointsMode === 'STAMP')}
${askBirthday ? `<form id="bform" class="notice" style="display:flex;flex-direction:column;gap:10px" novalidate>
<strong>Un cadeau pour votre anniversaire ?</strong>
<span>${e(birthdayGiftLine(store))} Indiquez le jour et le mois (l’année n’est pas demandée).</span>
${birthdaySelects()}
<span class="error" id="e-birthday" hidden>Choisissez un jour et un mois valides.</span>
<button class="btn" id="bsave">Enregistrer</button>
</form>` : ''}
<div style="display:flex;flex-direction:column;gap:12px;align-items:stretch"> <div style="display:flex;flex-direction:column;gap:12px;align-items:stretch">
${buttons} ${buttons}
${ ${
@ -329,6 +374,13 @@ ${opts.isNew ? '<p class="small">Un e-mail de confirmation vous a été envoyé
</details>`; </details>`;
const script = ` const script = `
${askBirthday ? `${BIRTHDAY_JS}
document.getElementById('bform').addEventListener('submit',async function(ev){
ev.preventDefault();var bd=readBirthday();var err=document.getElementById('e-birthday');err.hidden=!!bd;if(!bd)return;
document.getElementById('bsave').disabled=true;
var r=await fetch('/api/public/cards/${card.serial}/birthday${q}',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(bd)}).catch(function(){return null});
if(r&&r.ok){this.innerHTML='<strong>C’est noté, merci !</strong><span>Rendez-vous le jour de votre anniversaire.</span>'}else{err.textContent='Enregistrement impossible, réessayez.';err.hidden=false;document.getElementById('bsave').disabled=false}
});` : ''}
document.getElementById('delete').addEventListener('click',async function(){ document.getElementById('delete').addEventListener('click',async function(){
if(!confirm('Supprimer définitivement votre carte et votre solde ?'))return; if(!confirm('Supprimer définitivement votre carte et votre solde ?'))return;
this.disabled=true; this.disabled=true;
@ -344,7 +396,7 @@ export function privacyPage(store: StoreWithDesign) {
`Confidentialité — ${store.name}`, `Confidentialité — ${store.name}`,
`<h1>Confidentialité</h1> `<h1>Confidentialité</h1>
<p><strong>Responsable du traitement :</strong> ${e(store.name)}, ${e(store.addressLine)}, ${e(store.postalCode)} ${e(store.city)} (SIRET ${e(store.siret)}). Contact : <a href="mailto:${e(store.contactEmail)}">${e(store.contactEmail)}</a>.</p> <p><strong>Responsable du traitement :</strong> ${e(store.name)}, ${e(store.addressLine)}, ${e(store.postalCode)} ${e(store.city)} (SIRET ${e(store.siret)}). Contact : <a href="mailto:${e(store.contactEmail)}">${e(store.contactEmail)}</a>.</p>
<p><strong>Données collectées :</strong> votre prénom, votre adresse e-mail, votre solde et l'historique de vos passages (date, montant, points).</p> <p><strong>Données collectées :</strong> votre prénom, votre adresse e-mail, votre jour et mois d'anniversaire si vous les indiquez (facultatif), votre solde et l'historique de vos passages (date, montant, points).</p>
<p><strong>Finalité :</strong> gérer votre carte de fidélité. Vos données ne sont ni vendues ni utilisées à des fins publicitaires.</p> <p><strong>Finalité :</strong> gérer votre carte de fidélité. Vos données ne sont ni vendues ni utilisées à des fins publicitaires.</p>
<p><strong>Base légale :</strong> votre consentement, que vous pouvez retirer à tout moment en supprimant votre carte depuis le lien reçu par e-mail.</p> <p><strong>Base légale :</strong> votre consentement, que vous pouvez retirer à tout moment en supprimant votre carte depuis le lien reçu par e-mail.</p>
<p><strong>Sous-traitant :</strong> la plateforme MonEspacePro (EI Tony Averty) héberge les données pour le compte du commerce, en France / Union européenne.</p> <p><strong>Sous-traitant :</strong> la plateforme MonEspacePro (EI Tony Averty) héberge les données pour le compte du commerce, en France / Union européenne.</p>

View file

@ -0,0 +1,58 @@
import { Body, Controller, Get, Module, Param, Put, UseGuards } from '@nestjs/common';
import { IsBoolean, IsIn, IsOptional, IsString, MaxLength } from 'class-validator';
import { JwtPayload } from '../common/auth.types';
import { AdminGuard, CurrentUser, JwtAuthGuard, StaffGuard, StaffRoles } from '../common/guards';
import { REMINDER_DAYS, RemindersService } from './reminders.service';
class ReminderSettingsDto {
@IsBoolean()
enabled!: boolean;
@IsIn(REMINDER_DAYS)
days!: number;
@IsOptional() @IsString() @MaxLength(160)
message?: string | null;
}
@Controller('admin/stores/:id/reminders')
@UseGuards(JwtAuthGuard, AdminGuard)
export class AdminRemindersController {
constructor(private reminders: RemindersService) {}
@Get()
get(@Param('id') id: string) {
return this.reminders.overview(id);
}
@Put()
update(@Param('id') id: string, @Body() dto: ReminderSettingsDto) {
return this.reminders.update(id, { enabled: dto.enabled, days: dto.days, message: dto.message ?? null });
}
}
/** App Pro : réservé aux gérants. */
@Controller('staff/reminders')
@UseGuards(JwtAuthGuard, StaffGuard)
@StaffRoles('MANAGER')
export class StaffRemindersController {
constructor(private reminders: RemindersService) {}
@Get()
get(@CurrentUser() user: JwtPayload) {
if (user.kind !== 'staff') throw new Error('StaffGuard manquant');
return this.reminders.overview(user.storeId);
}
@Put()
update(@CurrentUser() user: JwtPayload, @Body() dto: ReminderSettingsDto) {
if (user.kind !== 'staff') throw new Error('StaffGuard manquant');
return this.reminders.update(user.storeId, { enabled: dto.enabled, days: dto.days, message: dto.message ?? null });
}
}
@Module({
controllers: [AdminRemindersController, StaffRemindersController],
providers: [RemindersService],
})
export class RemindersModule {}

View file

@ -0,0 +1,143 @@
import { Injectable, Logger, NotFoundException, OnApplicationBootstrap, OnApplicationShutdown } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.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 = Number(new Intl.DateTimeFormat('fr-FR', { hour: 'numeric', hour12: false, timeZone: 'Europe/Paris' }).format(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;
}
}

View file

@ -5,7 +5,7 @@ import { join } from 'path';
import { Jimp } from 'jimp'; import { Jimp } from 'jimp';
import { PKPass } from 'passkit-generator'; import { PKPass } from 'passkit-generator';
import { UPLOADS_DIR } from '../card-design/card-design.service'; import { UPLOADS_DIR } from '../card-design/card-design.service';
import { CardWithContext, latestNews, nextRewardText, rewardsText, unitLabel } from './wallet.types'; import { CardWithContext, newsText, nextRewardText, rewardsText, unitLabel } from './wallet.types';
type Certificates = { wwdr: Buffer; signerCert: Buffer; signerKey: Buffer; signerKeyPassphrase?: string }; type Certificates = { wwdr: Buffer; signerCert: Buffer; signerKey: Buffer; signerKeyPassphrase?: string };
@ -69,7 +69,7 @@ export class ApplePassService {
}), }),
backFields: [ backFields: [
// Toujours présent : quand sa valeur change (nouvelle campagne), l'iPhone affiche le message sur l'écran verrouillé. // Toujours présent : quand sa valeur change (nouvelle campagne), l'iPhone affiche le message sur l'écran verrouillé.
{ key: 'news', label: 'Actualité', value: latestNews(card) ?? 'Aucune actualité pour le moment.', changeMessage: '%@' }, { key: 'news', label: 'Actualité', value: newsText(card) ?? 'Aucune actualité pour le moment.', changeMessage: '%@' },
{ key: 'rewards', label: 'Récompenses', value: rewardsText(card) }, { key: 'rewards', label: 'Récompenses', value: rewardsText(card) },
{ {
key: 'store', key: 'store',

View file

@ -69,6 +69,20 @@ export class CardUpdatesService {
}); });
} }
/** Message personnel (relance, anniversaire) : la rubrique « Actualité » Apple change (notification), message Google sur sa carte. */
async remind(cardId: string, text: string, storeName: string) {
const card = await this.prisma.loyaltyCard.findUniqueOrThrow({
where: { id: cardId },
include: { ...CARD_WITH_CONTEXT, devices: { include: { device: true } } },
});
// Solde à jour d'abord (cadeau d'anniversaire), puis le message avec notification.
await this.google.updateObject(card);
await Promise.all([
this.pushApple(card.devices.map((r) => r.device.pushToken)),
this.google.addObjectMessage(card.serial, `reminder_${Date.now()}`, storeName, text),
]);
}
private async pushApple(tokens: string[]) { private async pushApple(tokens: string[]) {
const gone = await this.apns.push([...new Set(tokens)]); const gone = await this.apns.push([...new Set(tokens)]);
if (gone.length) await this.prisma.appleDevice.deleteMany({ where: { pushToken: { in: gone } } }); if (gone.length) await this.prisma.appleDevice.deleteMany({ where: { pushToken: { in: gone } } });

View file

@ -89,6 +89,14 @@ export class GoogleWalletService {
}); });
} }
/** Message avec notification sur la carte d'un seul client (relance). */
async addObjectMessage(serial: string, messageId: string, header: string, body: string) {
if (!this.enabled) return;
await this.call('POST', `/loyaltyObject/${encodeURIComponent(this.objectId(serial))}/addMessage`, {
message: { id: messageId, header, body, messageType: 'TEXT_AND_NOTIFY' },
});
}
private buildClass(store: StoreForClass) { private buildClass(store: StoreForClass) {
const design = store.cardDesign!; const design = store.cardDesign!;
const publicUrl: string = this.config.get('publicUrl')!; const publicUrl: string = this.config.get('publicUrl')!;

View file

@ -7,7 +7,7 @@ export const CARD_WITH_CONTEXT = {
include: { include: {
cardDesign: { include: { rewards: { where: { active: true }, orderBy: { cost: 'asc' } } } }, cardDesign: { include: { rewards: { where: { active: true }, orderBy: { cost: 'asc' } } } },
subscription: { select: { plan: true, status: true } }, subscription: { select: { plan: true, status: true } },
campaigns: { orderBy: { createdAt: 'desc' }, take: 1, select: { message: true } }, campaigns: { orderBy: { createdAt: 'desc' }, take: 1, select: { message: true, createdAt: true } },
}, },
}, },
} satisfies Prisma.LoyaltyCardInclude; } satisfies Prisma.LoyaltyCardInclude;
@ -42,7 +42,44 @@ export function rewardsText(card: CardWithContext) {
return rewards.length ? rewards.map((r) => `${r.label} — ${r.cost} ${unit}`).join('\n') : 'Renseignez-vous au comptoir.'; return rewards.length ? rewards.map((r) => `${r.label} — ${r.cost} ${unit}`).join('\n') : 'Renseignez-vous au comptoir.';
} }
/** Dernier message de campagne du magasin (affiché au dos de la carte Apple). */
export function latestNews(card: CardWithContext) { export const DEFAULT_REMINDER = 'Vous nous manquez, {prenom} ! Votre solde de {solde} vous attend en magasin.';
return card.store.campaigns[0]?.message ?? null;
/** Texte de relance personnalisé pour ce client. */
export function reminderText(card: CardWithContext) {
const unit = card.store.cardDesign?.pointsMode === 'STAMP' ? 'tampon' : 'point';
const solde = `${card.balance} ${unit}${card.balance > 1 ? 's' : ''}`;
return (card.store.reminderMessage || DEFAULT_REMINDER)
.replaceAll('{prenom}', card.customer.firstName)
.replaceAll('{solde}', solde);
}
export const DEFAULT_BIRTHDAY = 'Joyeux anniversaire, {prenom} ! {cadeau}';
/** « 5 tampons offerts sur votre carte. » (ou rien si le magasin n'offre pas de points). */
export function birthdayGiftText(card: CardWithContext) {
const n = card.store.birthdayPoints;
if (n <= 0) return '';
const unit = card.store.cardDesign?.pointsMode === 'STAMP' ? 'tampon' : 'point';
return `${n} ${unit}${n > 1 ? 's' : ''} offert${n > 1 ? 's' : ''} sur votre carte.`;
}
export function birthdayText(card: CardWithContext) {
return (card.store.birthdayMessage || DEFAULT_BIRTHDAY)
.replaceAll('{prenom}', card.customer.firstName)
.replaceAll('{cadeau}', birthdayGiftText(card))
.replace(/\s+/g, ' ')
.trim();
}
/** Rubrique « Actualité » : le message le plus récent entre campagne, relance et anniversaire. */
export function newsText(card: CardWithContext) {
const campaign = card.store.campaigns[0];
const items: [Date | null | undefined, () => string][] = [
[campaign?.createdAt, () => campaign!.message],
[card.reminderSentAt, () => reminderText(card)],
[card.birthdayGiftAt, () => birthdayText(card)],
];
const latest = items.filter(([d]) => d).sort((a, b) => b[0]!.getTime() - a[0]!.getTime())[0];
return latest ? latest[1]() : null;
} }

View file

@ -49,6 +49,8 @@ function Navigator() {
<Stack.Screen name="done" options={{ headerShown: false, gestureEnabled: false }} /> <Stack.Screen name="done" options={{ headerShown: false, gestureEnabled: false }} />
<Stack.Screen name="history" options={{ title: 'Historique' }} /> <Stack.Screen name="history" options={{ title: 'Historique' }} />
<Stack.Screen name="campaigns" options={{ title: 'Campagnes' }} /> <Stack.Screen name="campaigns" options={{ title: 'Campagnes' }} />
<Stack.Screen name="reminders" options={{ title: 'Relance des inactifs' }} />
<Stack.Screen name="birthday" options={{ title: "Offre d'anniversaire" }} />
</Stack.Protected> </Stack.Protected>
</Stack> </Stack>
); );

120
pro/app/birthday.tsx Normal file
View file

@ -0,0 +1,120 @@
import { useCallback, useState } from 'react';
import { Pressable, ScrollView, Switch, TextInput, View } from 'react-native';
import { useFocusEffect } from 'expo-router';
import { api } from '../src/api';
import { describe } from '../src/errors';
import { useStore } from '../src/session';
import { Banner, Button, Card, T, unit } from '../src/ui';
import { font, useColors } from '../src/theme';
interface Birthday {
allowed: boolean;
settings: { enabled: boolean; points: number; message: string | null };
defaultMessage: string;
maxPoints: number;
stats: { cards: number; known: number; giftedThisYear: number };
}
/** Offre d'anniversaire (gérants, formule Pro). */
export default function BirthdayScreen() {
const c = useColors();
const store = useStore();
const [data, setData] = useState<Birthday | null>(null);
const [enabled, setEnabled] = useState(false);
const [points, setPoints] = useState(0);
const [message, setMessage] = useState('');
const [error, setError] = useState<string | null>(null);
const [saved, setSaved] = useState(false);
const [busy, setBusy] = useState(false);
const apply = (d: Birthday) => {
setData(d);
setEnabled(d.settings.enabled);
setPoints(d.settings.points);
setMessage(d.settings.message ?? '');
};
useFocusEffect(
useCallback(() => {
api.get<Birthday>('/api/staff/birthday').then(apply).catch((e) => setError(describe(e).detail));
}, []),
);
async function save() {
setBusy(true);
setError(null);
setSaved(false);
try {
apply(await api.put<Birthday>('/api/staff/birthday', { enabled, points, message: message.trim() || null }));
setSaved(true);
} catch (e) {
setError(describe(e).detail);
} finally {
setBusy(false);
}
}
if (!data) return <View style={{ padding: 20 }}>{error ? <Banner tone="error">{error}</Banner> : <T v="muted">Chargement…</T>}</View>;
const step = (d: number) => setPoints((p) => Math.max(0, Math.min(data.maxPoints, p + d)));
const stepper = (label: string, d: number) => (
<Pressable
accessibilityRole="button"
accessibilityLabel={d > 0 ? 'Plus' : 'Moins'}
onPress={() => step(d)}
style={{ width: 48, height: 48, borderRadius: 24, borderWidth: 1, borderColor: c.border, backgroundColor: c.surface, alignItems: 'center', justifyContent: 'center' }}
>
<T style={{ fontFamily: font.bold, fontSize: 22 }}>{label}</T>
</Pressable>
);
return (
<ScrollView contentContainerStyle={{ padding: 20, gap: 16 }} keyboardShouldPersistTaps="handled">
{error && <Banner tone="error">{error}</Banner>}
{saved && <Banner tone="ok">Réglages enregistrés.</Banner>}
{!data.allowed && <Banner tone="warn">L'offre d'anniversaire est incluse dans la formule Pro. Contactez MonEspacePro pour changer de formule.</Banner>}
<T v="muted">
Vos clients indiquent leur anniversaire à l'inscription ou sur la page de leur carte. Le jour J, ils reçoivent une notification et votre cadeau. Un cadeau par an.
</T>
<Card style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', padding: 16 }}>
<T v="label">Offre d'anniversaire</T>
<Switch value={enabled} onValueChange={setEnabled} disabled={!data.allowed && !enabled} accessibilityLabel="Offre d'anniversaire" />
</Card>
<T v="label">Cadeau</T>
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 16 }}>
{stepper('−', -1)}
<T style={{ fontFamily: font.extrabold, fontSize: 26, minWidth: 40, textAlign: 'center' }}>{points}</T>
{stepper('+', 1)}
<T v="muted" style={{ flex: 1 }}>{points === 0 ? 'message seulement' : `${unit(store.design.pointsMode, points)} offert${points > 1 ? 's' : ''}`}</T>
</View>
<T v="label">Message</T>
<TextInput
value={message}
onChangeText={setMessage}
multiline
maxLength={160}
placeholder={data.defaultMessage}
placeholderTextColor={c.text3}
accessibilityLabel="Message d'anniversaire"
style={{ minHeight: 90, borderWidth: 1, borderColor: c.border, borderRadius: 14, padding: 14, backgroundColor: c.surface, color: c.text, fontFamily: font.regular, fontSize: 16, textAlignVertical: 'top' }}
/>
<T v="muted" style={{ fontSize: 13 }}>Vide = texte par défaut. {'{prenom}'} et {'{cadeau}'} sont remplacés automatiquement.</T>
<Button label="Enregistrer" onPress={save} loading={busy} />
<View style={{ flexDirection: 'row', gap: 12 }}>
{[
[`${data.stats.known}/${data.stats.cards}`, 'anniversaires connus'],
[data.stats.giftedThisYear, 'cadeaux (12 mois)'],
].map(([n, l]) => (
<Card key={String(l)} style={{ flex: 1, padding: 14, gap: 2 }}>
<T style={{ fontFamily: font.extrabold, fontSize: 22 }}>{n}</T>
<T v="muted" style={{ fontSize: 13 }}>{l}</T>
</Card>
))}
</View>
</ScrollView>
);
}

View file

@ -113,6 +113,8 @@ export default function Home() {
<View style={{ flex: 1 }} /> <View style={{ flex: 1 }} />
{isManager && <Button label="Envoyer une campagne" variant="secondary" onPress={() => router.push('/campaigns')} />} {isManager && <Button label="Envoyer une campagne" variant="secondary" onPress={() => router.push('/campaigns')} />}
{isManager && <Button label="Relance des clients inactifs" variant="secondary" onPress={() => router.push('/reminders')} />}
{isManager && <Button label="Offre d'anniversaire" variant="secondary" onPress={() => router.push('/birthday')} />}
<Button label="Historique des opérations" variant="secondary" onPress={() => router.push('/history')} /> <Button label="Historique des opérations" variant="secondary" onPress={() => router.push('/history')} />
</ScrollView> </ScrollView>
</SafeAreaView> </SafeAreaView>

116
pro/app/reminders.tsx Normal file
View file

@ -0,0 +1,116 @@
import { useCallback, useState } from 'react';
import { Pressable, ScrollView, Switch, TextInput, View } from 'react-native';
import { useFocusEffect } from 'expo-router';
import { api } from '../src/api';
import { describe } from '../src/errors';
import { Banner, Button, Card, T } from '../src/ui';
import { font, useColors } from '../src/theme';
interface Reminders {
allowed: boolean;
settings: { enabled: boolean; days: number; message: string | null };
defaultMessage: string;
dayChoices: number[];
stats: { pending: number; sentLast30Days: number; cameBack: number; totalReminded: number };
}
/** Relance automatique des clients inactifs (gérants, formule Pro). */
export default function RemindersScreen() {
const c = useColors();
const [data, setData] = useState<Reminders | null>(null);
const [enabled, setEnabled] = useState(false);
const [days, setDays] = useState(45);
const [message, setMessage] = useState('');
const [error, setError] = useState<string | null>(null);
const [saved, setSaved] = useState(false);
const [busy, setBusy] = useState(false);
const apply = (d: Reminders) => {
setData(d);
setEnabled(d.settings.enabled);
setDays(d.settings.days);
setMessage(d.settings.message ?? '');
};
useFocusEffect(
useCallback(() => {
api.get<Reminders>('/api/staff/reminders').then(apply).catch((e) => setError(describe(e).detail));
}, []),
);
async function save() {
setBusy(true);
setError(null);
setSaved(false);
try {
apply(await api.put<Reminders>('/api/staff/reminders', { enabled, days, message: message.trim() || null }));
setSaved(true);
} catch (e) {
setError(describe(e).detail);
} finally {
setBusy(false);
}
}
if (!data) return <View style={{ padding: 20 }}>{error ? <Banner tone="error">{error}</Banner> : <T v="muted">Chargement…</T>}</View>;
const s = data.stats;
return (
<ScrollView contentContainerStyle={{ padding: 20, gap: 16 }} keyboardShouldPersistTaps="handled">
{error && <Banner tone="error">{error}</Banner>}
{saved && <Banner tone="ok">Réglages enregistrés.</Banner>}
{!data.allowed && <Banner tone="warn">La relance automatique est incluse dans la formule Pro. Contactez MonEspacePro pour changer de formule.</Banner>}
<T v="muted">
Un client qui n'est pas revenu depuis le délai choisi reçoit une notification sur sa carte, entre 10 h et 19 h. Une seule relance par absence.
</T>
<Card style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', padding: 16 }}>
<T v="label">Relance automatique</T>
<Switch value={enabled} onValueChange={setEnabled} disabled={!data.allowed && !enabled} accessibilityLabel="Relance automatique" />
</Card>
<T v="label">Relancer après</T>
<View style={{ flexDirection: 'row', gap: 8, flexWrap: 'wrap' }}>
{data.dayChoices.map((d) => (
<Pressable
key={d}
accessibilityRole="button"
accessibilityState={{ selected: days === d }}
onPress={() => setDays(d)}
style={{ paddingVertical: 10, paddingHorizontal: 16, borderRadius: 999, borderWidth: 1, borderColor: days === d ? c.primary : c.border, backgroundColor: days === d ? c.primarySoft : c.surface }}
>
<T style={{ fontFamily: font.semibold, color: days === d ? c.primary : c.text }}>{d} jours</T>
</Pressable>
))}
</View>
<T v="label">Message</T>
<TextInput
value={message}
onChangeText={setMessage}
multiline
maxLength={160}
placeholder={data.defaultMessage}
placeholderTextColor={c.text3}
accessibilityLabel="Message de relance"
style={{ minHeight: 90, borderWidth: 1, borderColor: c.border, borderRadius: 14, padding: 14, backgroundColor: c.surface, color: c.text, fontFamily: font.regular, fontSize: 16, textAlignVertical: 'top' }}
/>
<T v="muted" style={{ fontSize: 13 }}>Vide = texte par défaut. {'{prenom}'} et {'{solde}'} sont remplacés automatiquement.</T>
<Button label="Enregistrer" onPress={save} loading={busy} />
<View style={{ flexDirection: 'row', gap: 12 }}>
{[
[s.pending, 'à relancer'],
[s.sentLast30Days, 'relances (30 j)'],
[`${s.cameBack}/${s.totalReminded}`, 'revenus'],
].map(([n, l]) => (
<Card key={String(l)} style={{ flex: 1, padding: 14, gap: 2 }}>
<T style={{ fontFamily: font.extrabold, fontSize: 22 }}>{n}</T>
<T v="muted" style={{ fontSize: 13 }}>{l}</T>
</Card>
))}
</View>
</ScrollView>
);
}

View file

@ -100,6 +100,7 @@ async function request<T>(method: string, path: string, body?: unknown, auth = t
export const api = { export const api = {
get: <T>(path: string) => request<T>('GET', path), get: <T>(path: string) => request<T>('GET', path),
post: <T>(path: string, body: unknown = {}) => request<T>('POST', path, body), post: <T>(path: string, body: unknown = {}) => request<T>('POST', path, body),
put: <T>(path: string, body: unknown) => request<T>('PUT', path, body),
}; };
// ── Types de l'API ───────────────────────────────────────────── // ── Types de l'API ─────────────────────────────────────────────

View file

@ -25,8 +25,8 @@ const MARKETING = {
{ label: 'Employés illimités' }, { label: 'Employés illimités' },
{ label: 'Sans la mention « Propulsé par MonEspacePro »' }, { label: 'Sans la mention « Propulsé par MonEspacePro »' },
{ label: 'Notifications et campagnes sur l’écran du téléphone' }, { label: 'Notifications et campagnes sur l’écran du téléphone' },
{ label: 'Relance automatique des clients inactifs', soon: true }, { label: 'Relance automatique des clients inactifs' },
{ label: 'Offre d’anniversaire', soon: true }, { label: 'Offre d’anniversaire' },
{ label: 'Collecte d’avis Google', soon: true }, { label: 'Collecte d’avis Google', soon: true },
{ label: 'Parrainage', soon: true }, { label: 'Parrainage', soon: true },
{ label: 'Statistiques avancées et export CSV', soon: true }, { label: 'Statistiques avancées et export CSV', soon: true },

View file

@ -118,8 +118,8 @@
<li><svg class="ico"><use href="#i-check"/></svg><span>Employés illimités</span></li> <li><svg class="ico"><use href="#i-check"/></svg><span>Employés illimités</span></li>
<li><svg class="ico"><use href="#i-check"/></svg><span>Sans la mention « Propulsé par MonEspacePro »</span></li> <li><svg class="ico"><use href="#i-check"/></svg><span>Sans la mention « Propulsé par MonEspacePro »</span></li>
<li><svg class="ico"><use href="#i-check"/></svg><span>Notifications et campagnes sur l’écran du téléphone</span></li> <li><svg class="ico"><use href="#i-check"/></svg><span>Notifications et campagnes sur l’écran du téléphone</span></li>
<li class="soon"><svg class="ico"><use href="#i-check"/></svg><span>Relance automatique des clients inactifs <span class="soon-tag">Bientôt</span></span></li> <li><svg class="ico"><use href="#i-check"/></svg><span>Relance automatique des clients inactifs</span></li>
<li class="soon"><svg class="ico"><use href="#i-check"/></svg><span>Offre d’anniversaire <span class="soon-tag">Bientôt</span></span></li> <li><svg class="ico"><use href="#i-check"/></svg><span>Offre d’anniversaire</span></li>
<li class="soon"><svg class="ico"><use href="#i-check"/></svg><span>Collecte d’avis Google <span class="soon-tag">Bientôt</span></span></li> <li class="soon"><svg class="ico"><use href="#i-check"/></svg><span>Collecte d’avis Google <span class="soon-tag">Bientôt</span></span></li>
<li class="soon"><svg class="ico"><use href="#i-check"/></svg><span>Parrainage <span class="soon-tag">Bientôt</span></span></li> <li class="soon"><svg class="ico"><use href="#i-check"/></svg><span>Parrainage <span class="soon-tag">Bientôt</span></span></li>
<li class="soon"><svg class="ico"><use href="#i-check"/></svg><span>Statistiques avancées et export CSV <span class="soon-tag">Bientôt</span></span></li> <li class="soon"><svg class="ico"><use href="#i-check"/></svg><span>Statistiques avancées et export CSV <span class="soon-tag">Bientôt</span></span></li>