@@ -375,6 +400,16 @@ ${opts.isNew ? '
Un e-mail de confirmation vous a été envoyé
`;
const script = `
+${
+ opts.referralUrl
+ ? `document.getElementById('share').addEventListener('click',async function(){
+ var url=document.getElementById('reflink').value;
+ var text=${JSON.stringify(`Rejoignez le programme de fidélité ${d.programName} de ${store.name} :`)};
+ if(navigator.share){try{await navigator.share({title:${JSON.stringify(store.name)},text:text,url:url});return}catch(e){if(e.name==='AbortError')return}}
+ try{await navigator.clipboard.writeText(url);this.textContent='Lien copié !'}catch(e){document.getElementById('reflink').select()}
+});`
+ : ''
+}
${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;
diff --git a/backend/src/referrals/referrals.controller.ts b/backend/src/referrals/referrals.controller.ts
new file mode 100644
index 0000000..6359d27
--- /dev/null
+++ b/backend/src/referrals/referrals.controller.ts
@@ -0,0 +1,60 @@
+import { Body, Controller, Get, Module, Param, Put, UseGuards } from '@nestjs/common';
+import { IsBoolean, IsInt, Max, Min } from 'class-validator';
+import { JwtPayload } from '../common/auth.types';
+import { AdminGuard, CurrentUser, JwtAuthGuard, StaffGuard, StaffRoles } from '../common/guards';
+import { MAX_REFERRAL_POINTS, ReferralsCoreModule, ReferralsService } from './referrals.service';
+
+class ReferralSettingsDto {
+ @IsBoolean()
+ enabled!: boolean;
+
+ @IsInt() @Min(0) @Max(MAX_REFERRAL_POINTS)
+ points!: number;
+
+ @IsInt() @Min(0) @Max(MAX_REFERRAL_POINTS)
+ friendPoints!: number;
+}
+
+const settings = (dto: ReferralSettingsDto) => ({ enabled: dto.enabled, points: dto.points, friendPoints: dto.friendPoints });
+
+@Controller('admin/stores/:id/referral')
+@UseGuards(JwtAuthGuard, AdminGuard)
+export class AdminReferralsController {
+ constructor(private referrals: ReferralsService) {}
+
+ @Get()
+ get(@Param('id') id: string) {
+ return this.referrals.overview(id);
+ }
+
+ @Put()
+ update(@Param('id') id: string, @Body() dto: ReferralSettingsDto) {
+ return this.referrals.update(id, settings(dto));
+ }
+}
+
+/** App Pro : réservé aux gérants. */
+@Controller('staff/referral')
+@UseGuards(JwtAuthGuard, StaffGuard)
+@StaffRoles('MANAGER')
+export class StaffReferralsController {
+ constructor(private referrals: ReferralsService) {}
+
+ @Get()
+ get(@CurrentUser() user: JwtPayload) {
+ if (user.kind !== 'staff') throw new Error('StaffGuard manquant');
+ return this.referrals.overview(user.storeId);
+ }
+
+ @Put()
+ update(@CurrentUser() user: JwtPayload, @Body() dto: ReferralSettingsDto) {
+ if (user.kind !== 'staff') throw new Error('StaffGuard manquant');
+ return this.referrals.update(user.storeId, settings(dto));
+ }
+}
+
+@Module({
+ imports: [ReferralsCoreModule],
+ controllers: [AdminReferralsController, StaffReferralsController],
+})
+export class ReferralsModule {}
diff --git a/backend/src/referrals/referrals.service.ts b/backend/src/referrals/referrals.service.ts
new file mode 100644
index 0000000..fb33f6d
--- /dev/null
+++ b/backend/src/referrals/referrals.service.ts
@@ -0,0 +1,143 @@
+import { Global, Injectable, Logger, Module, NotFoundException } from '@nestjs/common';
+import { randomInt } from 'crypto';
+import { Prisma } from '@prisma/client';
+import { PrismaService } from '../prisma/prisma.service';
+import { EntitlementsService } from '../billing/entitlements.service';
+import { CardUpdatesService } from '../wallet/card-updates.service';
+import { referralOffered } from '../wallet/wallet.types';
+
+export const MAX_REFERRAL_POINTS = 100;
+/** Au-delà, le parrain n'est plus récompensé pendant 30 jours (le filleul l'est toujours). */
+export const MAX_REWARDS_PER_30_DAYS = 10;
+const ALPHABET = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789';
+
+export interface ReferralSettings {
+ enabled: boolean;
+ points: number;
+ friendPoints: number;
+}
+
+const plural = (n: number, stamp: boolean) => `${n} ${stamp ? 'tampon' : 'point'}${n > 1 ? 's' : ''}`;
+
+/**
+ * Parrainage : chaque client a un lien d'inscription personnel. Quand un ami
+ * s'inscrit par ce lien puis fait son premier passage en magasin, le parrain
+ * (et, si le magasin le souhaite, le filleul) reçoit des points.
+ * Récompense au premier passage réel : une inscription seule ne rapporte rien.
+ */
+@Injectable()
+export class ReferralsService {
+ private readonly logger = new Logger(ReferralsService.name);
+
+ constructor(
+ private prisma: PrismaService,
+ private entitlements: EntitlementsService,
+ private cardUpdates: CardUpdatesService,
+ ) {}
+
+ /** Code de parrainage de la carte, créé au besoin. */
+ async ensureCode(cardId: string): Promise {
+ const card = await this.prisma.loyaltyCard.findUniqueOrThrow({ where: { id: cardId }, select: { referralCode: true } });
+ if (card.referralCode) return card.referralCode;
+ for (let i = 0; i < 5; i++) {
+ const code = Array.from({ length: 8 }, () => ALPHABET[randomInt(ALPHABET.length)]).join('');
+ try {
+ const { count } = await this.prisma.loyaltyCard.updateMany({ where: { id: cardId, referralCode: null }, data: { referralCode: code } });
+ if (count) return code;
+ return (await this.prisma.loyaltyCard.findUniqueOrThrow({ where: { id: cardId }, select: { referralCode: true } })).referralCode!;
+ } catch (e) {
+ if (!(e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002')) throw e;
+ }
+ }
+ throw new Error('Code de parrainage impossible à générer');
+ }
+
+ /** Parrain d'une inscription (lien ?parrain=CODE) ; null si code inconnu ou parrainage inactif. */
+ async findReferrer(store: Parameters[0] & { id: string }, code: string | undefined | null) {
+ if (!code || !referralOffered(store)) return null;
+ const card = await this.prisma.loyaltyCard.findUnique({
+ where: { referralCode: code.toUpperCase().slice(0, 16) },
+ select: { id: true, storeId: true, customer: { select: { firstName: true } } },
+ });
+ return card && card.storeId === store.id ? { id: card.id, firstName: card.customer.firstName } : null;
+ }
+
+ async overview(storeId: string) {
+ const store = await this.prisma.store.findUnique({ where: { id: storeId } });
+ if (!store) throw new NotFoundException('Magasin introuvable');
+ const [allowed, referred, rewarded] = await Promise.all([
+ this.entitlements.can(storeId, 'referral'),
+ this.prisma.loyaltyCard.count({ where: { storeId, referredById: { not: null } } }),
+ this.prisma.loyaltyCard.count({ where: { storeId, referredById: { not: null }, referralRewardedAt: { not: null } } }),
+ ]);
+ return {
+ allowed,
+ settings: { enabled: store.referralEnabled, points: store.referralPoints, friendPoints: store.referralFriendPoints } as ReferralSettings,
+ maxPoints: MAX_REFERRAL_POINTS,
+ maxRewardsPer30Days: MAX_REWARDS_PER_30_DAYS,
+ stats: { referred, rewarded },
+ };
+ }
+
+ async update(storeId: string, settings: ReferralSettings) {
+ if (settings.enabled) await this.entitlements.require(storeId, 'referral');
+ await this.prisma.store.update({
+ where: { id: storeId },
+ data: { referralEnabled: settings.enabled, referralPoints: settings.points, referralFriendPoints: settings.friendPoints },
+ });
+ if (settings.enabled) {
+ // Chaque carte reçoit son code : le lien apparaît au dos des cartes existantes.
+ const cards = await this.prisma.loyaltyCard.findMany({ where: { storeId, referralCode: null }, select: { id: true } });
+ for (const c of cards) await this.ensureCode(c.id);
+ }
+ this.cardUpdates.notifyStore(storeId);
+ return this.overview(storeId);
+ }
+
+ /** Appelé après chaque crédit réussi au comptoir ; ne fait rien hors premier passage d'un filleul. */
+ onCredit(cardId: string) {
+ void this.rewardFirstVisit(cardId).catch((e) => this.logger.error(`Parrainage carte ${cardId} : ${(e as Error).message}`));
+ }
+
+ async rewardFirstVisit(cardId: string, now = new Date()) {
+ const friend = await this.prisma.loyaltyCard.findUnique({
+ where: { id: cardId },
+ include: { customer: true, store: { include: { cardDesign: true, subscription: { select: { plan: true, status: true } } } } },
+ });
+ if (!friend?.referredById || friend.referralRewardedAt) return;
+ const store = friend.store;
+ if (!referralOffered(store as never) || store.status !== 'ACTIVE' || store.billingSuspended) return;
+ const stamp = store.cardDesign?.pointsMode === 'STAMP';
+
+ const friendNews =
+ store.referralFriendPoints > 0 ? `Bienvenue, ${friend.customer.firstName} ! ${plural(store.referralFriendPoints, stamp)} offert${store.referralFriendPoints > 1 ? 's' : ''} grâce à votre parrainage.` : null;
+ // Conditionnel : un seul cadeau même si deux crédits arrivent en même temps.
+ const { count } = await this.prisma.loyaltyCard.updateMany({
+ where: { id: friend.id, referralRewardedAt: null },
+ data: {
+ referralRewardedAt: now,
+ ...(friendNews && { balance: { increment: store.referralFriendPoints }, personalNews: friendNews, personalNewsAt: now, passUpdatedAt: now }),
+ },
+ });
+ if (!count) return;
+ if (friendNews) await this.cardUpdates.remind(friend.id, friendNews, store.name);
+
+ const since = new Date(now.getTime() - 30 * 24 * 3600_000);
+ const recent = await this.prisma.loyaltyCard.count({
+ where: { referredById: friend.referredById, referralRewardedAt: { gte: since }, id: { not: friend.id } },
+ });
+ if (store.referralPoints <= 0 || recent >= MAX_REWARDS_PER_30_DAYS) return;
+ const referrer = await this.prisma.loyaltyCard.findUnique({ where: { id: friend.referredById }, include: { customer: true } });
+ if (!referrer || referrer.storeId !== store.id) return;
+ const news = `Merci ${referrer.customer.firstName} ! ${friend.customer.firstName} est venu(e) grâce à vous : ${plural(store.referralPoints, stamp)} offert${store.referralPoints > 1 ? 's' : ''}.`;
+ await this.prisma.loyaltyCard.update({
+ where: { id: referrer.id },
+ data: { balance: { increment: store.referralPoints }, personalNews: news, personalNewsAt: now, passUpdatedAt: now },
+ });
+ await this.cardUpdates.remind(referrer.id, news, store.name);
+ }
+}
+
+@Global()
+@Module({ providers: [ReferralsService], exports: [ReferralsService] })
+export class ReferralsCoreModule {}
diff --git a/backend/src/wallet/apple-pass.service.ts b/backend/src/wallet/apple-pass.service.ts
index 41c32d4..dc1e609 100644
--- a/backend/src/wallet/apple-pass.service.ts
+++ b/backend/src/wallet/apple-pass.service.ts
@@ -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, newsText, nextRewardText, reviewLink, reviewOffered, rewardsText, unitLabel } from './wallet.types';
+import { CardWithContext, newsText, nextRewardText, referralLink, referralOffered, reviewLink, reviewOffered, rewardsText, unitLabel } from './wallet.types';
type Certificates = { wwdr: Buffer; signerCert: Buffer; signerKey: Buffer; signerKeyPassphrase?: string };
@@ -84,6 +84,9 @@ export class ApplePassService {
...(reviewOffered(card.store)
? [{ key: 'review', label: 'Votre avis', value: reviewLink(this.config.get('webUrl')!, card), attributedValue: `Laisser un avis Google ` }]
: []),
+ ...(referralOffered(card.store) && referralLink(this.config.get('webUrl')!, card)
+ ? [{ key: 'referral', label: 'Parrainez vos proches', value: referralLink(this.config.get('webUrl')!, card)!, attributedValue: `Mon lien de parrainage ` }]
+ : []),
{ key: 'powered', label: '', value: 'Propulsé par MonEspacePro' },
],
},
diff --git a/backend/src/wallet/google-wallet.service.ts b/backend/src/wallet/google-wallet.service.ts
index 78dfcf3..3811150 100644
--- a/backend/src/wallet/google-wallet.service.ts
+++ b/backend/src/wallet/google-wallet.service.ts
@@ -2,7 +2,7 @@ import { Injectable, Logger, ServiceUnavailableException } from '@nestjs/common'
import { ConfigService } from '@nestjs/config';
import { readFileSync } from 'fs';
import { importPKCS8, SignJWT } from 'jose';
-import { CardWithContext, nextRewardText, reviewLink, reviewOffered, rewardsText, unitLabel } from './wallet.types';
+import { CardWithContext, nextRewardText, referralLink, referralOffered, reviewLink, reviewOffered, rewardsText, unitLabel } from './wallet.types';
type ServiceAccount = { client_email: string; private_key: string };
type StoreForClass = CardWithContext['store'];
@@ -142,6 +142,7 @@ export class GoogleWalletService {
linksModuleData: {
uris: [
{ id: 'manage', uri: `${webUrl}/carte/${card.serial}?k=${card.accessKey}`, description: 'Ma carte' },
+ ...(referralOffered(card.store) && referralLink(webUrl, card) ? [{ id: 'referral', uri: referralLink(webUrl, card)!, description: 'Parrainer un proche' }] : []),
...(reviewOffered(card.store) ? [{ id: 'review', uri: reviewLink(webUrl, card), description: 'Laisser un avis Google' }] : []),
],
},
diff --git a/backend/src/wallet/wallet.types.ts b/backend/src/wallet/wallet.types.ts
index d97e966..dce455f 100644
--- a/backend/src/wallet/wallet.types.ts
+++ b/backend/src/wallet/wallet.types.ts
@@ -81,6 +81,7 @@ export function newsText(card: CardWithContext) {
[card.reminderSentAt, () => reminderText(card)],
[card.birthdayGiftAt, () => birthdayText(card)],
[card.reviewAskedAt, () => reviewText(card)],
+ [card.personalNewsAt, () => card.personalNews ?? ''],
];
const latest = items.filter(([d]) => d).sort((a, b) => b[0]!.getTime() - a[0]!.getTime())[0];
return latest ? latest[1]() : null;
@@ -106,3 +107,13 @@ export function reviewText(card: CardWithContext) {
export function reviewLink(webUrl: string, card: CardWithContext) {
return `${webUrl}/api/public/cards/${card.serial}/review?k=${card.accessKey}`;
}
+
+/** Parrainage actif pour ce magasin (formule Pro). */
+export function referralOffered(store: CardWithContext['store']) {
+ return store.referralEnabled && store.subscription?.status === 'ACTIVE' && hasFeature(store.subscription.plan, 'referral');
+}
+
+/** Lien d'inscription à partager par le client (null tant que son code n'est pas créé). */
+export function referralLink(webUrl: string, card: CardWithContext) {
+ return card.referralCode ? `${webUrl}/c/${card.store.slug}?parrain=${card.referralCode}` : null;
+}
diff --git a/pro/app/_layout.tsx b/pro/app/_layout.tsx
index 438124a..88c0ad9 100644
--- a/pro/app/_layout.tsx
+++ b/pro/app/_layout.tsx
@@ -52,6 +52,7 @@ function Navigator() {
+
diff --git a/pro/app/loyalty.tsx b/pro/app/loyalty.tsx
index 664ee62..b841355 100644
--- a/pro/app/loyalty.tsx
+++ b/pro/app/loyalty.tsx
@@ -11,6 +11,7 @@ export default function Loyalty() {
router.push('/reminders')} />
router.push('/birthday')} />
router.push('/reviews')} />
+ router.push('/referral')} />
);
}
diff --git a/pro/app/referral.tsx b/pro/app/referral.tsx
new file mode 100644
index 0000000..4ccf872
--- /dev/null
+++ b/pro/app/referral.tsx
@@ -0,0 +1,113 @@
+import { useCallback, useState } from 'react';
+import { Pressable, ScrollView, Switch, 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 Referral {
+ allowed: boolean;
+ settings: { enabled: boolean; points: number; friendPoints: number };
+ maxPoints: number;
+ maxRewardsPer30Days: number;
+ stats: { referred: number; rewarded: number };
+}
+
+/** Parrainage (gérants, formule Pro). */
+export default function ReferralScreen() {
+ const c = useColors();
+ const store = useStore();
+ const [data, setData] = useState(null);
+ const [enabled, setEnabled] = useState(false);
+ const [points, setPoints] = useState(5);
+ const [friendPoints, setFriendPoints] = useState(0);
+ const [error, setError] = useState(null);
+ const [saved, setSaved] = useState(false);
+ const [busy, setBusy] = useState(false);
+
+ const apply = (d: Referral) => {
+ setData(d);
+ setEnabled(d.settings.enabled);
+ setPoints(d.settings.points);
+ setFriendPoints(d.settings.friendPoints);
+ };
+ useFocusEffect(
+ useCallback(() => {
+ api.get('/api/staff/referral').then(apply).catch((e) => setError(describe(e).detail));
+ }, []),
+ );
+
+ async function save() {
+ setBusy(true);
+ setError(null);
+ setSaved(false);
+ try {
+ apply(await api.put('/api/staff/referral', { enabled, points, friendPoints }));
+ setSaved(true);
+ } catch (e) {
+ setError(describe(e).detail);
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ if (!data) return {error ? {error} : Chargement… } ;
+
+ const btn = (label: string, d: number, value: number, set: (n: number) => void) => (
+ 0 ? 'plus' : 'moins'}`}
+ onPress={() => set(Math.max(0, Math.min(data.maxPoints, value + d)))}
+ style={{ width: 48, height: 48, borderRadius: 24, borderWidth: 1, borderColor: c.border, backgroundColor: c.surface, alignItems: 'center', justifyContent: 'center' }}
+ >
+ {d > 0 ? '+' : '−'}
+
+ );
+ const stepper = (label: string, value: number, set: (n: number) => void) => (
+
+ {label}
+
+ {btn(label, -1, value, set)}
+ {value}
+ {btn(label, 1, value, set)}
+ {value === 0 ? 'rien' : unit(store.design.pointsMode, value)}
+
+
+ );
+
+ return (
+
+ {error && {error} }
+ {saved && Réglages enregistrés. }
+ {!data.allowed && Le parrainage est inclus dans la formule Pro. Contactez MonEspacePro pour changer de formule. }
+
+
+ Chaque client a un lien à partager. Quand un ami s'inscrit avec ce lien et fait son premier passage, le parrain est récompensé. Au plus {data.maxRewardsPer30Days} récompenses par parrain sur 30 jours.
+
+
+
+ Parrainage
+
+
+
+ {stepper('Offerts au parrain', points, setPoints)}
+ {stepper('Offerts au filleul', friendPoints, setFriendPoints)}
+
+
+
+
+ {[
+ [data.stats.referred, 'filleuls inscrits'],
+ [data.stats.rewarded, 'venus en magasin'],
+ ].map(([n, l]) => (
+
+ {n}
+ {l}
+
+ ))}
+
+
+ );
+}
diff --git a/site-src/pricing.js b/site-src/pricing.js
index 03005ee..d2f634d 100644
--- a/site-src/pricing.js
+++ b/site-src/pricing.js
@@ -28,7 +28,7 @@ const MARKETING = {
{ label: 'Relance automatique des clients inactifs' },
{ label: 'Offre d’anniversaire' },
{ label: 'Collecte d’avis Google' },
- { label: 'Parrainage', soon: true },
+ { label: 'Parrainage' },
{ label: 'Statistiques avancées et export CSV', soon: true },
],
},
diff --git a/site/tarif/index.html b/site/tarif/index.html
index 2c73713..7a0806e 100644
--- a/site/tarif/index.html
+++ b/site/tarif/index.html
@@ -121,7 +121,7 @@
Relance automatique des clients inactifs
Offre d’anniversaire
Collecte d’avis Google
-Parrainage Bientôt
+Parrainage
Statistiques avancées et export CSV Bientôt