Campagnes : notification Wallet à toutes les cartes d'un magasin (formule Pro)

- Modèle Campaign + migration manuelle 2026-10-07-campagnes.sql
- Apple : champ « Actualité » au dos avec changeMessage, push APNs
- Google : message de classe TEXT_AND_NOTIFY
- 1 campagne par 24 h, magasin actif, message différent du précédent
- Onglet Campagnes dans l'admin, écran Campagnes (gérants) dans l'app Pro
- Site : « Bientôt » retiré des campagnes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Tony AVERTY 2026-10-07 10:20:49 +02:00
parent 8eb1ce3821
commit a9baf09e0d
16 changed files with 526 additions and 88 deletions

View file

@ -0,0 +1,122 @@
import { useCallback, useEffect, useState } from 'react';
import { api } from '../api';
interface Campaign {
id: string;
message: string;
sentByName: string;
cards: number;
appleDevices: number;
createdAt: string;
}
interface Overview {
allowed: boolean;
audience: { cards: number; appleDevices: number };
nextAllowedAt: string | null;
items: Campaign[];
}
const MAX = 160;
const when = (d: string) =>
new Date(d).toLocaleString('fr-FR', { day: 'numeric', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' });
export function CampaignsTab({ storeId, storeName }: { storeId: string; storeName: string }) {
const [data, setData] = useState<Overview | null>(null);
const [message, setMessage] = useState('');
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const load = useCallback(() => {
api.get<Overview>(`/api/admin/stores/${storeId}/campaigns`).then(setData).catch((e) => setError(e.message));
}, [storeId]);
useEffect(load, [load]);
if (!data) return error ? <div className="alert error">{error}</div> : <p className="muted">Chargement…</p>;
const text = message.trim();
const blocked = !data.allowed || !!data.nextAllowedAt;
async function send() {
if (!confirm(`Envoyer ce message aux ${data!.audience.cards} cartes de ${storeName} ?\n\n« ${text} »`)) return;
setBusy(true);
setError(null);
try {
await api.post(`/api/admin/stores/${storeId}/campaigns`, { message: text });
setMessage('');
setNotice('Campagne envoyée. Les cartes se mettent à jour dans les minutes qui suivent.');
load();
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(false);
}
}
return (
<>
{error && <div className="alert error" role="alert">{error}</div>}
{notice && <div className="alert ok" role="status">{notice}</div>}
{!data.allowed && <div className="alert warn">Les campagnes sont réservées aux formules Pro et Réseau (abonnement actif).</div>}
<section className="card" style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
<div>
<h2>Nouvelle campagne</h2>
<p className="muted" style={{ margin: 0 }}>
Le message apparaît en notification sur le téléphone des clients et reste visible sur leur carte.
Audience : <strong>{data.audience.cards}</strong> cartes, dont <strong>{data.audience.appleDevices}</strong> iPhone joignables (Google Wallet : tous les clients qui ont ajouté la carte).
</p>
</div>
<label htmlFor="campaign-msg" className="sr-only">Message</label>
<textarea
id="campaign-msg"
className="input"
rows={3}
maxLength={MAX}
placeholder="Ex. : -20 % sur les viennoiseries ce samedi, sur présentation de votre carte !"
value={message}
onChange={(e) => setMessage(e.target.value)}
disabled={blocked || busy}
/>
<div className="row between">
<span className="muted" style={{ fontSize: 14 }}>{text.length} / {MAX} caractères · 1 campagne par jour maximum</span>
<button className="btn" disabled={blocked || busy || text.length < 5} onClick={send}>
{busy ? 'Envoi…' : 'Envoyer la campagne'}
</button>
</div>
{data.nextAllowedAt && <div className="alert warn">Prochain envoi possible le {when(data.nextAllowedAt)}.</div>}
</section>
<section className="card">
<h2>Historique</h2>
{data.items.length === 0 ? (
<p className="muted" style={{ margin: 0 }}>Aucune campagne envoyée pour l'instant.</p>
) : (
<div className="table-scroll">
<table>
<thead>
<tr>
<th scope="col">Date</th>
<th scope="col">Message</th>
<th scope="col">Envoyée par</th>
<th scope="col" className="num">Cartes</th>
</tr>
</thead>
<tbody>
{data.items.map((c) => (
<tr key={c.id}>
<td className="muted" style={{ whiteSpace: 'nowrap' }}>{when(c.createdAt)}</td>
<td>{c.message}</td>
<td>{c.sentByName}</td>
<td className="num">{c.cards}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</section>
</>
);
}

View file

@ -6,11 +6,13 @@ import { StoreForm } from '../components/StoreForm';
import { CardWizard } from './CardWizard';
import { StaffTab } from './StaffTab';
import { BillingTab } from './BillingTab';
import { CampaignsTab } from './CampaignsTab';
const TABS = [
['infos', 'Infos'],
['carte', 'Carte de fidélité'],
['employes', 'Employés'],
['campagnes', 'Campagnes'],
['facturation', 'Facturation'],
] as const;
@ -109,6 +111,7 @@ export function StorePage() {
/>
<Route path="carte" element={<CardWizard store={store} onSaved={reload} />} />
<Route path="employes" element={<StaffTab storeId={store.id} />} />
<Route path="campagnes" element={<CampaignsTab storeId={store.id} storeName={store.name} />} />
<Route path="facturation" element={<BillingTab storeId={store.id} contactEmail={store.contactEmail} onChange={reload} />} />
</Routes>
</>

View file

@ -0,0 +1,13 @@
-- Notifications de campagne (formule Pro).
CREATE TABLE `Campaign` (
`id` VARCHAR(191) NOT NULL,
`storeId` VARCHAR(191) NOT NULL,
`message` VARCHAR(160) NOT NULL,
`sentByName` VARCHAR(191) NOT NULL,
`cards` INTEGER NOT NULL,
`appleDevices` INTEGER NOT NULL,
`createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
INDEX `Campaign_storeId_createdAt_idx`(`storeId`, `createdAt`),
PRIMARY KEY (`id`),
CONSTRAINT `Campaign_storeId_fkey` FOREIGN KEY (`storeId`) REFERENCES `Store`(`id`) ON DELETE CASCADE ON UPDATE CASCADE
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

View file

@ -22,46 +22,47 @@ model Admin {
// ── Magasins ──────────────────────────────────────────────────
enum StoreStatus {
DRAFT /// créé, carte pas encore conçue / abonnement pas encore actif
DRAFT /// créé, carte pas encore conçue / abonnement pas encore actif
ACTIVE
SUSPENDED /// paiement échoué : scans et inscriptions refusés
SUSPENDED /// paiement échoué : scans et inscriptions refusés
CLOSED
}
model Store {
id String @id @default(cuid())
id String @id @default(cuid())
/// Identifiant public court utilisé dans les URL d'inscription (/c/<slug>).
slug String @unique
name String
addressLine String
postalCode String
city String
siret String @db.Char(14)
contactName String
contactEmail String
contactPhone String
status StoreStatus @default(DRAFT)
slug String @unique
name String
addressLine String
postalCode String
city String
siret String @db.Char(14)
contactName String
contactEmail String
contactPhone String
status StoreStatus @default(DRAFT)
/// Suspendu automatiquement pour impayé (réactivé automatiquement au paiement).
billingSuspended Boolean @default(false)
billingSuspended Boolean @default(false)
// Anti-triche : réglages par magasin
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
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
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
cardDesign CardDesign?
staff StaffUser[]
cards LoyaltyCard[]
transactions Transaction[]
subscription Subscription?
invoices Invoice[]
cardDesign CardDesign?
staff StaffUser[]
cards LoyaltyCard[]
transactions Transaction[]
subscription Subscription?
invoices Invoice[]
campaigns Campaign[]
}
enum PointsMode {
AMOUNT /// points proportionnels au montant (pointsPerEuro)
STAMP /// un tampon par passage
AMOUNT /// points proportionnels au montant (pointsPerEuro)
STAMP /// un tampon par passage
}
model CardDesign {
@ -70,7 +71,7 @@ model CardDesign {
store Store @relation(fields: [storeId], references: [id], onDelete: Cascade)
programName String
logoPath String?
stripPath String? /// bandeau
stripPath String? /// bandeau
backgroundColor String @default("#1F2937")
foregroundColor String @default("#FFFFFF")
labelColor String @default("#D1D5DB")
@ -81,12 +82,12 @@ model CardDesign {
}
model Reward {
id String @id @default(cuid())
id String @id @default(cuid())
cardDesignId String
cardDesign CardDesign @relation(fields: [cardDesignId], references: [id], onDelete: Cascade)
cardDesign CardDesign @relation(fields: [cardDesignId], references: [id], onDelete: Cascade)
label String
cost Int /// points ou tampons nécessaires
active Boolean @default(true)
cost Int /// points ou tampons nécessaires
active Boolean @default(true)
transactions Transaction[]
}
@ -97,50 +98,50 @@ enum StaffRole {
}
model StaffUser {
id String @id @default(cuid())
id String @id @default(cuid())
storeId String
store Store @relation(fields: [storeId], references: [id], onDelete: Cascade)
email String @unique
store Store @relation(fields: [storeId], references: [id], onDelete: Cascade)
email String @unique
displayName String
passwordHash String
role StaffRole @default(EMPLOYEE)
active Boolean @default(true)
role StaffRole @default(EMPLOYEE)
active Boolean @default(true)
/// Incrémenté pour révoquer tous les jetons de rafraîchissement.
tokenVersion Int @default(0)
createdAt DateTime @default(now())
tokenVersion Int @default(0)
createdAt DateTime @default(now())
transactions Transaction[]
}
// ── Clients finaux ────────────────────────────────────────────
model Customer {
id String @id @default(cuid())
firstName String
email String
consentAt DateTime /// consentement RGPD horodaté
createdAt DateTime @default(now())
cards LoyaltyCard[]
id String @id @default(cuid())
firstName String
email String
consentAt DateTime /// consentement RGPD horodaté
createdAt DateTime @default(now())
cards LoyaltyCard[]
}
model LoyaltyCard {
id String @id @default(cuid())
storeId String
store Store @relation(fields: [storeId], references: [id], onDelete: Cascade)
customerId String
customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade)
id String @id @default(cuid())
storeId String
store Store @relation(fields: [storeId], references: [id], onDelete: Cascade)
customerId String
customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade)
/// 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.
authToken String
authToken String
/// Clé secrète des liens client (page de la carte, téléchargement du pass).
accessKey String @unique
balance Int @default(0)
accessKey String @unique
balance Int @default(0)
/// Dernière modification visible dans le Wallet (solde, design du magasin) : sert aux mises à jour Apple.
passUpdatedAt DateTime @default(now())
lastCreditAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
transactions Transaction[]
devices AppleRegistration[]
passUpdatedAt DateTime @default(now())
lastCreditAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
transactions Transaction[]
devices AppleRegistration[]
@@unique([storeId, customerId])
}
@ -148,7 +149,7 @@ model LoyaltyCard {
enum TransactionType {
CREDIT
REDEEM
ADJUST /// correction manuelle (gérant)
ADJUST /// correction manuelle (gérant)
REJECTED /// tentative refusée par l'anti-triche (0 point), visible dans les opérations
}
@ -160,22 +161,22 @@ enum RejectReason {
/// Journal immuable : chaque scan est enregistré avec l'employé.
model Transaction {
id String @id @default(cuid())
storeId String
store Store @relation(fields: [storeId], references: [id], onDelete: Cascade)
cardId String
card LoyaltyCard @relation(fields: [cardId], references: [id], onDelete: Cascade)
staffId String
staff StaffUser @relation(fields: [staffId], references: [id])
type TransactionType
amountCents Int?
points Int /// positif (crédit) ou négatif (récompense)
id String @id @default(cuid())
storeId String
store Store @relation(fields: [storeId], references: [id], onDelete: Cascade)
cardId String
card LoyaltyCard @relation(fields: [cardId], references: [id], onDelete: Cascade)
staffId String
staff StaffUser @relation(fields: [staffId], references: [id])
type TransactionType
amountCents Int?
points Int /// positif (crédit) ou négatif (récompense)
/// Solde de la carte après l'opération (lecture de l'historique sans recalcul).
balanceAfter Int
rejectReason RejectReason?
rewardId String?
reward Reward? @relation(fields: [rewardId], references: [id])
createdAt DateTime @default(now())
rewardId String?
reward Reward? @relation(fields: [rewardId], references: [id])
createdAt DateTime @default(now())
@@index([storeId, createdAt])
@@index([cardId, createdAt])
@ -184,10 +185,10 @@ model Transaction {
// ── Apple Wallet (service web PassKit) ────────────────────────
model AppleDevice {
id String @id @default(cuid())
deviceLibraryId String @unique
pushToken String
registrations AppleRegistration[]
id String @id @default(cuid())
deviceLibraryId String @unique
pushToken String
registrations AppleRegistration[]
}
model AppleRegistration {
@ -239,24 +240,40 @@ model Subscription {
}
model Invoice {
id String @id @default(cuid())
id String @id @default(cuid())
/// Numérotation continue, sans trou : MEP-2026-000001
number String @unique
sequence Int @unique
number String @unique
sequence Int @unique
storeId String
store Store @relation(fields: [storeId], references: [id])
stripeInvoiceId String? @unique
store Store @relation(fields: [storeId], references: [id])
stripeInvoiceId String? @unique
amountCents Int
/// Libellé de la ligne (formule et période), figé à l'émission.
description String @default("Abonnement MonEspacePro — carte de fidélité dématérialisée, 1 magasin")
description String @default("Abonnement MonEspacePro — carte de fidélité dématérialisée, 1 magasin")
/// Identité du client figée à l'émission (une facture ne change plus).
clientName String
clientAddress String @db.Text
clientAddress String @db.Text
clientSiret String
clientEmail String
periodStart DateTime
periodEnd DateTime
issuedAt DateTime @default(now())
issuedAt DateTime @default(now())
paidAt DateTime?
pdfPath String?
}
/// Notification de campagne envoyée à toutes les cartes Wallet d'un magasin (formule Pro).
model Campaign {
id String @id @default(cuid())
storeId String
store Store @relation(fields: [storeId], references: [id], onDelete: Cascade)
message String @db.VarChar(160)
/// « MonEspacePro » (admin) ou nom du gérant qui l'a envoyée.
sentByName String
/// Cartes et iPhones visés au moment de l'envoi.
cards Int
appleDevices Int
createdAt DateTime @default(now())
@@index([storeId, createdAt])
}

View file

@ -13,6 +13,7 @@ import { ContactModule } from './contact/contact.controller';
import { BillingModule } from './billing/billing.controller';
import { EntitlementsModule } from './billing/entitlements.service';
import { WalletModule } from './wallet/wallet.module';
import { CampaignsModule } from './campaigns/campaigns.controller';
import { HealthController } from './health.controller';
@Module({
@ -29,6 +30,7 @@ import { HealthController } from './health.controller';
ContactModule,
BillingModule,
EntitlementsModule,
CampaignsModule,
],
controllers: [HealthController],
providers: [{ provide: APP_GUARD, useClass: ThrottlerGuard }],

View file

@ -0,0 +1,56 @@
import { Body, Controller, Get, Module, Param, Post, UseGuards } from '@nestjs/common';
import { Throttle } from '@nestjs/throttler';
import { IsString, MaxLength, MinLength } from 'class-validator';
import { JwtPayload } from '../common/auth.types';
import { AdminGuard, CurrentUser, JwtAuthGuard, StaffGuard, StaffRoles } from '../common/guards';
import { PrismaService } from '../prisma/prisma.service';
import { CampaignsService } from './campaigns.service';
class SendCampaignDto {
@IsString() @MinLength(5) @MaxLength(160)
message!: string;
}
@Controller('admin/stores/:id/campaigns')
@UseGuards(JwtAuthGuard, AdminGuard)
export class AdminCampaignsController {
constructor(private campaigns: CampaignsService) {}
@Get()
list(@Param('id') id: string) {
return this.campaigns.overview(id);
}
@Post()
send(@Param('id') id: string, @Body() dto: SendCampaignDto) {
return this.campaigns.send(id, dto.message, 'MonEspacePro');
}
}
/** App Pro : réservé aux gérants. */
@Controller('staff/campaigns')
@UseGuards(JwtAuthGuard, StaffGuard)
@StaffRoles('MANAGER')
export class StaffCampaignsController {
constructor(private campaigns: CampaignsService, private prisma: PrismaService) {}
@Get()
list(@CurrentUser() user: JwtPayload) {
if (user.kind !== 'staff') throw new Error('StaffGuard manquant');
return this.campaigns.overview(user.storeId);
}
@Post()
@Throttle({ default: { limit: 5, ttl: 60_000 } })
async send(@CurrentUser() user: JwtPayload, @Body() dto: SendCampaignDto) {
if (user.kind !== 'staff') throw new Error('StaffGuard manquant');
const staff = await this.prisma.staffUser.findUniqueOrThrow({ where: { id: user.sub }, select: { displayName: true } });
return this.campaigns.send(user.storeId, dto.message, staff.displayName);
}
}
@Module({
controllers: [AdminCampaignsController, StaffCampaignsController],
providers: [CampaignsService],
})
export class CampaignsModule {}

View file

@ -0,0 +1,68 @@
import { BadRequestException, ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { EntitlementsService } from '../billing/entitlements.service';
import { CardUpdatesService } from '../wallet/card-updates.service';
/** Une campagne par jour : Google limite à 3 notifications par carte et par 24 h, et les clients n'aiment pas être harcelés. */
export const CAMPAIGN_INTERVAL_MS = 24 * 3600_000;
@Injectable()
export class CampaignsService {
constructor(
private prisma: PrismaService,
private entitlements: EntitlementsService,
private cardUpdates: CardUpdatesService,
) {}
/** État de l'écran Campagnes : droits, audience, prochain envoi possible, historique. */
async overview(storeId: string) {
const store = await this.prisma.store.findUnique({ where: { id: storeId }, select: { id: true } });
if (!store) throw new NotFoundException('Magasin introuvable');
const [allowed, cards, appleDevices, items] = await Promise.all([
this.entitlements.can(storeId, 'campaigns'),
this.prisma.loyaltyCard.count({ where: { storeId } }),
this.prisma.appleDevice.count({ where: { registrations: { some: { card: { storeId } } } } }),
this.prisma.campaign.findMany({ where: { storeId }, orderBy: { createdAt: 'desc' }, take: 50 }),
]);
const last = items[0];
const nextAllowedAt =
last && last.createdAt.getTime() + CAMPAIGN_INTERVAL_MS > Date.now()
? new Date(last.createdAt.getTime() + CAMPAIGN_INTERVAL_MS)
: null;
return { allowed, audience: { cards, appleDevices }, nextAllowedAt, items };
}
async send(storeId: string, rawMessage: string, sentByName: string) {
await this.entitlements.require(storeId, 'campaigns');
const store = await this.prisma.store.findUnique({ where: { id: storeId } });
if (!store) throw new NotFoundException('Magasin introuvable');
if (store.status !== 'ACTIVE' || store.billingSuspended) {
throw new BadRequestException('Le magasin doit être actif pour envoyer une campagne.');
}
const message = rawMessage.replace(/\s+/g, ' ').trim();
if (message.length < 5) throw new BadRequestException('Le message est trop court.');
const last = await this.prisma.campaign.findFirst({ where: { storeId }, orderBy: { createdAt: 'desc' } });
if (last && last.createdAt.getTime() + CAMPAIGN_INTERVAL_MS > Date.now()) {
const at = new Date(last.createdAt.getTime() + CAMPAIGN_INTERVAL_MS);
throw new ConflictException({
statusCode: 409,
code: 'CAMPAIGN_TOO_SOON',
nextAllowedAt: at,
message: `Une campagne par jour au maximum. Prochain envoi possible le ${at.toLocaleString('fr-FR', { timeZone: 'Europe/Paris', dateStyle: 'short', timeStyle: 'short' })}.`,
});
}
// L'iPhone ne notifie que si le texte change.
if (last && last.message === message) throw new BadRequestException('Ce message est identique à la campagne précédente.');
const [cards, appleDevices] = await Promise.all([
this.prisma.loyaltyCard.count({ where: { storeId } }),
this.prisma.appleDevice.count({ where: { registrations: { some: { card: { storeId } } } } }),
]);
const campaign = await this.prisma.campaign.create({
data: { storeId, message, sentByName, cards, appleDevices },
});
this.cardUpdates.broadcast(storeId, campaign, store.name);
return campaign;
}
}

View file

@ -5,7 +5,7 @@ import { join } from 'path';
import { Jimp } from 'jimp';
import { PKPass } from 'passkit-generator';
import { UPLOADS_DIR } from '../card-design/card-design.service';
import { CardWithContext, nextRewardText, rewardsText, unitLabel } from './wallet.types';
import { CardWithContext, latestNews, nextRewardText, rewardsText, unitLabel } from './wallet.types';
type Certificates = { wwdr: Buffer; signerCert: Buffer; signerKey: Buffer; signerKeyPassphrase?: string };
@ -68,6 +68,8 @@ export class ApplePassService {
auxiliaryFields: [{ key: 'next-reward', label: 'PROCHAINE RÉCOMPENSE', value: nextReward, changeMessage: '%@' }],
}),
backFields: [
// 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: 'rewards', label: 'Récompenses', value: rewardsText(card) },
{
key: 'store',

View file

@ -54,6 +54,21 @@ export class CardUpdatesService {
});
}
/** Campagne : la carte Apple affiche le nouveau message au dos (notification), Google reçoit un message de classe. */
broadcast(storeId: string, campaign: { id: string; message: string }, storeName: string) {
void this.run(`campagne ${campaign.id}`, async () => {
await this.prisma.loyaltyCard.updateMany({ where: { storeId }, data: { passUpdatedAt: new Date() } });
const devices = await this.prisma.appleDevice.findMany({
where: { registrations: { some: { card: { storeId } } } },
select: { pushToken: true },
});
await Promise.all([
this.pushApple(devices.map((d) => d.pushToken)),
this.google.addClassMessage(storeId, campaign.id, storeName, campaign.message),
]);
});
}
private async pushApple(tokens: string[]) {
const gone = await this.apns.push([...new Set(tokens)]);
if (gone.length) await this.prisma.appleDevice.deleteMany({ where: { pushToken: { in: gone } } });

View file

@ -78,6 +78,17 @@ export class GoogleWalletService {
await this.call('PATCH', `/loyaltyClass/${encodeURIComponent(c.id)}`, c);
}
/**
* Message de campagne sur toutes les cartes Google du magasin, avec notification.
* Google limite les notifications à 3 par carte et par 24 h : nos campagnes sont limitées à 1 par jour.
*/
async addClassMessage(storeId: string, campaignId: string, header: string, body: string) {
if (!this.enabled) return;
await this.call('POST', `/loyaltyClass/${encodeURIComponent(this.classId(storeId))}/addMessage`, {
message: { id: `campaign_${campaignId}`, header, body, messageType: 'TEXT_AND_NOTIFY' },
});
}
private buildClass(store: StoreForClass) {
const design = store.cardDesign!;
const publicUrl: string = this.config.get('publicUrl')!;

View file

@ -7,6 +7,7 @@ export const CARD_WITH_CONTEXT = {
include: {
cardDesign: { include: { rewards: { where: { active: true }, orderBy: { cost: 'asc' } } } },
subscription: { select: { plan: true, status: true } },
campaigns: { orderBy: { createdAt: 'desc' }, take: 1, select: { message: true } },
},
},
} satisfies Prisma.LoyaltyCardInclude;
@ -40,3 +41,8 @@ export function rewardsText(card: CardWithContext) {
const rewards = card.store.cardDesign?.rewards ?? [];
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) {
return card.store.campaigns[0]?.message ?? null;
}

View file

@ -48,6 +48,7 @@ function Navigator() {
<Stack.Screen name="client/[serial]/rewards" options={{ title: 'Récompenses' }} />
<Stack.Screen name="done" options={{ headerShown: false, gestureEnabled: false }} />
<Stack.Screen name="history" options={{ title: 'Historique' }} />
<Stack.Screen name="campaigns" options={{ title: 'Campagnes' }} />
</Stack.Protected>
</Stack>
);

121
pro/app/campaigns.tsx Normal file
View file

@ -0,0 +1,121 @@
import { useCallback, useState } from 'react';
import { Alert, ScrollView, 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 } from '../src/ui';
import { font, useColors } from '../src/theme';
interface Overview {
allowed: boolean;
audience: { cards: number; appleDevices: number };
nextAllowedAt: string | null;
items: { id: string; message: string; sentByName: string; cards: number; createdAt: string }[];
}
const MAX = 160;
const when = (d: string) =>
new Date(d).toLocaleString('fr-FR', { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' });
/** Campagnes (gérants, formule Pro) : un message envoyé en notification à toutes les cartes du magasin. */
export default function Campaigns() {
const c = useColors();
const store = useStore();
const [data, setData] = useState<Overview | null>(null);
const [message, setMessage] = useState('');
const [error, setError] = useState<string | null>(null);
const [sent, setSent] = useState(false);
const [busy, setBusy] = useState(false);
const load = useCallback(async () => {
try {
setData(await api.get<Overview>('/api/staff/campaigns'));
} catch (e) {
setError(describe(e).detail);
}
}, []);
useFocusEffect(
useCallback(() => {
load();
}, [load]),
);
const text = message.trim();
const blocked = !data || !data.allowed || !!data.nextAllowedAt;
const send = () =>
Alert.alert('Envoyer la campagne ?', `${data!.audience.cards} cartes de ${store.name} recevront :\n\n« ${text} »`, [
{ text: 'Annuler', style: 'cancel' },
{
text: 'Envoyer',
onPress: async () => {
setBusy(true);
setError(null);
try {
await api.post('/api/staff/campaigns', { message: text });
setMessage('');
setSent(true);
await load();
} catch (e) {
setError(describe(e).detail);
} finally {
setBusy(false);
}
},
},
]);
return (
<ScrollView contentContainerStyle={{ padding: 20, gap: 16 }} keyboardShouldPersistTaps="handled">
{error && <Banner tone="error">{error}</Banner>}
{sent && <Banner tone="ok">Campagne envoyée. Les cartes de vos clients se mettent à jour dans les minutes qui suivent.</Banner>}
{data && !data.allowed && <Banner tone="warn">Les campagnes sont incluses dans la formule Pro. Contactez MonEspacePro pour changer de formule.</Banner>}
<T v="muted">
Votre message apparaît en notification sur le téléphone de vos clients et reste visible sur leur carte.
{data ? ` ${data.audience.cards} cartes au total.` : ''}
</T>
<TextInput
value={message}
onChangeText={setMessage}
editable={!blocked && !busy}
multiline
maxLength={MAX}
placeholder="Ex. : -20 % sur les viennoiseries ce samedi !"
placeholderTextColor={c.text3}
accessibilityLabel="Message de la campagne"
style={{
minHeight: 110,
borderWidth: 1,
borderColor: c.border,
borderRadius: 14,
padding: 14,
backgroundColor: c.surface,
color: c.text,
fontFamily: font.regular,
fontSize: 17,
textAlignVertical: 'top',
opacity: blocked ? 0.6 : 1,
}}
/>
<T v="muted" style={{ fontSize: 13 }}>{text.length} / {MAX} · 1 campagne par jour maximum</T>
{data?.nextAllowedAt && <Banner tone="warn">Prochain envoi possible le {when(data.nextAllowedAt)}.</Banner>}
<Button label="Envoyer la campagne" onPress={send} disabled={blocked || text.length < 5} loading={busy} />
{!!data?.items.length && (
<View style={{ gap: 10, marginTop: 8 }}>
<T v="h2">Campagnes envoyées</T>
{data.items.map((i) => (
<Card key={i.id} style={{ padding: 14, gap: 4 }}>
<T>{i.message}</T>
<T v="muted" style={{ fontSize: 13 }}>
{when(i.createdAt)} · {i.sentByName} · {i.cards} cartes
</T>
</Card>
))}
</View>
)}
</ScrollView>
);
}

View file

@ -112,6 +112,7 @@ export default function Home() {
</View>
<View style={{ flex: 1 }} />
{isManager && <Button label="Envoyer une campagne" variant="secondary" onPress={() => router.push('/campaigns')} />}
<Button label="Historique des opérations" variant="secondary" onPress={() => router.push('/history')} />
</ScrollView>
</SafeAreaView>

View file

@ -24,7 +24,7 @@ const MARKETING = {
items: [
{ label: 'Employés illimités' },
{ label: 'Sans la mention « Propulsé par MonEspacePro »' },
{ label: 'Notifications et campagnes sur l’écran du téléphone', soon: true },
{ label: 'Notifications et campagnes sur l’écran du téléphone' },
{ label: 'Relance automatique des clients inactifs', soon: true },
{ label: 'Offre d’anniversaire', soon: true },
{ label: 'Collecte d’avis Google', soon: true },

View file

@ -117,7 +117,7 @@
<ul class="fl" style="margin-top:12px">
<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 class="soon"><svg class="ico"><use href="#i-check"/></svg><span>Notifications et campagnes sur l’écran du téléphone <span class="soon-tag">Bientôt</span></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 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>