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>
This commit is contained in:
parent
699853d7c0
commit
166f7888cd
19 changed files with 612 additions and 24 deletions
106
admin/src/pages/BirthdayCard.tsx
Normal file
106
admin/src/pages/BirthdayCard.tsx
Normal 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>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -1,6 +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 { RemindersCard } from './RemindersCard';
|
||||||
|
import { BirthdayCard } from './BirthdayCard';
|
||||||
|
|
||||||
interface Campaign {
|
interface Campaign {
|
||||||
id: string;
|
id: string;
|
||||||
|
|
@ -90,6 +91,7 @@ export function CampaignsTab({ storeId, storeName }: { storeId: string; storeNam
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<RemindersCard storeId={storeId} />
|
<RemindersCard storeId={storeId} />
|
||||||
|
<BirthdayCard storeId={storeId} />
|
||||||
|
|
||||||
<section className="card">
|
<section className="card">
|
||||||
<h2>Historique</h2>
|
<h2>Historique</h2>
|
||||||
|
|
|
||||||
|
|
@ -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 et relances'],
|
['campagnes', 'Fidélisation'],
|
||||||
['facturation', 'Facturation'],
|
['facturation', 'Facturation'],
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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;
|
||||||
|
|
@ -54,6 +54,13 @@ model Store {
|
||||||
/// Texte de la relance ; {prenom} et {solde} sont remplacés. Vide = texte par défaut.
|
/// Texte de la relance ; {prenom} et {solde} sont remplacés. Vide = texte par défaut.
|
||||||
reminderMessage String? @db.VarChar(160)
|
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
|
||||||
|
|
||||||
|
|
@ -120,12 +127,15 @@ 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 {
|
||||||
|
|
@ -146,6 +156,8 @@ model LoyaltyCard {
|
||||||
lastCreditAt DateTime?
|
lastCreditAt DateTime?
|
||||||
/// Dernière relance « client inactif » envoyée (une seule par période d'inactivité).
|
/// Dernière relance « client inactif » envoyée (une seule par période d'inactivité).
|
||||||
reminderSentAt DateTime?
|
reminderSentAt DateTime?
|
||||||
|
/// Dernier cadeau d'anniversaire (un par an).
|
||||||
|
birthdayGiftAt DateTime?
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
transactions Transaction[]
|
transactions Transaction[]
|
||||||
|
|
|
||||||
|
|
@ -15,6 +15,7 @@ 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 { RemindersModule } from './reminders/reminders.controller';
|
||||||
|
import { BirthdaysModule } from './birthdays/birthdays.controller';
|
||||||
import { HealthController } from './health.controller';
|
import { HealthController } from './health.controller';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
|
|
@ -33,6 +34,7 @@ import { HealthController } from './health.controller';
|
||||||
EntitlementsModule,
|
EntitlementsModule,
|
||||||
CampaignsModule,
|
CampaignsModule,
|
||||||
RemindersModule,
|
RemindersModule,
|
||||||
|
BirthdaysModule,
|
||||||
],
|
],
|
||||||
controllers: [HealthController],
|
controllers: [HealthController],
|
||||||
providers: [{ provide: APP_GUARD, useClass: ThrottlerGuard }],
|
providers: [{ provide: APP_GUARD, useClass: ThrottlerGuard }],
|
||||||
|
|
|
||||||
87
backend/src/birthdays/birthdays.controller.ts
Normal file
87
backend/src/birthdays/birthdays.controller.ts
Normal 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 {}
|
||||||
153
backend/src/birthdays/birthdays.service.ts
Normal file
153
backend/src/birthdays/birthdays.service.ts
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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')
|
||||||
|
|
|
||||||
|
|
@ -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 {}
|
||||||
|
|
|
||||||
|
|
@ -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,
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -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, '&')
|
.replace(/&/g, '&')
|
||||||
|
|
@ -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>
|
||||||
|
|
|
||||||
|
|
@ -69,12 +69,14 @@ export class CardUpdatesService {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Relance d'un client inactif : la rubrique « Actualité » Apple change (notification), message Google sur sa carte. */
|
/** Message personnel (relance, anniversaire) : la rubrique « Actualité » Apple change (notification), message Google sur sa carte. */
|
||||||
async remind(cardId: string, text: string, storeName: string) {
|
async remind(cardId: string, text: string, storeName: string) {
|
||||||
const card = await this.prisma.loyaltyCard.findUniqueOrThrow({
|
const card = await this.prisma.loyaltyCard.findUniqueOrThrow({
|
||||||
where: { id: cardId },
|
where: { id: cardId },
|
||||||
include: { devices: { include: { device: true } } },
|
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([
|
await Promise.all([
|
||||||
this.pushApple(card.devices.map((r) => r.device.pushToken)),
|
this.pushApple(card.devices.map((r) => r.device.pushToken)),
|
||||||
this.google.addObjectMessage(card.serial, `reminder_${Date.now()}`, storeName, text),
|
this.google.addObjectMessage(card.serial, `reminder_${Date.now()}`, storeName, text),
|
||||||
|
|
|
||||||
|
|
@ -54,9 +54,32 @@ export function reminderText(card: CardWithContext) {
|
||||||
.replaceAll('{solde}', solde);
|
.replaceAll('{solde}', solde);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Rubrique « Actualité » : la relance de ce client si elle est plus récente que la dernière campagne. */
|
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) {
|
export function newsText(card: CardWithContext) {
|
||||||
const campaign = card.store.campaigns[0];
|
const campaign = card.store.campaigns[0];
|
||||||
if (card.reminderSentAt && (!campaign || card.reminderSentAt > campaign.createdAt)) return reminderText(card);
|
const items: [Date | null | undefined, () => string][] = [
|
||||||
return campaign?.message ?? null;
|
[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;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -50,6 +50,7 @@ function Navigator() {
|
||||||
<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="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
120
pro/app/birthday.tsx
Normal 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>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -114,6 +114,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')} />}
|
{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>
|
||||||
|
|
|
||||||
|
|
@ -26,7 +26,7 @@ const MARKETING = {
|
||||||
{ 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' },
|
{ 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 },
|
||||||
|
|
|
||||||
|
|
@ -119,7 +119,7 @@
|
||||||
<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><svg class="ico"><use href="#i-check"/></svg><span>Relance automatique des clients inactifs</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>
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue