MonEspacePro/backend/src/signup/signup.service.ts
Tony AVERTY 468e1bfa11 Inscription et espace du Dirigeant sur monespacepro.eu
Les pages des commerçants (/inscription, /espace) sont copiées dans le site
vitrine par « npm --prefix admin run build:espace » ; liens des e-mails,
de Stripe et de l'app Pro mis à jour. ADMIN_URL n'est plus nécessaire.

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

117 lines
6.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { ConflictException, Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { BillingInterval, Plan, Prisma } from '@prisma/client';
import * as argon2 from 'argon2';
import Stripe from 'stripe';
import { PrismaService } from '../prisma/prisma.service';
import { MailService } from '../mail/mail.service';
import { emailLayout, esc } from '../mail/email-layout';
import { uniqueSlug } from '../stores/slug';
import { PLANS } from '../billing/plans';
/** Champs du magasin saisis à l'inscription (copiés tels quels dans Store). */
export interface SignupStoreData {
name: string;
siret: string;
addressLine: string;
postalCode: string;
city: string;
contactName: string;
contactEmail: string;
contactPhone: string;
}
/**
* Inscription en ligne depuis la page Tarif : formulaire → paiement Stripe →
* création automatique du magasin et du compte Dirigeant (webhook) → e-mail
* de bienvenue avec le lien vers l'espace web pour concevoir la carte.
*/
@Injectable()
export class SignupService {
private readonly logger = new Logger(SignupService.name);
constructor(
private prisma: PrismaService,
private config: ConfigService,
private mail: MailService,
) {}
/** Enregistre la demande ; rien n'est créé avant le paiement. */
async prepare(data: SignupStoreData, password: string, plan: Plan, interval: BillingInterval) {
const email = data.contactEmail.toLowerCase();
if (await this.prisma.staffUser.findUnique({ where: { email }, select: { id: true } })) {
throw new ConflictException('Un compte existe déjà avec cet e-mail. Connectez-vous à votre espace, ou utilisez une autre adresse.');
}
return this.prisma.pendingSignup.create({
data: { email, data: { ...data, contactEmail: email } as unknown as Prisma.InputJsonValue, passwordHash: await argon2.hash(password), plan, interval },
});
}
/**
* Paiement réussi : crée le magasin (brouillon), le compte Dirigeant et
* l'abonnement. Idempotent (webhook rejoué). Renvoie l'id du magasin.
*/
async complete(session: Stripe.Checkout.Session, stripe: Stripe): Promise<string | undefined> {
const pending = await this.prisma.pendingSignup.findUnique({ where: { id: session.metadata!.signupId } });
if (!pending) {
this.logger.error(`Inscription ${session.metadata!.signupId} introuvable (session ${session.id})`);
return undefined;
}
if (pending.storeId) return pending.storeId;
const data = pending.data as unknown as SignupStoreData;
const customerId = String(session.customer);
const store = await this.prisma.$transaction(async (tx) => {
const store = await tx.store.create({ data: { ...data, slug: await uniqueSlug(this.prisma, data.name) } });
await tx.subscription.create({ data: { storeId: store.id, stripeCustomerId: customerId, plan: pending.plan, interval: pending.interval } });
await tx.pendingSignup.update({ where: { id: pending.id }, data: { storeId: store.id } });
return store;
});
// Compte Dirigeant : l'e-mail a pu être pris entre-temps (cas rarissime) ; le magasin existe quand même.
try {
await this.prisma.staffUser.create({
data: { storeId: store.id, email: pending.email, displayName: data.contactName, role: 'MANAGER', passwordHash: pending.passwordHash },
});
} catch (e) {
if (!(e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002')) throw e;
this.logger.error(`Inscription ${pending.id} : e-mail ${pending.email} déjà utilisé, compte Dirigeant à créer depuis l'admin`);
}
// Les prochains événements Stripe retrouvent le magasin par ces métadonnées.
await stripe.customers.update(customerId, {
name: data.name,
phone: data.contactPhone,
address: { line1: data.addressLine, postal_code: data.postalCode, city: data.city, country: 'FR' },
metadata: { storeId: store.id, siret: data.siret },
});
if (session.subscription) await stripe.subscriptions.update(String(session.subscription), { metadata: { storeId: store.id } });
await this.welcome(store.id).catch((e) => this.logger.error(`E-mail de bienvenue non envoyé : ${(e as Error).message}`));
this.logger.log(`Inscription en ligne : magasin ${store.id} (${data.name}) créé, formule ${pending.plan}`);
return store.id;
}
private async welcome(storeId: string) {
const store = await this.prisma.store.findUniqueOrThrow({ where: { id: storeId }, include: { subscription: true } });
const espace = `${this.config.get('webUrl')}/espace`;
const def = PLANS[store.subscription?.plan ?? 'ESSENTIEL'];
const text = `Bonjour ${store.contactName},\n\nBienvenue sur MonEspacePro ! Votre abonnement ${def.name} pour ${store.name} est actif.\n\nDernière étape : concevez votre carte de fidélité (logo, couleurs, récompenses) sur ${espace}, avec l'e-mail ${store.contactEmail} et le mot de passe choisi à l'inscription. Votre programme s'ouvre à vos clients dès la carte enregistrée.\n\nEn caisse, installez l'app MonEspacePro Pro sur votre téléphone et connectez-vous avec les mêmes identifiants.\n\nMonEspacePro`;
const html = emailLayout({
webUrl: this.config.get('webUrl')!,
preheader: `Concevez votre carte de fidélité pour ouvrir ${store.name} à vos clients.`,
eyebrow: `Formule ${def.name}`,
title: 'Bienvenue sur MonEspacePro',
paragraphs: [
`Bonjour ${esc(store.contactName)},`,
`Votre abonnement <strong>${esc(def.name)}</strong> pour <strong>${esc(store.name)}</strong> est actif. Dernière étape : concevez votre carte de fidélité (logo, couleurs, récompenses). Votre programme s'ouvre à vos clients dès la carte enregistrée.`,
],
cta: { label: 'Concevoir ma carte', url: espace },
details: [
['Identifiant', esc(store.contactEmail)],
['Mot de passe', 'Celui choisi à l’inscription'],
['En caisse', 'App MonEspacePro Pro, mêmes identifiants'],
],
note: 'Depuis l’app Pro, vous créez aussi les comptes de vos employés et réglez vos modules.',
});
await this.mail.send(store.contactEmail, `Bienvenue sur MonEspacePro, ${store.name}`, text, html);
}
}