From b75e396bde3a1a3f2f60aeee799d2375167d1676 Mon Sep 17 00:00:00 2001 From: Tony AVERTY Date: Wed, 7 Oct 2026 10:42:55 +0200 Subject: [PATCH] Parrainage (formule Pro) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Code personnel par carte, lien d'inscription ?parrain=CODE (page de la carte, dos Apple, liens Google) - Bandeau « X vous invite » à l'inscription ; bouton Partager (partage natif ou copie) - Récompense au premier passage du filleul : parrain et filleul (réglables), une fois, au plus 10 récompenses par parrain sur 30 jours - Notifications via la rubrique Actualité (message personnel) - Admin : carte Parrainage ; app Pro : écran dans Fidélisation - Migration manuelle 2026-10-07-parrainage.sql Co-Authored-By: Claude Opus 5.5 --- admin/src/pages/CampaignsTab.tsx | 2 + admin/src/pages/ReferralCard.tsx | 87 +++++++++++ .../2026-10-07-parrainage.sql | 14 ++ backend/prisma/schema.prisma | 41 +++-- backend/src/app.module.ts | 4 + backend/src/counter/counter.service.ts | 4 + .../src/enrollment/enrollment.controller.ts | 18 ++- backend/src/enrollment/enrollment.service.ts | 17 ++- backend/src/enrollment/pages.ts | 41 ++++- backend/src/referrals/referrals.controller.ts | 60 ++++++++ backend/src/referrals/referrals.service.ts | 143 ++++++++++++++++++ backend/src/wallet/apple-pass.service.ts | 5 +- backend/src/wallet/google-wallet.service.ts | 3 +- backend/src/wallet/wallet.types.ts | 11 ++ pro/app/_layout.tsx | 1 + pro/app/loyalty.tsx | 1 + pro/app/referral.tsx | 113 ++++++++++++++ site-src/pricing.js | 2 +- site/tarif/index.html | 2 +- 19 files changed, 547 insertions(+), 22 deletions(-) create mode 100644 admin/src/pages/ReferralCard.tsx create mode 100644 backend/prisma/manual-migrations/2026-10-07-parrainage.sql create mode 100644 backend/src/referrals/referrals.controller.ts create mode 100644 backend/src/referrals/referrals.service.ts create mode 100644 pro/app/referral.tsx diff --git a/admin/src/pages/CampaignsTab.tsx b/admin/src/pages/CampaignsTab.tsx index 2632d8e..9438cbd 100644 --- a/admin/src/pages/CampaignsTab.tsx +++ b/admin/src/pages/CampaignsTab.tsx @@ -3,6 +3,7 @@ import { api } from '../api'; import { RemindersCard } from './RemindersCard'; import { BirthdayCard } from './BirthdayCard'; import { ReviewsCard } from './ReviewsCard'; +import { ReferralCard } from './ReferralCard'; interface Campaign { id: string; @@ -94,6 +95,7 @@ export function CampaignsTab({ storeId, storeName }: { storeId: string; storeNam +

Historique

diff --git a/admin/src/pages/ReferralCard.tsx b/admin/src/pages/ReferralCard.tsx new file mode 100644 index 0000000..62f17ce --- /dev/null +++ b/admin/src/pages/ReferralCard.tsx @@ -0,0 +1,87 @@ +import { useCallback, useEffect, useState } from 'react'; +import { api } from '../api'; + +interface Referral { + allowed: boolean; + settings: { enabled: boolean; points: number; friendPoints: number }; + maxPoints: number; + maxRewardsPer30Days: number; + stats: { referred: number; rewarded: number }; +} + +/** Parrainage (formule Pro). */ +export function ReferralCard({ storeId }: { storeId: string }) { + 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 [notice, setNotice] = useState(null); + const [busy, setBusy] = useState(false); + + const apply = (d: Referral) => { + setData(d); + setEnabled(d.settings.enabled); + setPoints(d.settings.points); + setFriendPoints(d.settings.friendPoints); + }; + const load = useCallback(() => { + api.get(`/api/admin/stores/${storeId}/referral`).then(apply).catch((e) => setError(e.message)); + }, [storeId]); + useEffect(load, [load]); + + if (!data) return error ?
{error}
: null; + const clamp = (v: string) => Math.max(0, Math.min(data.maxPoints, Math.floor(Number(v) || 0))); + + async function save() { + setBusy(true); + setError(null); + setNotice(null); + try { + apply(await api.put(`/api/admin/stores/${storeId}/referral`, { enabled, points, friendPoints })); + setNotice('Parrainage enregistré.'); + } catch (e) { + setError((e as Error).message); + } finally { + setBusy(false); + } + } + + return ( +
+
+

Parrainage

+

+ Chaque client a un lien personnel (sur la page et au dos de sa carte). Quand un ami s'inscrit avec ce lien puis fait son premier passage, + le parrain est récompensé, et l'ami aussi si vous le souhaitez. Au plus {data.maxRewardsPer30Days} récompenses par parrain sur 30 jours. +

+
+ {error &&
{error}
} + {notice &&
{notice}
} + {!data.allowed &&
Le parrainage est réservé aux formules Pro et Réseau (abonnement actif).
} + + + +
+
+ + setPoints(clamp(e.target.value))} /> +
+
+ + setFriendPoints(clamp(e.target.value))} /> +
+
+ +
+ + {data.stats.referred} filleul(s) inscrit(s) · {data.stats.rewarded} venu(s) en magasin + + +
+
+ ); +} diff --git a/backend/prisma/manual-migrations/2026-10-07-parrainage.sql b/backend/prisma/manual-migrations/2026-10-07-parrainage.sql new file mode 100644 index 0000000..cd633e2 --- /dev/null +++ b/backend/prisma/manual-migrations/2026-10-07-parrainage.sql @@ -0,0 +1,14 @@ +-- Parrainage (formule Pro). +ALTER TABLE `Store` + ADD COLUMN `referralEnabled` BOOLEAN NOT NULL DEFAULT false, + ADD COLUMN `referralPoints` INTEGER NOT NULL DEFAULT 5, + ADD COLUMN `referralFriendPoints` INTEGER NOT NULL DEFAULT 0; +ALTER TABLE `LoyaltyCard` + ADD COLUMN `referralCode` VARCHAR(16) NULL, + ADD COLUMN `referredById` VARCHAR(191) NULL, + ADD COLUMN `referralRewardedAt` DATETIME(3) NULL, + ADD COLUMN `personalNews` VARCHAR(200) NULL, + ADD COLUMN `personalNewsAt` DATETIME(3) NULL, + ADD UNIQUE INDEX `LoyaltyCard_referralCode_key`(`referralCode`), + ADD INDEX `LoyaltyCard_referredById_fkey`(`referredById`), + ADD CONSTRAINT `LoyaltyCard_referredById_fkey` FOREIGN KEY (`referredById`) REFERENCES `LoyaltyCard`(`id`) ON DELETE SET NULL ON UPDATE CASCADE; diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index c1e90cb..360347b 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -70,6 +70,13 @@ model Store { /// Texte de la demande ; {prenom} est remplacé. Vide = texte par défaut. reviewMessage String? @db.VarChar(160) + // Parrainage (formule Pro) + referralEnabled Boolean @default(false) + /// Offerts au parrain quand son filleul fait son premier passage. + referralPoints Int @default(5) + /// Offerts au filleul à son premier passage (0 = rien). + referralFriendPoints Int @default(0) + createdAt DateTime @default(now()) updatedAt DateTime @updatedAt @@ -148,20 +155,20 @@ model Customer { } model LoyaltyCard { - id String @id @default(cuid()) + id String @id @default(cuid()) storeId String - store Store @relation(fields: [storeId], references: [id], onDelete: Cascade) + store Store @relation(fields: [storeId], references: [id], onDelete: Cascade) customerId String - customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade) + 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 /// 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()) + passUpdatedAt DateTime @default(now()) lastCreditAt DateTime? /// Dernière relance « client inactif » envoyée (une seule par période d'inactivité). reminderSentAt DateTime? @@ -170,10 +177,22 @@ model LoyaltyCard { /// Demande d'avis Google envoyée (une seule fois par client) et clic sur le lien. reviewAskedAt DateTime? reviewClickedAt DateTime? - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - transactions Transaction[] - devices AppleRegistration[] + + /// Code de parrainage (lien partagé par le client), créé à la demande. + referralCode String? @unique @db.VarChar(16) + /// Carte du parrain si le client s'est inscrit par un lien de parrainage. + referredById String? + referredBy LoyaltyCard? @relation("Referral", fields: [referredById], references: [id], onDelete: SetNull) + referrals LoyaltyCard[] @relation("Referral") + /// Parrainage récompensé (premier passage du filleul). + referralRewardedAt DateTime? + /// Dernier message personnel (parrainage) affiché dans « Actualité ». + personalNews String? @db.VarChar(200) + personalNewsAt DateTime? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + transactions Transaction[] + devices AppleRegistration[] @@unique([storeId, customerId]) } diff --git a/backend/src/app.module.ts b/backend/src/app.module.ts index e009143..470acbb 100644 --- a/backend/src/app.module.ts +++ b/backend/src/app.module.ts @@ -17,6 +17,8 @@ import { CampaignsModule } from './campaigns/campaigns.controller'; import { RemindersModule } from './reminders/reminders.controller'; import { BirthdaysModule } from './birthdays/birthdays.controller'; import { ReviewsModule } from './reviews/reviews.controller'; +import { ReferralsModule } from './referrals/referrals.controller'; +import { ReferralsCoreModule } from './referrals/referrals.service'; import { HealthController } from './health.controller'; @Module({ @@ -37,6 +39,8 @@ import { HealthController } from './health.controller'; RemindersModule, BirthdaysModule, ReviewsModule, + ReferralsCoreModule, + ReferralsModule, ], controllers: [HealthController], providers: [{ provide: APP_GUARD, useClass: ThrottlerGuard }], diff --git a/backend/src/counter/counter.service.ts b/backend/src/counter/counter.service.ts index fb70ca2..fbe3c9c 100644 --- a/backend/src/counter/counter.service.ts +++ b/backend/src/counter/counter.service.ts @@ -2,6 +2,7 @@ import { BadRequestException, ForbiddenException, HttpException, HttpStatus, Inj import { Prisma, RejectReason, StaffRole } from '@prisma/client'; import { PrismaService } from '../prisma/prisma.service'; import { CardUpdatesService } from '../wallet/card-updates.service'; +import { ReferralsService } from '../referrals/referrals.service'; export type StaffContext = { staffId: string; storeId: string; role: StaffRole }; @@ -25,6 +26,7 @@ export class CounterService { constructor( private prisma: PrismaService, private cardUpdates: CardUpdatesService, + private referrals: ReferralsService, ) {} async me(ctx: StaffContext) { @@ -121,6 +123,8 @@ export class CounterService { }); } this.cardUpdates.notify(card.id); + // Premier passage d'un filleul : récompenses du parrainage (en arrière-plan). + this.referrals.onCredit(card.id); return { points, balance: result, firstName: card.customer.firstName }; } diff --git a/backend/src/enrollment/enrollment.controller.ts b/backend/src/enrollment/enrollment.controller.ts index f1981ef..d0cce5e 100644 --- a/backend/src/enrollment/enrollment.controller.ts +++ b/backend/src/enrollment/enrollment.controller.ts @@ -16,6 +16,8 @@ import { Response } from 'express'; import QRCode from 'qrcode'; import { Transform } from 'class-transformer'; import { Equals, IsEmail, IsInt, IsOptional, IsString, Length, Max, Min } from 'class-validator'; +import { ReferralsService } from '../referrals/referrals.service'; +import { referralOffered } from '../wallet/wallet.types'; import { EnrollmentService } from './enrollment.service'; import { ApplePassService } from '../wallet/apple-pass.service'; import { GoogleWalletService } from '../wallet/google-wallet.service'; @@ -40,6 +42,10 @@ class EnrollDto { @IsOptional() @IsInt() @Min(1) @Max(31) birthDay?: number; + + /** Code du parrain (lien ?parrain=…). */ + @IsOptional() @IsString() @Length(1, 16) + referralCode?: string; } class ResendDto { @@ -56,17 +62,19 @@ function html(res: Response, body: string, status = 200) { export class EnrollmentPagesController { constructor( private enrollment: EnrollmentService, + private referrals: ReferralsService, private apple: ApplePassService, private google: GoogleWalletService, ) {} @Get('c/:slug') - async enroll(@Param('slug') slug: string, @Res() res: Response) { + async enroll(@Param('slug') slug: string, @Query('parrain') code: string | undefined, @Res() res: Response) { const store = await this.enrollment.findStore(slug); // Brouillon : l'affichette peut déjà être imprimée, on affiche « indisponible » plutôt qu'un 404. if (!store) return html(res, notFoundPage(), 404); if (store.status !== 'ACTIVE' || !store.cardDesign) return html(res, unavailablePage(store)); - html(res, enrollPage(store)); + const referrer = await this.referrals.findReferrer(store, code); + html(res, enrollPage(store, referrer && { code: code!.toUpperCase(), firstName: referrer.firstName })); } @Get('c/:slug/confidentialite') @@ -86,6 +94,8 @@ export class EnrollmentPagesController { ) { const card = await this.enrollment.findCard(serial, key); if (!card) return html(res, notFoundPage(), 404); + if (referralOffered(card.store)) card.referralCode = await this.referrals.ensureCode(card.id); + const referred = card.referralCode ? await this.enrollment.referralCount(card.id) : 0; // La clé du lien ne doit pas fuiter vers des tiers (polices Google, etc.). res.setHeader('Referrer-Policy', 'no-referrer'); html( @@ -96,6 +106,8 @@ export class EnrollmentPagesController { apple: this.apple.enabled, google: this.google.enabled, // Même contenu que le QR des Wallets : l'app Pro le scanne directement sur l'écran. + referred, + referralUrl: this.enrollment.referralUrl(card), qrSvg: await QRCode.toString(card.serial, { type: 'svg', errorCorrectionLevel: 'M', margin: 0 }), }), ); @@ -114,7 +126,7 @@ export class EnrollmentApiController { @HttpCode(200) @Throttle({ default: { limit: 10, ttl: 60_000 } }) enroll(@Param('slug') slug: string, @Body() dto: EnrollDto) { - return this.enrollment.enroll(slug, dto.firstName, dto.email, dto.birthMonth && dto.birthDay ? { month: dto.birthMonth, day: dto.birthDay } : null); + return this.enrollment.enroll(slug, dto.firstName, dto.email, dto.birthMonth && dto.birthDay ? { month: dto.birthMonth, day: dto.birthDay } : null, dto.referralCode); } @Post('stores/:slug/resend') diff --git a/backend/src/enrollment/enrollment.service.ts b/backend/src/enrollment/enrollment.service.ts index 7e6d093..372b497 100644 --- a/backend/src/enrollment/enrollment.service.ts +++ b/backend/src/enrollment/enrollment.service.ts @@ -7,6 +7,8 @@ import { CARD_WITH_CONTEXT, CardWithContext } from '../wallet/wallet.types'; import { emailLayout, esc } from '../mail/email-layout'; import { isValidBirthday } from '../birthdays/birthdays.service'; import { birthdayOffered } from './pages'; +import { ReferralsService } from '../referrals/referrals.service'; +import { referralLink, referralOffered } from '../wallet/wallet.types'; /** Alphabet sans caractères ambigus : le numéro peut être lu à voix haute au comptoir. */ const SERIAL_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; @@ -37,6 +39,7 @@ export class EnrollmentService { private prisma: PrismaService, private mail: MailService, private config: ConfigService, + private referrals: ReferralsService, ) {} findStore(slug: string) { @@ -54,14 +57,16 @@ export class EnrollmentService { return store; } - async enroll(slug: string, firstName: string, rawEmail: string, birthday: { month: number; day: number } | null = null): Promise { + async enroll(slug: string, firstName: string, rawEmail: string, birthday: { month: number; day: number } | null = null, referralCode?: string): Promise { const store = await this.openStore(slug); const email = rawEmail.toLowerCase(); const existing = await this.findCardByEmail(store.id, email); if (existing) return { status: 'exists', maskedEmail: maskEmail(email) }; + const referrer = await this.referrals.findReferrer(store, referralCode); const card = await this.prisma.loyaltyCard.create({ data: { + ...(referrer && { referredBy: { connect: { id: referrer.id } } }), serial: randomSerial(), authToken: token(), accessKey: token(), @@ -78,6 +83,7 @@ export class EnrollmentService { }, include: CARD_WITH_CONTEXT, }); + if (referralOffered(card.store)) card.referralCode = await this.referrals.ensureCode(card.id); this.sendCardLink(card, true).catch((e) => this.logger.error(`E-mail d'inscription non envoyé : ${e.message}`)); return { status: 'created', cardUrl: this.cardUrl(card) }; } @@ -109,10 +115,19 @@ export class EnrollmentService { }); } + referralUrl(card: CardWithContext) { + return referralLink(this.config.get('webUrl')!, card); + } + cardUrl(card: { serial: string; accessKey: string }) { return `${this.config.get('webUrl')}/carte/${card.serial}?k=${card.accessKey}`; } + /** Filleuls inscrits avec le lien de cette carte. */ + referralCount(cardId: string) { + return this.prisma.loyaltyCard.count({ where: { referredById: cardId } }); + } + private findCardByEmail(storeId: string, email: string) { return this.prisma.loyaltyCard.findFirst({ where: { storeId, customer: { email } }, include: CARD_WITH_CONTEXT }); } diff --git a/backend/src/enrollment/pages.ts b/backend/src/enrollment/pages.ts index db659a2..2ddd1dd 100644 --- a/backend/src/enrollment/pages.ts +++ b/backend/src/enrollment/pages.ts @@ -185,7 +185,7 @@ ${more > 0 ? `
et ${more} autre${more > 1 ? 's' : ''} récompen
`; } -export function enrollPage(store: StoreWithDesign) { +export function enrollPage(store: StoreWithDesign, referrer: { code: string; firstName: string } | null = null) { const program = store.cardDesign!.programName; const unitLower = store.cardDesign!.pointsMode === 'STAMP' ? 'tampons' : 'points'; const body = ` @@ -194,6 +194,15 @@ export function enrollPage(store: StoreWithDesign) { ${e(store.name)} · ${e(store.city)}

${e(program)}

+ ${ + referrer + ? `
${e(referrer.firstName)} vous invite ! ${ + store.referralFriendPoints > 0 + ? `${store.referralFriendPoints} ${unitLower.replace(/s$/, '')}${store.referralFriendPoints > 1 ? 's' : ''} offert${store.referralFriendPoints > 1 ? 's' : ''} à votre premier passage en magasin.` + : 'Créez votre carte et passez en magasin.' + }
` + : '' + } ${promises(store)}
@@ -240,6 +249,7 @@ export function enrollPage(store: StoreWithDesign) { var slug=${JSON.stringify(store.slug)}; var $=function(id){return document.getElementById(id)}; var lastEmail=''; +var referralCode=${JSON.stringify(referrer?.code ?? null)}; var hasBirthday=${birthdayOffered(store) ? 'true' : 'false'}; ${BIRTHDAY_JS} function show(id,on){$(id).hidden=!on} @@ -253,7 +263,7 @@ $('f').addEventListener('submit',async function(ev){ if(!okName||!okMail||!consent||bd===false)return; $('submit').disabled=true; try{ - var r=await fetch('/api/public/stores/'+slug+'/enroll',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(Object.assign({firstName:firstName,email:email,consent:true},bd?{birthMonth:bd.month,birthDay:bd.day}:{}))}); + var r=await fetch('/api/public/stores/'+slug+'/enroll',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(Object.assign({firstName:firstName,email:email,consent:true},bd?{birthMonth:bd.month,birthDay:bd.day}:{},referralCode?{referralCode:referralCode}:{}))}); var data=await r.json().catch(function(){return {}}); if(!r.ok){throw new Error(r.status===409?'Le programme est momentanément indisponible.':r.status===429?'Trop de tentatives, réessayez dans une minute.':'Une erreur est survenue, réessayez.')} if(data.status==='created'){location.href=data.cardUrl+'&nouveau=1';return} @@ -306,7 +316,7 @@ function rewardsList(rewards: Reward[], balance: number, stamp: boolean) { export function cardPage( card: CardWithContext, - opts: { platform: Platform; isNew: boolean; apple: boolean; google: boolean; qrSvg: string }, + opts: { platform: Platform; isNew: boolean; apple: boolean; google: boolean; qrSvg: string; referred?: number; referralUrl?: string | null }, ) { const store = card.store as StoreWithDesign; const d = store.cardDesign!; @@ -366,6 +376,21 @@ ${askBirthday ? `Laisser un avis Google` : ''} ${opts.isNew ? '

Un e-mail de confirmation vous a été envoyé avec le lien de votre carte.

' : ''} +${ + opts.referralUrl + ? `
+ Parrainez vos proches + ${ + store.referralPoints > 0 + ? `Gagnez ${store.referralPoints} ${unit.toLowerCase().replace(/s$/, '')}${store.referralPoints > 1 ? 's' : ''} pour chaque ami qui s’inscrit avec votre lien et passe en magasin.` + : 'Partagez votre lien avec vos proches.' + }${store.referralFriendPoints > 0 ? ` Votre ami reçoit ${store.referralFriendPoints} ${unit.toLowerCase().replace(/s$/, '')}${store.referralFriendPoints > 1 ? 's' : ''} lui aussi.` : ''} + + + ${opts.referred ? `${opts.referred} ami${opts.referred > 1 ? 's' : ''} inscrit${opts.referred > 1 ? 's' : ''} grâce à vous.` : ''} +
` + : '' +}
Supprimer ma carte
@@ -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() {