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>
This commit is contained in:
parent
a9baf09e0d
commit
699853d7c0
18 changed files with 498 additions and 24 deletions
|
|
@ -1,5 +1,6 @@
|
||||||
import { useCallback, useEffect, useState } from 'react';
|
import { useCallback, useEffect, useState } from 'react';
|
||||||
import { api } from '../api';
|
import { api } from '../api';
|
||||||
|
import { RemindersCard } from './RemindersCard';
|
||||||
|
|
||||||
interface Campaign {
|
interface Campaign {
|
||||||
id: string;
|
id: string;
|
||||||
|
|
@ -88,6 +89,8 @@ 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} />
|
||||||
|
|
||||||
<section className="card">
|
<section className="card">
|
||||||
<h2>Historique</h2>
|
<h2>Historique</h2>
|
||||||
{data.items.length === 0 ? (
|
{data.items.length === 0 ? (
|
||||||
|
|
|
||||||
101
admin/src/pages/RemindersCard.tsx
Normal file
101
admin/src/pages/RemindersCard.tsx
Normal 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>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -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', 'Campagnes et relances'],
|
||||||
['facturation', 'Facturation'],
|
['facturation', 'Facturation'],
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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;
|
||||||
|
|
@ -48,6 +48,12 @@ 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)
|
||||||
|
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
|
|
@ -123,25 +129,27 @@ model Customer {
|
||||||
}
|
}
|
||||||
|
|
||||||
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[]
|
createdAt DateTime @default(now())
|
||||||
devices AppleRegistration[]
|
updatedAt DateTime @updatedAt
|
||||||
|
transactions Transaction[]
|
||||||
|
devices AppleRegistration[]
|
||||||
|
|
||||||
@@unique([storeId, customerId])
|
@@unique([storeId, customerId])
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -14,6 +14,7 @@ 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 { HealthController } from './health.controller';
|
import { HealthController } from './health.controller';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
|
|
@ -31,6 +32,7 @@ import { HealthController } from './health.controller';
|
||||||
BillingModule,
|
BillingModule,
|
||||||
EntitlementsModule,
|
EntitlementsModule,
|
||||||
CampaignsModule,
|
CampaignsModule,
|
||||||
|
RemindersModule,
|
||||||
],
|
],
|
||||||
controllers: [HealthController],
|
controllers: [HealthController],
|
||||||
providers: [{ provide: APP_GUARD, useClass: ThrottlerGuard }],
|
providers: [{ provide: APP_GUARD, useClass: ThrottlerGuard }],
|
||||||
|
|
|
||||||
58
backend/src/reminders/reminders.controller.ts
Normal file
58
backend/src/reminders/reminders.controller.ts
Normal 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 {}
|
||||||
143
backend/src/reminders/reminders.service.ts
Normal file
143
backend/src/reminders/reminders.service.ts
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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',
|
||||||
|
|
|
||||||
|
|
@ -69,6 +69,18 @@ export class CardUpdatesService {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Relance d'un client inactif : 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: { devices: { include: { device: true } } },
|
||||||
|
});
|
||||||
|
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 } } });
|
||||||
|
|
|
||||||
|
|
@ -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')!;
|
||||||
|
|
|
||||||
|
|
@ -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,21 @@ 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Rubrique « Actualité » : la relance de ce client si elle est plus récente que la dernière campagne. */
|
||||||
|
export function newsText(card: CardWithContext) {
|
||||||
|
const campaign = card.store.campaigns[0];
|
||||||
|
if (card.reminderSentAt && (!campaign || card.reminderSentAt > campaign.createdAt)) return reminderText(card);
|
||||||
|
return campaign?.message ?? null;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -49,6 +49,7 @@ 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.Protected>
|
</Stack.Protected>
|
||||||
</Stack>
|
</Stack>
|
||||||
);
|
);
|
||||||
|
|
|
||||||
|
|
@ -113,6 +113,7 @@ 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')} />}
|
||||||
<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
116
pro/app/reminders.tsx
Normal 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>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -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 ─────────────────────────────────────────────
|
||||||
|
|
|
||||||
|
|
@ -25,7 +25,7 @@ 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', soon: true },
|
||||||
{ label: 'Collecte d’avis Google', soon: true },
|
{ label: 'Collecte d’avis Google', soon: true },
|
||||||
{ label: 'Parrainage', soon: true },
|
{ label: 'Parrainage', soon: true },
|
||||||
|
|
|
||||||
|
|
@ -118,7 +118,7 @@
|
||||||
<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 class="soon"><svg class="ico"><use href="#i-check"/></svg><span>Offre d’anniversaire <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>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>
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue