Collecte d'avis Google (formule Pro) + correctif heure de Paris

- Lien de la fiche Google validé (https, domaines Google), demande après 1/2/3/5 passages
- Notification unique 2 h après le passage (10 h–20 h), lien au dos de la carte Apple,
  dans les liens Google Wallet et sur la page de la carte ; clics comptés via redirection
- Admin : carte Avis Google ; app Pro : écran Fidélisation regroupant les 4 outils
- Correctif : l'heure de Paris (« 23 h ») était lue comme NaN, la relance des inactifs
  pouvait partir la nuit
- Migration manuelle 2026-10-07-avis-google.sql

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Tony AVERTY 2026-10-07 10:37:41 +02:00
parent 166f7888cd
commit 0826d059ff
18 changed files with 555 additions and 27 deletions

View file

@ -2,6 +2,7 @@ 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'; import { BirthdayCard } from './BirthdayCard';
import { ReviewsCard } from './ReviewsCard';
interface Campaign { interface Campaign {
id: string; id: string;
@ -92,6 +93,7 @@ export function CampaignsTab({ storeId, storeName }: { storeId: string; storeNam
<RemindersCard storeId={storeId} /> <RemindersCard storeId={storeId} />
<BirthdayCard storeId={storeId} /> <BirthdayCard storeId={storeId} />
<ReviewsCard storeId={storeId} />
<section className="card"> <section className="card">
<h2>Historique</h2> <h2>Historique</h2>

View file

@ -0,0 +1,100 @@
import { useCallback, useEffect, useState } from 'react';
import { api } from '../api';
interface Reviews {
allowed: boolean;
settings: { enabled: boolean; url: string | null; afterVisits: number; message: string | null };
defaultMessage: string;
visitChoices: number[];
stats: { asked: number; clicked: number };
}
/** Collecte d'avis Google (formule Pro). */
export function ReviewsCard({ storeId }: { storeId: string }) {
const [data, setData] = useState<Reviews | null>(null);
const [enabled, setEnabled] = useState(false);
const [url, setUrl] = useState('');
const [afterVisits, setAfterVisits] = useState(2);
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: Reviews) => {
setData(d);
setEnabled(d.settings.enabled);
setUrl(d.settings.url ?? '');
setAfterVisits(d.settings.afterVisits);
setMessage(d.settings.message ?? '');
};
const load = useCallback(() => {
api.get<Reviews>(`/api/admin/stores/${storeId}/reviews`).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<Reviews>(`/api/admin/stores/${storeId}/reviews`, { enabled, url: url.trim() || null, afterVisits, message: message.trim() || null }));
setNotice("Collecte d'avis enregistrée.");
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(false);
}
}
return (
<section className="card" style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
<div>
<h2>Avis Google</h2>
<p className="muted" style={{ margin: 0 }}>
Après le nombre de passages choisi, le client reçoit une seule fois une notification qui l'invite à laisser un avis (2 h après son passage).
Le lien est aussi au dos de sa carte et sur sa page. Règle Google : aucune récompense en échange d'un avis.
</p>
</div>
{error && <div className="alert error" role="alert">{error}</div>}
{notice && <div className="alert ok" role="status">{notice}</div>}
{!data.allowed && <div className="alert warn">La collecte d'avis 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)} />
Collecte d'avis activée
</label>
<div>
<label htmlFor="review-url" style={{ fontWeight: 600 }}>Lien de la fiche Google</label>
<input id="review-url" className="input" type="url" placeholder="https://g.page/r/…/review" value={url} onChange={(e) => setUrl(e.target.value)} />
<span className="muted" style={{ fontSize: 14 }}>
Dans Google Business Profile : « Demander des avis » → copier le lien.
</span>
</div>
<div role="group" aria-label="Nombre de passages" className="row" style={{ gap: 8, alignItems: 'center' }}>
<span>Demander après</span>
{data.visitChoices.map((n) => (
<button key={n} type="button" className="chip" aria-pressed={afterVisits === n} onClick={() => setAfterVisits(n)}>
{n} passage{n > 1 ? 's' : ''}
</button>
))}
</div>
<div>
<label htmlFor="review-msg" style={{ fontWeight: 600 }}>Message</label>
<textarea id="review-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.</span>
</div>
<div className="row between">
<span className="muted" style={{ fontSize: 14 }}>
{data.stats.asked} demande(s) envoyée(s) · {data.stats.clicked} clic(s) vers Google
</span>
<button className="btn" disabled={busy} onClick={save}>{busy ? 'Enregistrement…' : 'Enregistrer'}</button>
</div>
</section>
);
}

View file

@ -0,0 +1,9 @@
-- Collecte d'avis Google (formule Pro).
ALTER TABLE `Store`
ADD COLUMN `reviewEnabled` BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN `googleReviewUrl` VARCHAR(500) NULL,
ADD COLUMN `reviewAfterVisits` INTEGER NOT NULL DEFAULT 2,
ADD COLUMN `reviewMessage` VARCHAR(160) NULL;
ALTER TABLE `LoyaltyCard`
ADD COLUMN `reviewAskedAt` DATETIME(3) NULL,
ADD COLUMN `reviewClickedAt` DATETIME(3) NULL;

View file

@ -61,6 +61,15 @@ model Store {
/// Texte du message ; {prenom} et {cadeau} sont remplacés. Vide = texte par défaut. /// Texte du message ; {prenom} et {cadeau} sont remplacés. Vide = texte par défaut.
birthdayMessage String? @db.VarChar(160) birthdayMessage String? @db.VarChar(160)
// Collecte d'avis Google (formule Pro)
reviewEnabled Boolean @default(false)
/// Lien « Demander des avis » de la fiche Google du magasin.
googleReviewUrl String? @db.VarChar(500)
/// Demande envoyée après ce nombre de passages (crédits).
reviewAfterVisits Int @default(2)
/// Texte de la demande ; {prenom} est remplacé. Vide = texte par défaut.
reviewMessage String? @db.VarChar(160)
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
@ -158,6 +167,9 @@ model LoyaltyCard {
reminderSentAt DateTime? reminderSentAt DateTime?
/// Dernier cadeau d'anniversaire (un par an). /// Dernier cadeau d'anniversaire (un par an).
birthdayGiftAt DateTime? birthdayGiftAt DateTime?
/// Demande d'avis Google envoyée (une seule fois par client) et clic sur le lien.
reviewAskedAt DateTime?
reviewClickedAt DateTime?
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
transactions Transaction[] transactions Transaction[]

View file

@ -16,6 +16,7 @@ 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 { BirthdaysModule } from './birthdays/birthdays.controller';
import { ReviewsModule } from './reviews/reviews.controller';
import { HealthController } from './health.controller'; import { HealthController } from './health.controller';
@Module({ @Module({
@ -35,6 +36,7 @@ import { HealthController } from './health.controller';
CampaignsModule, CampaignsModule,
RemindersModule, RemindersModule,
BirthdaysModule, BirthdaysModule,
ReviewsModule,
], ],
controllers: [HealthController], controllers: [HealthController],
providers: [{ provide: APP_GUARD, useClass: ThrottlerGuard }], providers: [{ provide: APP_GUARD, useClass: ThrottlerGuard }],

View file

@ -1,6 +1,6 @@
import type { CardDesign, Plan, Reward, Store, SubscriptionStatus } from '@prisma/client'; import type { CardDesign, Plan, Reward, Store, SubscriptionStatus } from '@prisma/client';
import { hasFeature } from '../billing/plans'; import { hasFeature } from '../billing/plans';
import { nextRewardText, type CardWithContext } from '../wallet/wallet.types'; import { nextRewardText, reviewOffered, type CardWithContext } from '../wallet/wallet.types';
/** Pages publiques (clients finaux), rendues côté serveur aux couleurs du magasin. */ /** Pages publiques (clients finaux), rendues côté serveur aux couleurs du magasin. */
@ -364,6 +364,7 @@ ${askBirthday ? `<form id="bform" class="notice" style="display:flex;flex-direct
: '' : ''
} }
</div> </div>
${reviewOffered(card.store) && !opts.isNew ? `<a class="btn ghost" href="/api/public/cards/${e(card.serial)}/review${e(q)}" rel="noopener">Laisser un avis Google</a>` : ''}
${opts.isNew ? '<p class="small">Un e-mail de confirmation vous a été envoyé avec le lien de votre carte.</p>' : ''} ${opts.isNew ? '<p class="small">Un e-mail de confirmation vous a été envoyé avec le lien de votre carte.</p>' : ''}
<details style="margin-top:12px"> <details style="margin-top:12px">
<summary class="small" style="cursor:pointer">Supprimer ma carte</summary> <summary class="small" style="cursor:pointer">Supprimer ma carte</summary>

View file

@ -1,5 +1,6 @@
import { Injectable, Logger, NotFoundException, OnApplicationBootstrap, OnApplicationShutdown } from '@nestjs/common'; import { Injectable, Logger, NotFoundException, OnApplicationBootstrap, OnApplicationShutdown } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service'; import { PrismaService } from '../prisma/prisma.service';
import { parisDate } from '../birthdays/birthdays.service';
import { EntitlementsService } from '../billing/entitlements.service'; import { EntitlementsService } from '../billing/entitlements.service';
import { CardUpdatesService } from '../wallet/card-updates.service'; import { CardUpdatesService } from '../wallet/card-updates.service';
import { CARD_WITH_CONTEXT, DEFAULT_REMINDER, reminderText } from '../wallet/wallet.types'; import { CARD_WITH_CONTEXT, DEFAULT_REMINDER, reminderText } from '../wallet/wallet.types';
@ -102,7 +103,7 @@ export class RemindersService implements OnApplicationBootstrap, OnApplicationSh
/** Passage horaire. */ /** Passage horaire. */
async tick(now = new Date()) { async tick(now = new Date()) {
if (this.running) return; if (this.running) return;
const hour = Number(new Intl.DateTimeFormat('fr-FR', { hour: 'numeric', hour12: false, timeZone: 'Europe/Paris' }).format(now)); const { hour } = parisDate(now);
if (hour < SEND_HOURS.from || hour >= SEND_HOURS.to) return; if (hour < SEND_HOURS.from || hour >= SEND_HOURS.to) return;
this.running = true; this.running = true;
try { try {

View file

@ -0,0 +1,78 @@
import { Body, Controller, Get, Module, Param, Put, Query, Res, UseGuards } from '@nestjs/common';
import { Throttle } from '@nestjs/throttler';
import { IsBoolean, IsIn, IsOptional, IsString, MaxLength } from 'class-validator';
import type { Response } from 'express';
import { JwtPayload } from '../common/auth.types';
import { AdminGuard, CurrentUser, JwtAuthGuard, StaffGuard, StaffRoles } from '../common/guards';
import { ReviewsService, VISIT_CHOICES } from './reviews.service';
class ReviewSettingsDto {
@IsBoolean()
enabled!: boolean;
@IsOptional() @IsString() @MaxLength(500)
url?: string | null;
@IsIn(VISIT_CHOICES)
afterVisits!: number;
@IsOptional() @IsString() @MaxLength(160)
message?: string | null;
}
const settings = (dto: ReviewSettingsDto) => ({ enabled: dto.enabled, url: dto.url ?? null, afterVisits: dto.afterVisits, message: dto.message ?? null });
@Controller('admin/stores/:id/reviews')
@UseGuards(JwtAuthGuard, AdminGuard)
export class AdminReviewsController {
constructor(private reviews: ReviewsService) {}
@Get()
get(@Param('id') id: string) {
return this.reviews.overview(id);
}
@Put()
update(@Param('id') id: string, @Body() dto: ReviewSettingsDto) {
return this.reviews.update(id, settings(dto));
}
}
/** App Pro : réservé aux gérants. */
@Controller('staff/reviews')
@UseGuards(JwtAuthGuard, StaffGuard)
@StaffRoles('MANAGER')
export class StaffReviewsController {
constructor(private reviews: ReviewsService) {}
@Get()
get(@CurrentUser() user: JwtPayload) {
if (user.kind !== 'staff') throw new Error('StaffGuard manquant');
return this.reviews.overview(user.storeId);
}
@Put()
update(@CurrentUser() user: JwtPayload, @Body() dto: ReviewSettingsDto) {
if (user.kind !== 'staff') throw new Error('StaffGuard manquant');
return this.reviews.update(user.storeId, settings(dto));
}
}
/** Lien au dos de la carte : compte le clic puis redirige vers la fiche Google. */
@Controller('public/cards/:serial/review')
export class PublicReviewController {
constructor(private reviews: ReviewsService) {}
@Get()
@Throttle({ default: { limit: 20, ttl: 60_000 } })
async go(@Param('serial') serial: string, @Query('k') key: string | undefined, @Res() res: Response) {
res.setHeader('Referrer-Policy', 'no-referrer');
res.redirect(302, await this.reviews.click(serial, key));
}
}
@Module({
controllers: [AdminReviewsController, StaffReviewsController, PublicReviewController],
providers: [ReviewsService],
})
export class ReviewsModule {}

View file

@ -0,0 +1,166 @@
import { BadRequestException, Injectable, Logger, NotFoundException, OnApplicationBootstrap, OnApplicationShutdown } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { parisDate } from '../birthdays/birthdays.service';
import { EntitlementsService } from '../billing/entitlements.service';
import { CardUpdatesService } from '../wallet/card-updates.service';
import { CARD_WITH_CONTEXT, DEFAULT_REVIEW, reviewText } from '../wallet/wallet.types';
/** Envois entre 10 h et 20 h (heure de Paris). */
const SEND_HOURS = { from: 10, to: 20 };
/** La demande part 2 h après le passage (le client est rentré), et jamais plus de 3 jours après. */
const DELAY_MS = 2 * 3600_000;
const MAX_AGE_MS = 3 * 24 * 3600_000;
export const VISIT_CHOICES = [1, 2, 3, 5];
/** Liens Google acceptés : « Demander des avis » de la fiche d'établissement, ou lien Maps. */
const GOOGLE_HOSTS = ['g.page', 'search.google.com', 'www.google.com', 'google.com', 'maps.app.goo.gl', 'goo.gl', 'www.google.fr', 'google.fr', 'maps.google.com'];
export function normalizeReviewUrl(raw: string | null | undefined) {
const value = raw?.trim();
if (!value) return null;
let url: URL;
try {
url = new URL(value);
} catch {
throw new BadRequestException('Lien Google invalide.');
}
if (url.protocol !== 'https:' || !GOOGLE_HOSTS.includes(url.hostname)) {
throw new BadRequestException('Collez le lien « Demander des avis » de votre fiche Google (il commence par https://g.page/ ou https://search.google.com/).');
}
return url.toString();
}
export interface ReviewSettings {
enabled: boolean;
url: string | null;
afterVisits: number;
message: string | null;
}
/**
* Collecte d'avis Google : après N passages, le client reçoit (une seule fois) une
* notification qui l'invite à laisser un avis ; le lien est au dos de sa carte.
* Conforme aux règles Google : pas de récompense contre un avis, pas de tri des clients.
*/
@Injectable()
export class ReviewsService implements OnApplicationBootstrap, OnApplicationShutdown {
private readonly logger = new Logger(ReviewsService.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(), 120_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 [allowed, asked, clicked] = await Promise.all([
this.entitlements.can(storeId, 'googleReview'),
this.prisma.loyaltyCard.count({ where: { storeId, reviewAskedAt: { not: null } } }),
this.prisma.loyaltyCard.count({ where: { storeId, reviewClickedAt: { not: null } } }),
]);
return {
allowed,
settings: { enabled: store.reviewEnabled, url: store.googleReviewUrl, afterVisits: store.reviewAfterVisits, message: store.reviewMessage } as ReviewSettings,
defaultMessage: DEFAULT_REVIEW,
visitChoices: VISIT_CHOICES,
stats: { asked, clicked },
};
}
async update(storeId: string, settings: ReviewSettings) {
const url = normalizeReviewUrl(settings.url);
if (settings.enabled) {
await this.entitlements.require(storeId, 'googleReview');
if (!url) throw new BadRequestException('Renseignez le lien de votre fiche Google pour activer la collecte d’avis.');
}
await this.prisma.store.update({
where: { id: storeId },
data: {
reviewEnabled: settings.enabled,
googleReviewUrl: url,
reviewAfterVisits: settings.afterVisits,
reviewMessage: settings.message?.replace(/\s+/g, ' ').trim() || null,
},
});
// Le lien apparaît ou disparaît au dos des cartes.
this.cardUpdates.notifyStore(storeId);
return this.overview(storeId);
}
/** Clic du client : on le note, puis direction la fiche Google. */
async click(serial: string, key: string | undefined) {
const card = await this.prisma.loyaltyCard.findUnique({ where: { serial }, include: { store: true } });
if (!card || !key || card.accessKey !== key || !card.store.googleReviewUrl) throw new NotFoundException();
if (!card.reviewClickedAt) await this.prisma.loyaltyCard.update({ where: { id: card.id }, data: { reviewClickedAt: new Date() } });
return card.store.googleReviewUrl;
}
/** Passage horaire. */
async tick(now = new Date()) {
if (this.running) return;
const { hour } = parisDate(now);
if (hour < SEND_HOURS.from || hour >= SEND_HOURS.to) return;
this.running = true;
try {
const stores = await this.prisma.store.findMany({
where: { reviewEnabled: true, googleReviewUrl: { not: null }, status: 'ACTIVE', billingSuspended: false },
select: { id: true, name: true, reviewAfterVisits: true },
});
for (const store of stores) {
if (!(await this.entitlements.can(store.id, 'googleReview'))) continue;
const sent = await this.runStore(store, now);
if (sent) this.logger.log(`Avis Google : ${sent} demande(s) pour ${store.name}`);
}
} catch (e) {
this.logger.error(`Collecte d'avis : ${(e as Error).message}`);
} finally {
this.running = false;
}
}
private async runStore(store: { id: string; name: string; reviewAfterVisits: number }, now: Date) {
const recent = await this.prisma.loyaltyCard.findMany({
where: {
storeId: store.id,
reviewAskedAt: null,
lastCreditAt: { lte: new Date(now.getTime() - DELAY_MS), gte: new Date(now.getTime() - MAX_AGE_MS) },
},
select: { id: true },
});
if (!recent.length) return 0;
const visits = await this.prisma.transaction.groupBy({
by: ['cardId'],
where: { cardId: { in: recent.map((c) => c.id) }, type: 'CREDIT' },
_count: { _all: true },
});
let sent = 0;
for (const v of visits.filter((x) => x._count._all >= store.reviewAfterVisits)) {
const { count } = await this.prisma.loyaltyCard.updateMany({
where: { id: v.cardId, reviewAskedAt: null },
data: { reviewAskedAt: now, passUpdatedAt: now },
});
if (!count) continue;
const card = await this.prisma.loyaltyCard.findUniqueOrThrow({ where: { id: v.cardId }, include: CARD_WITH_CONTEXT });
try {
await this.cardUpdates.remind(card.id, reviewText(card), store.name);
sent++;
} catch (e) {
this.logger.warn(`Avis carte ${card.serial} : ${(e as Error).message}`);
}
}
return sent;
}
}

View file

@ -5,7 +5,7 @@ import { join } from 'path';
import { Jimp } from 'jimp'; import { Jimp } from 'jimp';
import { PKPass } from 'passkit-generator'; import { PKPass } from 'passkit-generator';
import { UPLOADS_DIR } from '../card-design/card-design.service'; import { UPLOADS_DIR } from '../card-design/card-design.service';
import { CardWithContext, newsText, nextRewardText, rewardsText, unitLabel } from './wallet.types'; import { CardWithContext, newsText, nextRewardText, reviewLink, reviewOffered, rewardsText, unitLabel } from './wallet.types';
type Certificates = { wwdr: Buffer; signerCert: Buffer; signerKey: Buffer; signerKeyPassphrase?: string }; type Certificates = { wwdr: Buffer; signerCert: Buffer; signerKey: Buffer; signerKeyPassphrase?: string };
@ -81,6 +81,9 @@ export class ApplePassService {
label: 'Ma carte', label: 'Ma carte',
value: `${this.config.get('webUrl')}/carte/${card.serial}?k=${card.accessKey}`, value: `${this.config.get('webUrl')}/carte/${card.serial}?k=${card.accessKey}`,
}, },
...(reviewOffered(card.store)
? [{ key: 'review', label: 'Votre avis', value: reviewLink(this.config.get('webUrl')!, card), attributedValue: `<a href="${reviewLink(this.config.get('webUrl')!, card)}">Laisser un avis Google</a>` }]
: []),
{ key: 'powered', label: '', value: 'Propulsé par MonEspacePro' }, { key: 'powered', label: '', value: 'Propulsé par MonEspacePro' },
], ],
}, },

View file

@ -2,7 +2,7 @@ import { Injectable, Logger, ServiceUnavailableException } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'; import { ConfigService } from '@nestjs/config';
import { readFileSync } from 'fs'; import { readFileSync } from 'fs';
import { importPKCS8, SignJWT } from 'jose'; import { importPKCS8, SignJWT } from 'jose';
import { CardWithContext, nextRewardText, rewardsText, unitLabel } from './wallet.types'; import { CardWithContext, nextRewardText, reviewLink, reviewOffered, rewardsText, unitLabel } from './wallet.types';
type ServiceAccount = { client_email: string; private_key: string }; type ServiceAccount = { client_email: string; private_key: string };
type StoreForClass = CardWithContext['store']; type StoreForClass = CardWithContext['store'];
@ -67,6 +67,7 @@ export class GoogleWalletService {
await this.call('PATCH', `/loyaltyObject/${encodeURIComponent(o.id)}`, { await this.call('PATCH', `/loyaltyObject/${encodeURIComponent(o.id)}`, {
loyaltyPoints: o.loyaltyPoints, loyaltyPoints: o.loyaltyPoints,
textModulesData: o.textModulesData, textModulesData: o.textModulesData,
linksModuleData: o.linksModuleData,
accountName: o.accountName, accountName: o.accountName,
}); });
} }
@ -139,7 +140,10 @@ export class GoogleWalletService {
{ id: 'rewards', header: 'Toutes les récompenses', body: rewardsText(card) }, { id: 'rewards', header: 'Toutes les récompenses', body: rewardsText(card) },
], ],
linksModuleData: { linksModuleData: {
uris: [{ id: 'manage', uri: `${webUrl}/carte/${card.serial}?k=${card.accessKey}`, description: 'Ma carte' }], uris: [
{ id: 'manage', uri: `${webUrl}/carte/${card.serial}?k=${card.accessKey}`, description: 'Ma carte' },
...(reviewOffered(card.store) ? [{ id: 'review', uri: reviewLink(webUrl, card), description: 'Laisser un avis Google' }] : []),
],
}, },
}; };
} }

View file

@ -1,4 +1,5 @@
import { Prisma } from '@prisma/client'; import { Prisma } from '@prisma/client';
import { hasFeature } from '../billing/plans';
/** Tout ce qu'il faut pour dessiner une carte, chargé en une requête. */ /** Tout ce qu'il faut pour dessiner une carte, chargé en une requête. */
export const CARD_WITH_CONTEXT = { export const CARD_WITH_CONTEXT = {
@ -79,7 +80,29 @@ export function newsText(card: CardWithContext) {
[campaign?.createdAt, () => campaign!.message], [campaign?.createdAt, () => campaign!.message],
[card.reminderSentAt, () => reminderText(card)], [card.reminderSentAt, () => reminderText(card)],
[card.birthdayGiftAt, () => birthdayText(card)], [card.birthdayGiftAt, () => birthdayText(card)],
[card.reviewAskedAt, () => reviewText(card)],
]; ];
const latest = items.filter(([d]) => d).sort((a, b) => b[0]!.getTime() - a[0]!.getTime())[0]; const latest = items.filter(([d]) => d).sort((a, b) => b[0]!.getTime() - a[0]!.getTime())[0];
return latest ? latest[1]() : null; return latest ? latest[1]() : null;
} }
export const DEFAULT_REVIEW = 'Merci pour vos visites, {prenom} ! Votre avis compte beaucoup pour nous : laissez-nous un avis Google en une minute.';
/** Collecte d'avis active pour ce magasin (formule Pro + lien renseigné). */
export function reviewOffered(store: CardWithContext['store']) {
return (
store.reviewEnabled &&
!!store.googleReviewUrl &&
store.subscription?.status === 'ACTIVE' &&
hasFeature(store.subscription.plan, 'googleReview')
);
}
export function reviewText(card: CardWithContext) {
return (card.store.reviewMessage || DEFAULT_REVIEW).replaceAll('{prenom}', card.customer.firstName);
}
/** Lien suivi (compte les clics) qui redirige vers la fiche Google. */
export function reviewLink(webUrl: string, card: CardWithContext) {
return `${webUrl}/api/public/cards/${card.serial}/review?k=${card.accessKey}`;
}

View file

@ -51,6 +51,8 @@ function Navigator() {
<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.Screen name="birthday" options={{ title: "Offre d'anniversaire" }} />
<Stack.Screen name="reviews" options={{ title: 'Avis Google' }} />
<Stack.Screen name="loyalty" options={{ title: 'Fidélisation' }} />
</Stack.Protected> </Stack.Protected>
</Stack> </Stack>
); );

View file

@ -112,9 +112,7 @@ export default function Home() {
</View> </View>
<View style={{ flex: 1 }} /> <View style={{ flex: 1 }} />
{isManager && <Button label="Envoyer une campagne" variant="secondary" onPress={() => router.push('/campaigns')} />} {isManager && <Button label="Fidélisation" variant="secondary" onPress={() => router.push('/loyalty')} />}
{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>

16
pro/app/loyalty.tsx Normal file
View file

@ -0,0 +1,16 @@
import { ScrollView } from 'react-native';
import { router } from 'expo-router';
import { Button, T } from '../src/ui';
/** Outils de fidélisation (gérants, formule Pro). */
export default function Loyalty() {
return (
<ScrollView contentContainerStyle={{ padding: 20, gap: 12 }}>
<T v="muted">Faites revenir vos clients avec des messages sur leur carte Wallet.</T>
<Button label="Envoyer une campagne" variant="secondary" onPress={() => router.push('/campaigns')} />
<Button label="Relance des clients inactifs" variant="secondary" onPress={() => router.push('/reminders')} />
<Button label="Offre d'anniversaire" variant="secondary" onPress={() => router.push('/birthday')} />
<Button label="Avis Google" variant="secondary" onPress={() => router.push('/reviews')} />
</ScrollView>
);
}

111
pro/app/reviews.tsx Normal file
View file

@ -0,0 +1,111 @@
import { useCallback, useState } from 'react';
import { Pressable, ScrollView, Switch, TextInput, View } from 'react-native';
import { useFocusEffect } from 'expo-router';
import { api } from '../src/api';
import { describe } from '../src/errors';
import { Banner, Button, Card, T } from '../src/ui';
import { font, useColors } from '../src/theme';
interface Reviews {
allowed: boolean;
settings: { enabled: boolean; url: string | null; afterVisits: number; message: string | null };
defaultMessage: string;
visitChoices: number[];
stats: { asked: number; clicked: number };
}
/** Collecte d'avis Google (gérants, formule Pro). */
export default function ReviewsScreen() {
const c = useColors();
const [data, setData] = useState<Reviews | null>(null);
const [enabled, setEnabled] = useState(false);
const [url, setUrl] = useState('');
const [afterVisits, setAfterVisits] = useState(2);
const [message, setMessage] = useState('');
const [error, setError] = useState<string | null>(null);
const [saved, setSaved] = useState(false);
const [busy, setBusy] = useState(false);
const apply = (d: Reviews) => {
setData(d);
setEnabled(d.settings.enabled);
setUrl(d.settings.url ?? '');
setAfterVisits(d.settings.afterVisits);
setMessage(d.settings.message ?? '');
};
useFocusEffect(
useCallback(() => {
api.get<Reviews>('/api/staff/reviews').then(apply).catch((e) => setError(describe(e).detail));
}, []),
);
async function save() {
setBusy(true);
setError(null);
setSaved(false);
try {
apply(await api.put<Reviews>('/api/staff/reviews', { enabled, url: url.trim() || null, afterVisits, 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 input = { borderWidth: 1, borderColor: c.border, borderRadius: 14, padding: 14, backgroundColor: c.surface, color: c.text, fontFamily: font.regular, fontSize: 16 } as const;
return (
<ScrollView contentContainerStyle={{ padding: 20, gap: 16 }} keyboardShouldPersistTaps="handled">
{error && <Banner tone="error">{error}</Banner>}
{saved && <Banner tone="ok">Réglages enregistrés.</Banner>}
{!data.allowed && <Banner tone="warn">La collecte d'avis est incluse dans la formule Pro. Contactez MonEspacePro pour changer de formule.</Banner>}
<T v="muted">
Après quelques passages, vos clients reçoivent une seule fois une invitation à laisser un avis Google. Règle Google : aucune récompense en échange d'un avis.
</T>
<Card style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', padding: 16 }}>
<T v="label">Collecte d'avis</T>
<Switch value={enabled} onValueChange={setEnabled} disabled={!data.allowed && !enabled} accessibilityLabel="Collecte d'avis" />
</Card>
<T v="label">Lien de votre fiche Google</T>
<TextInput value={url} onChangeText={setUrl} autoCapitalize="none" autoCorrect={false} keyboardType="url" placeholder="https://g.page/r/…/review" placeholderTextColor={c.text3} accessibilityLabel="Lien de la fiche Google" style={input} />
<T v="muted" style={{ fontSize: 13 }}>Google Business Profile → « Demander des avis » → copier le lien.</T>
<T v="label">Demander après</T>
<View style={{ flexDirection: 'row', gap: 8, flexWrap: 'wrap' }}>
{data.visitChoices.map((n) => (
<Pressable
key={n}
accessibilityRole="button"
accessibilityState={{ selected: afterVisits === n }}
onPress={() => setAfterVisits(n)}
style={{ paddingVertical: 10, paddingHorizontal: 16, borderRadius: 999, borderWidth: 1, borderColor: afterVisits === n ? c.primary : c.border, backgroundColor: afterVisits === n ? c.primarySoft : c.surface }}
>
<T style={{ fontFamily: font.semibold, color: afterVisits === n ? c.primary : c.text }}>{n} passage{n > 1 ? 's' : ''}</T>
</Pressable>
))}
</View>
<T v="label">Message</T>
<TextInput value={message} onChangeText={setMessage} multiline maxLength={160} placeholder={data.defaultMessage} placeholderTextColor={c.text3} accessibilityLabel="Message de demande d'avis" style={{ ...input, minHeight: 90, textAlignVertical: 'top' }} />
<Button label="Enregistrer" onPress={save} loading={busy} />
<View style={{ flexDirection: 'row', gap: 12 }}>
{[
[data.stats.asked, 'demandes envoyées'],
[data.stats.clicked, 'clics vers Google'],
].map(([n, l]) => (
<Card key={String(l)} style={{ flex: 1, padding: 14, gap: 2 }}>
<T style={{ fontFamily: font.extrabold, fontSize: 22 }}>{n}</T>
<T v="muted" style={{ fontSize: 13 }}>{l}</T>
</Card>
))}
</View>
</ScrollView>
);
}

View file

@ -27,7 +27,7 @@ const MARKETING = {
{ 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' }, { label: 'Offre d’anniversaire' },
{ label: 'Collecte d’avis Google', soon: true }, { label: 'Collecte d’avis Google' },
{ label: 'Parrainage', soon: true }, { label: 'Parrainage', soon: true },
{ label: 'Statistiques avancées et export CSV', soon: true }, { label: 'Statistiques avancées et export CSV', soon: true },
], ],

View file

@ -120,7 +120,7 @@
<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><svg class="ico"><use href="#i-check"/></svg><span>Offre d’anniversaire</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><svg class="ico"><use href="#i-check"/></svg><span>Collecte d’avis Google</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>
</ul> </ul>