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:
parent
8eb1ce3821
commit
a9baf09e0d
16 changed files with 526 additions and 88 deletions
122
admin/src/pages/CampaignsTab.tsx
Normal file
122
admin/src/pages/CampaignsTab.tsx
Normal 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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
@ -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>
|
||||
</>
|
||||
|
|
|
|||
13
backend/prisma/manual-migrations/2026-10-07-campagnes.sql
Normal file
13
backend/prisma/manual-migrations/2026-10-07-campagnes.sql
Normal 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;
|
||||
|
|
@ -57,6 +57,7 @@ model Store {
|
|||
transactions Transaction[]
|
||||
subscription Subscription?
|
||||
invoices Invoice[]
|
||||
campaigns Campaign[]
|
||||
}
|
||||
|
||||
enum PointsMode {
|
||||
|
|
@ -260,3 +261,19 @@ model Invoice {
|
|||
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])
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 }],
|
||||
|
|
|
|||
56
backend/src/campaigns/campaigns.controller.ts
Normal file
56
backend/src/campaigns/campaigns.controller.ts
Normal 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 {}
|
||||
68
backend/src/campaigns/campaigns.service.ts
Normal file
68
backend/src/campaigns/campaigns.service.ts
Normal 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;
|
||||
}
|
||||
}
|
||||
|
|
@ -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',
|
||||
|
|
|
|||
|
|
@ -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 } } });
|
||||
|
|
|
|||
|
|
@ -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')!;
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
121
pro/app/campaigns.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
|
|
@ -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>
|
||||
|
|
|
|||
|
|
@ -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 },
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
|
|
|
|||
Loading…
Reference in a new issue