MonEspacePro/backend/src/referrals/referrals.service.ts
Tony AVERTY bf10beb89b Inscription en ligne automatique, rôle Dirigeant, cadeaux en nature, titre des campagnes
- Inscription depuis la page Tarif : paiement Stripe puis création automatique
  du magasin, de l'abonnement et du compte Dirigeant (webhook), e-mail de bienvenue
- Plus d'essai gratuit (site, Stripe, e-mails)
- Création d'un magasin dans l'admin : formule obligatoire, compte Dirigeant et
  lien de paiement permanent envoyés automatiquement
- Ouverture automatique du magasin dès l'abonnement payé et la carte conçue
- API du Dirigeant : carte, employés, fiche magasin ; changement de mot de passe
- Anniversaire et parrainage : cadeau en nature remis en caisse
- Campagnes : titre de notification choisi à chaque envoi
- « Gérant » devient « Dirigeant »

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 11:45:07 +02:00

126 lines
6.6 KiB
TypeScript

import { Global, Injectable, Logger, Module, OnModuleInit } from '@nestjs/common';
import { randomInt } from 'crypto';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { fill, moduleActive, moduleConfig, rewardVars, StoreModules } from '../modules/catalog';
import { ModulesService } from '../modules/modules.service';
import { CardUpdatesService } from '../wallet/card-updates.service';
const ALPHABET = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789';
/**
* Module « 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 implements OnModuleInit {
private readonly logger = new Logger(ReferralsService.name);
constructor(
private prisma: PrismaService,
private modules: ModulesService,
private cardUpdates: CardUpdatesService,
) {}
onModuleInit() {
this.modules.registerStats('referral', async (storeId) => {
const [referred, rewarded] = await Promise.all([
this.prisma.loyaltyCard.count({ where: { storeId, referredById: { not: null } } }),
this.prisma.loyaltyCard.count({ where: { storeId, referredById: { not: null }, referralRewardedAt: { not: null } } }),
]);
return { 'Filleuls inscrits': referred, 'Venus en magasin': rewarded };
});
// À l'activation, chaque carte reçoit son code : le lien apparaît au dos des cartes existantes.
this.modules.registerHook('referral', async (storeId, values) => {
if (!values.enabled) return;
const cards = await this.prisma.loyaltyCard.findMany({ where: { storeId, referralCode: null }, select: { id: true } });
for (const c of cards) await this.ensureCode(c.id);
});
}
/** Code de parrainage de la carte, créé au besoin. */
async ensureCode(cardId: string): Promise<string> {
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 module inactif. */
async findReferrer(store: StoreModules & { id: string }, code: string | undefined | null) {
if (!code || !moduleActive(store, 'referral')) 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;
}
/** 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 (!moduleActive(store, 'referral') || store.status !== 'ACTIVE' || store.billingSuspended) return;
const c = moduleConfig(store, 'referral');
const stamp = store.cardDesign?.pointsMode === 'STAMP';
const title = fill(String(c.title), { magasin: store.name }) || store.name;
const base = { magasin: store.name };
const friendPoints = Number(c.friendPoints);
const friendGift = String(c.friendGift).trim();
const friendVars = rewardVars(friendPoints, friendGift, stamp);
const friendNews = friendVars.recompense ? fill(String(c.friendMessage), { ...base, prenom: friend.customer.firstName, ...friendVars }) : 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: friendPoints }, personalNews: friendNews.slice(0, 200), personalNewsAt: now, passUpdatedAt: now }),
},
});
if (!count) return;
if (friendGift) await this.prisma.gift.create({ data: { cardId: friend.id, label: friendGift, source: 'REFERRAL_FRIEND' } });
if (friendNews) await this.cardUpdates.remind(friend.id, friendNews, title);
const points = Number(c.points);
const gift = String(c.gift).trim();
const vars = rewardVars(points, gift, stamp);
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 (!vars.recompense || recent >= Number(c.maxRewardsPer30Days)) return;
const referrer = await this.prisma.loyaltyCard.findUnique({ where: { id: friend.referredById }, include: { customer: true } });
if (!referrer || referrer.storeId !== store.id) return;
const news = fill(String(c.referrerMessage), { ...base, prenom: referrer.customer.firstName, filleul: friend.customer.firstName, ...vars });
await this.prisma.loyaltyCard.update({
where: { id: referrer.id },
data: { balance: { increment: points }, personalNews: news.slice(0, 200), personalNewsAt: now, passUpdatedAt: now },
});
if (gift) await this.prisma.gift.create({ data: { cardId: referrer.id, label: gift, source: 'REFERRAL' } });
await this.cardUpdates.remind(referrer.id, news, title);
}
}
@Global()
@Module({ providers: [ReferralsService], exports: [ReferralsService] })
export class ReferralsCoreModule {}