From fe6874458d84609d2d863e56ece3af416c504280 Mon Sep 17 00:00:00 2001 From: Tony AVERTY Date: Wed, 7 Oct 2026 10:09:53 +0200 Subject: [PATCH] =?UTF-8?q?Socle=20des=20formules=20d'abonnement=20(Essent?= =?UTF-8?q?iel=2019=20=E2=82=AC,=20Pro=2039=20=E2=82=AC,=20R=C3=A9seau=202?= =?UTF-8?q?9=20=E2=82=AC/magasin)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Catalogue src/billing/plans.ts : prix mensuels/annuels (2 mois offerts), fonctions incluses et limites ; ancien prix 10 € = tarif fondateur - Formule enregistrée sur l'abonnement, déduite du prix Stripe (lookup_key) : un changement fait depuis le portail client est repris automatiquement - Lien d'abonnement au choix (formule, périodicité), essai 30 jours (une fois par magasin), codes promo ; e-mail de fin d'essai (trial_will_end) - Portail client Stripe (changer de formule, moyen de paiement, résilier) - EntitlementsService : droits par formule ; appliqué à la limite de 3 employés en Essentiel et au retrait de « Propulsé par » en Pro - Factures : libellé de la formule et de la périodicité - scripts/stripe-setup.ts idempotent (produits, prix, portail, webhook) - Admin : choix de la formule, badges, espace abonnement Co-Authored-By: Claude Opus 5.5 --- admin/src/api.ts | 6 +- admin/src/pages/BillingTab.tsx | 154 +++++++++++-- admin/src/pages/StorePage.tsx | 7 +- admin/src/pages/StoresPage.tsx | 4 +- .../manual-migrations/2026-10-07-formules.sql | 16 ++ backend/prisma/schema.prisma | 21 ++ backend/scripts/stripe-setup.ts | 139 ++++++++++++ backend/src/app.module.ts | 2 + backend/src/billing/billing.controller.ts | 31 ++- backend/src/billing/billing.service.ts | 213 ++++++++++++++---- backend/src/billing/entitlements.service.ts | 57 +++++ backend/src/billing/invoice-pdf.ts | 4 +- backend/src/billing/plans.ts | 102 +++++++++ backend/src/config/configuration.ts | 3 +- backend/src/enrollment/enrollment.service.ts | 2 +- backend/src/enrollment/pages.ts | 13 +- backend/src/staff/staff.service.ts | 8 +- backend/src/stores/stores.service.ts | 3 +- backend/src/wallet/wallet.types.ts | 7 +- 19 files changed, 707 insertions(+), 85 deletions(-) create mode 100644 backend/prisma/manual-migrations/2026-10-07-formules.sql create mode 100644 backend/scripts/stripe-setup.ts create mode 100644 backend/src/billing/entitlements.service.ts create mode 100644 backend/src/billing/plans.ts diff --git a/admin/src/api.ts b/admin/src/api.ts index ba2c6c6..404ba64 100644 --- a/admin/src/api.ts +++ b/admin/src/api.ts @@ -131,6 +131,9 @@ export const api = { // ── Types partagés avec l'API ───────────────────────────────── export type StoreStatus = 'DRAFT' | 'ACTIVE' | 'SUSPENDED' | 'CLOSED'; export type SubscriptionStatus = 'INCOMPLETE' | 'ACTIVE' | 'PAST_DUE' | 'CANCELED'; +export type Plan = 'ESSENTIEL' | 'PRO' | 'RESEAU'; +export type BillingInterval = 'MONTH' | 'YEAR'; +export const PLAN_LABEL: Record = { ESSENTIEL: 'Essentiel', PRO: 'Pro', RESEAU: 'Réseau' }; export interface Store { id: string; @@ -153,11 +156,12 @@ export interface Store { export interface StoreListItem extends Store { customers: number; subscriptionStatus: SubscriptionStatus | null; + plan: Plan | null; } export interface StoreDetail extends Store { counts: { cards: number; staff: number; transactions: number }; - subscription: { status: SubscriptionStatus } | null; + subscription: { status: SubscriptionStatus; plan: Plan; stripeSubscriptionId: string | null } | null; /** Lien encodé dans le QR d'inscription. */ enrollUrl: string; } diff --git a/admin/src/pages/BillingTab.tsx b/admin/src/pages/BillingTab.tsx index c3c479f..de92c5d 100644 --- a/admin/src/pages/BillingTab.tsx +++ b/admin/src/pages/BillingTab.tsx @@ -1,11 +1,32 @@ import { useCallback, useEffect, useState } from 'react'; -import { api, downloadFile, SubscriptionStatus } from '../api'; +import { api, BillingInterval, downloadFile, Plan, SubscriptionStatus } from '../api'; + +interface CatalogEntry { + plan: Plan; + name: string; + tagline: string; + priceCents: Record; + features: string[]; + limits: { maxStaff: number | null }; +} interface Billing { testMode: boolean; - subscription: { status: SubscriptionStatus; currentPeriodEnd: string | null; hasCustomer: boolean } | null; + catalog: CatalogEntry[]; + trialDays: number; + subscription: { + status: SubscriptionStatus; + plan: Plan; + interval: BillingInterval; + legacyPrice: boolean; + trialEndsAt: string | null; + cancelAtPeriodEnd: boolean; + currentPeriodEnd: string | null; + hasCustomer: boolean; + hasSubscription: boolean; + } | null; billingSuspended: boolean; - invoices: { id: string; number: string; amountCents: number; periodStart: string; periodEnd: string; issuedAt: string; paidAt: string | null }[]; + invoices: { id: string; number: string; description: string; amountCents: number; periodStart: string; periodEnd: string; issuedAt: string; paidAt: string | null }[]; } const STATUS: Record = { @@ -15,25 +36,42 @@ const STATUS: Record = { CANCELED: ['Résilié', 'CLOSED'], }; -const euros = (c: number) => (c / 100).toLocaleString('fr-FR', { style: 'currency', currency: 'EUR' }); +/** Libellés lisibles des fonctions du catalogue (src/billing/plans.ts côté API). */ +const FEATURE_LABEL: Record = { + campaigns: 'Notifications push et campagnes', + inactiveReminders: 'Relance des clients inactifs', + birthday: "Offre d'anniversaire", + googleReview: "Collecte d'avis Google", + referral: 'Parrainage', + advancedStats: 'Statistiques avancées', + csvExport: 'Export CSV', + whiteLabel: 'Sans « Propulsé par MonEspacePro »', + multiStore: 'Carte commune à plusieurs magasins', +}; + +const euros = (c: number) => (c / 100).toLocaleString('fr-FR', { style: 'currency', currency: 'EUR', minimumFractionDigits: c % 100 ? 2 : 0 }); const day = (d: string) => new Date(d).toLocaleDateString('fr-FR', { day: 'numeric', month: 'short', year: 'numeric' }); export function BillingTab({ storeId, contactEmail, onChange }: { storeId: string; contactEmail: string; onChange: () => void }) { const [data, setData] = useState(null); const [error, setError] = useState(null); - const [link, setLink] = useState<{ url: string; emailedTo: string | null } | null>(null); + const [link, setLink] = useState<{ url: string; emailedTo: string | null; label: string } | null>(null); const [busy, setBusy] = useState(false); + const [plan, setPlan] = useState('PRO'); + const [interval, setInterval] = useState('MONTH'); + const [trial, setTrial] = useState(true); const reload = useCallback(() => { api.get(`/api/admin/stores/${storeId}/billing`).then(setData).catch((e) => setError(e.message)); }, [storeId]); useEffect(reload, [reload]); - async function createLink(sendEmail: boolean) { + async function run(label: string, path: string, body: object) { setBusy(true); setError(null); try { - setLink(await api.post(`/api/admin/stores/${storeId}/billing/checkout-link`, { sendEmail })); + const r = await api.post<{ url: string; emailedTo: string | null }>(path, body); + setLink({ ...r, label }); reload(); onChange(); } catch (e) { @@ -45,7 +83,10 @@ export function BillingTab({ storeId, contactEmail, onChange }: { storeId: strin if (!data) return error ?
{error}
:

Chargement…

; const sub = data.subscription; - const active = sub?.status === 'ACTIVE'; + const current = sub && sub.status !== 'CANCELED' && sub.hasSubscription ? data.catalog.find((c) => c.plan === sub.plan) : null; + const trialing = sub?.trialEndsAt && new Date(sub.trialEndsAt) > new Date(); + const trialUsed = !!sub?.trialEndsAt; + const canSubscribe = !current; return ( <> @@ -56,35 +97,101 @@ export function BillingTab({ storeId, contactEmail, onChange }: { storeId: strin

Abonnement

-

10 € par mois, sans engagement — carte bancaire ou prélèvement SEPA.

+

+ {current + ? `Formule ${current.name}${sub!.legacyPrice ? ' (tarif fondateur)' : ''} — ${sub!.interval === 'YEAR' ? 'annuelle' : 'mensuelle'}` + : 'Aucune formule souscrite. Sans abonnement actif, le magasin a les droits de la formule Essentiel.'} +

{sub ? STATUS[sub.status][0] : 'Aucun abonnement'}
- {sub?.currentPeriodEnd && active &&

Prochain prélèvement le {day(sub.currentPeriodEnd)}.

} - {data.billingSuspended && ( -
Magasin suspendu automatiquement pour impayé. Il sera réactivé dès que le paiement passera.
+ {trialing &&
Essai gratuit jusqu'au {day(sub!.trialEndsAt!)} : aucun prélèvement avant cette date.
} + {sub?.cancelAtPeriodEnd && sub.currentPeriodEnd && ( +
Résiliation demandée : l'abonnement s'arrête le {day(sub.currentPeriodEnd)}.
)} - {!active && ( + {sub?.currentPeriodEnd && sub.status === 'ACTIVE' && !sub.cancelAtPeriodEnd && !trialing && ( +

Prochain prélèvement le {day(sub.currentPeriodEnd)}.

+ )} + {data.billingSuspended &&
Magasin suspendu automatiquement pour impayé. Il sera réactivé dès que le paiement passera.
} + + {current && (
- - -
- )} - {link && ( -
- {link.emailedTo ? <>Lien envoyé à {link.emailedTo}. : null} - Valable 24 h :{' '} - {link.url} + + + Changer de formule, de moyen de paiement, résilier.
)} + {canSubscribe && ( +
+
+

Choisir une formule

+
+ + +
+
+
+ {data.catalog.map((c) => ( + + ))} +
+ +

+ Le commerçant pourra saisir un code promo sur la page de paiement (codes à créer dans Stripe → Coupons). +

+
+ + +
+
+ )} + + {link && ( +
+ {link.label} {link.emailedTo ? <>envoyé à {link.emailedTo}. : 'créé. '} + {link.url} +
+ )} +
- +
+ @@ -95,6 +202,7 @@ export function BillingTab({ storeId, contactEmail, onChange }: { storeId: strin {data.invoices.map((i) => ( + diff --git a/admin/src/pages/StorePage.tsx b/admin/src/pages/StorePage.tsx index 0ef9600..d48d0ab 100644 --- a/admin/src/pages/StorePage.tsx +++ b/admin/src/pages/StorePage.tsx @@ -1,6 +1,6 @@ import { useCallback, useEffect, useState } from 'react'; import { Link, NavLink, Navigate, Route, Routes, useParams } from 'react-router-dom'; -import { api, StoreDetail, StoreStatus } from '../api'; +import { api, PLAN_LABEL, StoreDetail, StoreStatus } from '../api'; import { StatusBadge } from '../components/Layout'; import { StoreForm } from '../components/StoreForm'; import { CardWizard } from './CardWizard'; @@ -46,6 +46,11 @@ export function StorePage() {

{store.name}

+ {store.subscription?.stripeSubscriptionId && store.subscription.status !== 'CANCELED' && ( + + {PLAN_LABEL[store.subscription.plan]} + + )}

{store.city} · {store.counts.cards} clients · {store.counts.staff} employés diff --git a/admin/src/pages/StoresPage.tsx b/admin/src/pages/StoresPage.tsx index 60559dd..204ece6 100644 --- a/admin/src/pages/StoresPage.tsx +++ b/admin/src/pages/StoresPage.tsx @@ -1,6 +1,6 @@ import { useEffect, useState } from 'react'; import { Link } from 'react-router-dom'; -import { api, StoreListItem, StoreStatus } from '../api'; +import { api, PLAN_LABEL, StoreListItem, StoreStatus } from '../api'; import { STATUS_LABEL, StatusBadge } from '../components/Layout'; const FILTERS: (StoreStatus | 'ALL')[] = ['ALL', 'DRAFT', 'ACTIVE', 'SUSPENDED', 'CLOSED']; @@ -101,7 +101,7 @@ export function StoresPage() {

- + ))} diff --git a/backend/prisma/manual-migrations/2026-10-07-formules.sql b/backend/prisma/manual-migrations/2026-10-07-formules.sql new file mode 100644 index 0000000..7cc0b39 --- /dev/null +++ b/backend/prisma/manual-migrations/2026-10-07-formules.sql @@ -0,0 +1,16 @@ +-- Formules d'abonnement (Essentiel / Pro / Réseau) — à exécuter UNE fois dans phpMyAdmin +-- sur la base monespacepro, AVANT de déployer le nouveau code. Sans perte de données. + +-- AlterTable +ALTER TABLE `Subscription` ADD COLUMN `cancelAtPeriodEnd` BOOLEAN NOT NULL DEFAULT false, + ADD COLUMN `interval` ENUM('MONTH', 'YEAR') NOT NULL DEFAULT 'MONTH', + ADD COLUMN `legacyPrice` BOOLEAN NOT NULL DEFAULT false, + ADD COLUMN `plan` ENUM('ESSENTIEL', 'PRO', 'RESEAU') NOT NULL DEFAULT 'ESSENTIEL', + ADD COLUMN `trialEndsAt` DATETIME(3) NULL; + +-- AlterTable +ALTER TABLE `Invoice` ADD COLUMN `description` VARCHAR(191) NOT NULL DEFAULT 'Abonnement MonEspacePro — carte de fidélité dématérialisée, 1 magasin'; + + +-- Les abonnements existants sont à l'ancien prix unique (10 €/mois) : tarif fondateur, formule Essentiel. +UPDATE `Subscription` SET `legacyPrice` = true WHERE `stripeSubscriptionId` IS NOT NULL; diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index c3330a4..bb99c87 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -201,6 +201,18 @@ model AppleRegistration { } // ── Facturation ─────────────────────────────────────────────── +/// Formule d'abonnement (catalogue : src/billing/plans.ts). +enum Plan { + ESSENTIEL + PRO + RESEAU +} + +enum BillingInterval { + MONTH + YEAR +} + enum SubscriptionStatus { INCOMPLETE ACTIVE @@ -215,6 +227,13 @@ model Subscription { stripeCustomerId String? @unique stripeSubscriptionId String? @unique status SubscriptionStatus @default(INCOMPLETE) + /// Formule payée (recopiée depuis le prix Stripe). Sans abonnement : ESSENTIEL. + plan Plan @default(ESSENTIEL) + interval BillingInterval @default(MONTH) + /// Ancien tarif conservé (« fondateur ») : prix Stripe hors catalogue. + legacyPrice Boolean @default(false) + trialEndsAt DateTime? + cancelAtPeriodEnd Boolean @default(false) currentPeriodEnd DateTime? updatedAt DateTime @updatedAt } @@ -228,6 +247,8 @@ model Invoice { store Store @relation(fields: [storeId], references: [id]) stripeInvoiceId String? @unique amountCents Int + /// Libellé de la ligne (formule et période), figé à l'émission. + description String @default("Abonnement MonEspacePro — carte de fidélité dématérialisée, 1 magasin") /// Identité du client figée à l'émission (une facture ne change plus). clientName String clientAddress String @db.Text diff --git a/backend/scripts/stripe-setup.ts b/backend/scripts/stripe-setup.ts new file mode 100644 index 0000000..54513a9 --- /dev/null +++ b/backend/scripts/stripe-setup.ts @@ -0,0 +1,139 @@ +/** + * Prépare le compte Stripe pour les formules MonEspacePro. Idempotent : + * peut être relancé (test, puis production) sans créer de doublons. + * + * npx ts-node scripts/stripe-setup.ts + * + * - un produit par formule et ses prix mensuel / annuel (lookup_key du catalogue) ; + * - la configuration du portail client (changement de formule, résiliation…) ; + * - les événements du webhook (ajout de la fin d'essai). + * Affiche STRIPE_PORTAL_CONFIG_ID à recopier dans le .env. + */ +import Stripe from 'stripe'; +import { PLANS } from '../src/billing/plans'; + +try { + process.loadEnvFile(); +} catch { + /* variables déjà présentes */ +} + +const key = process.env.STRIPE_SECRET_KEY; +if (!key) throw new Error('STRIPE_SECRET_KEY manquante'); +const stripe = new Stripe(key); +const mode = key.startsWith('sk_test_') ? 'TEST' : 'PRODUCTION'; + +const WEBHOOK_EVENTS: Stripe.WebhookEndpointCreateParams.EnabledEvent[] = [ + 'checkout.session.completed', + 'customer.subscription.created', + 'customer.subscription.updated', + 'customer.subscription.deleted', + 'customer.subscription.trial_will_end', + 'invoice.paid', + 'invoice.payment_failed', +]; + +async function main() { + console.log(`Stripe en mode ${mode}\n`); + const portalProducts: Stripe.BillingPortal.ConfigurationCreateParams.Features.SubscriptionUpdate.Product[] = []; + + // Pas de products.search : son index n'est pas immédiat et ferait créer des doublons. + const allProducts = await stripe.products.list({ active: true, limit: 100 }); + + for (const def of Object.values(PLANS)) { + // Produit : celui d'un prix existant de la formule, sinon par sa métadonnée, sinon création. + const knownPrice = (await stripe.prices.list({ lookup_keys: Object.values(def.lookupKey), limit: 1 })).data[0]; + const product = + (knownPrice && (await stripe.products.retrieve(String(knownPrice.product)))) ?? + allProducts.data.find((p) => p.metadata?.mep_plan === def.plan) ?? + (await stripe.products.create({ + name: `MonEspacePro ${def.name}`, + description: def.tagline, + metadata: { mep_plan: def.plan }, + })); + const priceIds: string[] = []; + for (const interval of ['MONTH', 'YEAR'] as const) { + const lookupKey = def.lookupKey[interval]; + let price = (await stripe.prices.list({ lookup_keys: [lookupKey], limit: 1 })).data[0]; + if (price && price.unit_amount !== def.priceCents[interval]) { + // Le prix a changé dans le catalogue : nouveau prix, la clé lui est transférée. + price = await stripe.prices.create({ + product: product.id, + currency: 'eur', + unit_amount: def.priceCents[interval], + recurring: { interval: interval === 'YEAR' ? 'year' : 'month' }, + lookup_key: lookupKey, + transfer_lookup_key: true, + nickname: `${def.name} ${interval === 'YEAR' ? 'annuel' : 'mensuel'}`, + }); + console.log(` prix mis à jour ${lookupKey} → ${price.id}`); + } else if (!price) { + price = await stripe.prices.create({ + product: product.id, + currency: 'eur', + unit_amount: def.priceCents[interval], + recurring: { interval: interval === 'YEAR' ? 'year' : 'month' }, + lookup_key: lookupKey, + nickname: `${def.name} ${interval === 'YEAR' ? 'annuel' : 'mensuel'}`, + }); + console.log(` prix créé ${lookupKey} → ${price.id}`); + } + priceIds.push(price.id); + } + portalProducts.push({ product: product.id, prices: priceIds }); + console.log(`✓ ${def.name} (${product.id})`); + } + + // Portail client + const portalParams: Stripe.BillingPortal.ConfigurationCreateParams = { + business_profile: { + headline: 'MonEspacePro — gérez votre abonnement', + privacy_policy_url: 'https://monespacepro.eu/confidentialite/', + terms_of_service_url: 'https://monespacepro.eu/cgv/', + }, + default_return_url: 'https://monespacepro.eu/', + features: { + customer_update: { enabled: true, allowed_updates: ['email', 'address', 'phone', 'name'] }, + invoice_history: { enabled: true }, + payment_method_update: { enabled: true }, + subscription_cancel: { + enabled: true, + mode: 'at_period_end', + cancellation_reason: { + enabled: true, + options: ['too_expensive', 'unused', 'missing_features', 'switched_service', 'other'], + }, + }, + subscription_update: { + enabled: true, + default_allowed_updates: ['price'], + proration_behavior: 'create_prorations', + products: portalProducts, + }, + }, + }; + const configs = await stripe.billingPortal.configurations.list({ active: true, limit: 100 }); + const ours = configs.data.find((c) => c.metadata?.mep === 'portal'); + const portal = ours + ? await stripe.billingPortal.configurations.update(ours.id, portalParams) + : await stripe.billingPortal.configurations.create({ ...portalParams, metadata: { mep: 'portal' } }); + console.log(`✓ Portail client ${ours ? 'mis à jour' : 'créé'}`); + + // Webhook + const url = 'https://api.monespacepro.eu/api/stripe/webhook'; + const hook = (await stripe.webhookEndpoints.list({ limit: 100 })).data.find((w) => w.url === url); + if (hook) { + await stripe.webhookEndpoints.update(hook.id, { enabled_events: WEBHOOK_EVENTS }); + console.log('✓ Webhook : événements à jour'); + } else { + const created = await stripe.webhookEndpoints.create({ url, enabled_events: WEBHOOK_EVENTS, description: 'MonEspacePro API' }); + console.log(`✓ Webhook créé — STRIPE_WEBHOOK_SECRET=${created.secret}`); + } + + console.log(`\nÀ mettre dans le .env :\nSTRIPE_PORTAL_CONFIG_ID=${portal.id}`); +} + +main().catch((e) => { + console.error('ERREUR', e.message); + process.exit(1); +}); diff --git a/backend/src/app.module.ts b/backend/src/app.module.ts index 99868af..917fff2 100644 --- a/backend/src/app.module.ts +++ b/backend/src/app.module.ts @@ -11,6 +11,7 @@ import { EnrollmentModule } from './enrollment/enrollment.module'; import { CounterModule } from './counter/counter.module'; import { ContactModule } from './contact/contact.controller'; import { BillingModule } from './billing/billing.controller'; +import { EntitlementsModule } from './billing/entitlements.service'; import { WalletModule } from './wallet/wallet.module'; import { HealthController } from './health.controller'; @@ -27,6 +28,7 @@ import { HealthController } from './health.controller'; CounterModule, ContactModule, BillingModule, + EntitlementsModule, ], controllers: [HealthController], providers: [{ provide: APP_GUARD, useClass: ThrottlerGuard }], diff --git a/backend/src/billing/billing.controller.ts b/backend/src/billing/billing.controller.ts index bc43311..5e0fa93 100644 --- a/backend/src/billing/billing.controller.ts +++ b/backend/src/billing/billing.controller.ts @@ -1,17 +1,33 @@ import { Body, Controller, Get, Headers, HttpCode, Logger, Module, Param, Post, Req, Res, UseGuards } from '@nestjs/common'; import type { RawBodyRequest } from '@nestjs/common'; import { SkipThrottle } from '@nestjs/throttler'; -import { IsBoolean, IsOptional } from 'class-validator'; +import { BillingInterval, Plan } from '@prisma/client'; +import { IsBoolean, IsEnum, IsOptional } from 'class-validator'; import type { Request, Response } from 'express'; import { AdminGuard, JwtAuthGuard } from '../common/guards'; import { BillingService } from './billing.service'; class CheckoutLinkDto { + @IsEnum(Plan) + plan!: Plan; + + @IsEnum(BillingInterval) + interval!: BillingInterval; + + /** Proposer l'essai gratuit (une seule fois par magasin). */ + @IsOptional() @IsBoolean() + trial?: boolean; + /** Envoyer le lien par e-mail au contact du magasin. */ @IsOptional() @IsBoolean() sendEmail?: boolean; } +class PortalLinkDto { + @IsOptional() @IsBoolean() + sendEmail?: boolean; +} + @Controller('admin') @UseGuards(JwtAuthGuard, AdminGuard) export class BillingAdminController { @@ -25,7 +41,18 @@ export class BillingAdminController { @Post('stores/:storeId/billing/checkout-link') @HttpCode(200) checkoutLink(@Param('storeId') storeId: string, @Body() dto: CheckoutLinkDto) { - return this.billing.checkoutLink(storeId, dto.sendEmail ?? true); + return this.billing.checkoutLink(storeId, { + plan: dto.plan, + interval: dto.interval, + trial: dto.trial ?? false, + sendEmail: dto.sendEmail ?? true, + }); + } + + @Post('stores/:storeId/billing/portal-link') + @HttpCode(200) + portalLink(@Param('storeId') storeId: string, @Body() dto: PortalLinkDto) { + return this.billing.portalLink(storeId, dto.sendEmail ?? false); } @Get('invoices/:id/pdf') diff --git a/backend/src/billing/billing.service.ts b/backend/src/billing/billing.service.ts index 37eb2a8..33898ae 100644 --- a/backend/src/billing/billing.service.ts +++ b/backend/src/billing/billing.service.ts @@ -1,6 +1,6 @@ import { BadRequestException, Injectable, Logger, NotFoundException, ServiceUnavailableException } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; -import { Prisma, SubscriptionStatus } from '@prisma/client'; +import { BillingInterval, Plan, Prisma, SubscriptionStatus } from '@prisma/client'; import { mkdir, readFile, writeFile } from 'fs/promises'; import { join } from 'path'; import Stripe from 'stripe'; @@ -8,6 +8,7 @@ import { PrismaService } from '../prisma/prisma.service'; import { MailService } from '../mail/mail.service'; import { emailLayout, esc } from '../mail/email-layout'; import { renderInvoicePdf } from './invoice-pdf'; +import { PLANS, TRIAL_DAYS, planFromLookupKey, publicCatalog } from './plans'; /** Factures PDF : hors des dossiers servis publiquement. */ export const INVOICES_DIR = join(process.cwd(), 'storage', 'invoices'); @@ -54,17 +55,27 @@ export class BillingService { include: { subscription: true, invoices: { orderBy: { sequence: 'desc' } } }, }); if (!store) throw new NotFoundException('Magasin introuvable'); + const sub = store.subscription; return { testMode: (this.config.get('stripe.secretKey') ?? '').startsWith('sk_test_'), - subscription: store.subscription && { - status: store.subscription.status, - currentPeriodEnd: store.subscription.currentPeriodEnd, - hasCustomer: !!store.subscription.stripeCustomerId, + catalog: publicCatalog(), + trialDays: TRIAL_DAYS, + subscription: sub && { + status: sub.status, + plan: sub.plan, + interval: sub.interval, + legacyPrice: sub.legacyPrice, + trialEndsAt: sub.trialEndsAt, + cancelAtPeriodEnd: sub.cancelAtPeriodEnd, + currentPeriodEnd: sub.currentPeriodEnd, + hasCustomer: !!sub.stripeCustomerId, + hasSubscription: !!sub.stripeSubscriptionId, }, billingSuspended: store.billingSuspended, invoices: store.invoices.map((i) => ({ id: i.id, number: i.number, + description: i.description, amountCents: i.amountCents, periodStart: i.periodStart, periodEnd: i.periodEnd, @@ -74,35 +85,47 @@ export class BillingService { }; } - /** - * Crée (ou réutilise) le client Stripe du magasin et un lien Checkout - * d'abonnement ; l'envoie par e-mail au contact du magasin si demandé. - */ - async checkoutLink(storeId: string, sendEmail: boolean) { + /** Client Stripe du magasin, créé à la première demande. */ + private async ensureCustomer(storeId: string) { const store = await this.prisma.store.findUnique({ where: { id: storeId }, include: { subscription: true } }); if (!store) throw new NotFoundException('Magasin introuvable'); - if (store.subscription?.status === 'ACTIVE') throw new BadRequestException('Ce magasin a déjà un abonnement actif'); + if (store.subscription?.stripeCustomerId) return { store, customerId: store.subscription.stripeCustomerId }; + const customer = await this.stripe.customers.create({ + name: store.name, + email: store.contactEmail, + phone: store.contactPhone, + address: { line1: store.addressLine, postal_code: store.postalCode, city: store.city, country: 'FR' }, + metadata: { storeId: store.id, siret: store.siret }, + preferred_locales: ['fr'], + }); + await this.prisma.subscription.upsert({ + where: { storeId }, + create: { storeId, stripeCustomerId: customer.id }, + update: { stripeCustomerId: customer.id }, + }); + return { store, customerId: customer.id }; + } - let customerId = store.subscription?.stripeCustomerId; - if (!customerId) { - const customer = await this.stripe.customers.create({ - name: store.name, - email: store.contactEmail, - phone: store.contactPhone, - address: { line1: store.addressLine, postal_code: store.postalCode, city: store.city, country: 'FR' }, - metadata: { storeId: store.id, siret: store.siret }, - preferred_locales: ['fr'], - }); - customerId = customer.id; - await this.prisma.subscription.upsert({ - where: { storeId }, - create: { storeId, stripeCustomerId: customerId }, - update: { stripeCustomerId: customerId }, - }); + private async priceFor(plan: Plan, interval: BillingInterval) { + const key = PLANS[plan].lookupKey[interval]; + const price = (await this.stripe.prices.list({ lookup_keys: [key], active: true, limit: 1 })).data[0]; + if (!price) throw new ServiceUnavailableException(`Prix Stripe « ${key} » introuvable : lancer scripts/stripe-setup.ts`); + return price; + } + + /** + * Lien Checkout pour souscrire une formule (mensuelle ou annuelle), avec + * essai gratuit éventuel et codes promo ; envoyé par e-mail si demandé. + */ + async checkoutLink(storeId: string, opts: { plan: Plan; interval: BillingInterval; trial: boolean; sendEmail: boolean }) { + const { store, customerId } = await this.ensureCustomer(storeId); + if (store.subscription?.stripeSubscriptionId && store.subscription.status !== 'CANCELED') { + throw new BadRequestException('Ce magasin a déjà un abonnement : changez de formule depuis le portail client'); } - - const price = (await this.stripe.prices.list({ lookup_keys: [this.config.get('stripe.priceLookupKey')!], limit: 1 })).data[0]; - if (!price) throw new ServiceUnavailableException('Prix Stripe introuvable'); + // Un seul essai par magasin, même après résiliation. + const trialAllowed = opts.trial && !store.subscription?.trialEndsAt; + const price = await this.priceFor(opts.plan, opts.interval); + const def = PLANS[opts.plan]; const webUrl: string = this.config.get('webUrl')!; const session = await this.stripe.checkout.sessions.create({ @@ -110,38 +133,82 @@ export class BillingService { customer: customerId, line_items: [{ price: price.id, quantity: 1 }], payment_method_types: ['card', 'sepa_debit'], + allow_promotion_codes: true, locale: 'fr', client_reference_id: store.id, - subscription_data: { metadata: { storeId: store.id } }, + subscription_data: { + metadata: { storeId: store.id }, + ...(trialAllowed && { trial_period_days: TRIAL_DAYS }), + }, metadata: { storeId: store.id }, success_url: `${webUrl}/abonnement/merci/`, cancel_url: `${webUrl}/tarif/`, expires_at: Math.floor(Date.now() / 1000) + 24 * 3600, // 24 h, maximum autorisé par Stripe }); - if (sendEmail) { - const text = `Bonjour ${store.contactName},\n\nVoici le lien pour activer l'abonnement MonEspacePro de ${store.name} (10 € par mois, sans engagement, carte bancaire ou prélèvement SEPA) :\n${session.url}\n\nCe lien est valable 24 heures.\n\nMonEspacePro`; + const priceText = `${euros(def.priceCents[opts.interval])} ${opts.interval === 'YEAR' ? 'par an (2 mois offerts)' : 'par mois'}`; + if (opts.sendEmail) { + const text = `Bonjour ${store.contactName},\n\nVoici le lien pour activer la formule ${def.name} de MonEspacePro pour ${store.name} (${priceText}${trialAllowed ? `, ${TRIAL_DAYS} jours d'essai gratuit` : ''}, sans engagement) :\n${session.url}\n\nCe lien est valable 24 heures.\n\nMonEspacePro`; const html = emailLayout({ webUrl, - preheader: `Activez l'abonnement MonEspacePro de ${store.name} en quelques clics.`, - eyebrow: 'Abonnement', + preheader: `Activez la formule ${def.name} de MonEspacePro pour ${store.name}.`, + eyebrow: `Formule ${def.name}`, title: `Activez MonEspacePro pour ${store.name}`, paragraphs: [ `Bonjour ${esc(store.contactName)},`, - `Votre carte de fidélité est prête. Il ne reste qu'à activer l'abonnement de ${esc(store.name)} pour l'ouvrir à vos clients.`, + `Votre carte de fidélité est prête. Il ne reste qu'à activer la formule ${esc(def.name)} de ${esc(store.name)} pour l'ouvrir à vos clients.`, ], - cta: { label: 'Activer mon abonnement', url: session.url! }, + cta: { label: trialAllowed ? `Commencer l'essai gratuit de ${TRIAL_DAYS} jours` : 'Activer mon abonnement', url: session.url! }, details: [ - ['Formule', 'Carte de fidélité dématérialisée, 1 magasin'], - ['Prix', '10 € par mois — TVA non applicable, art. 293 B du CGI'], + ['Formule', `${esc(def.name)} — ${esc(def.tagline)}`], + ['Prix', `${priceText} — TVA non applicable, art. 293 B du CGI`], + ...(trialAllowed ? ([['Essai', `${TRIAL_DAYS} jours gratuits, aucun prélèvement avant la fin de l'essai`]] as [string, string][]) : []), ['Engagement', 'Aucun, résiliable à tout moment'], ['Paiement', 'Carte bancaire ou prélèvement SEPA, factures automatiques'], ], note: 'Ce lien est valable 24 heures. Passé ce délai, demandez-nous simplement un nouveau lien.', }); - await this.mail.send(store.contactEmail, `Activez l'abonnement MonEspacePro de ${store.name}`, text, html); + await this.mail.send(store.contactEmail, `Activez la formule ${def.name} de MonEspacePro`, text, html); } - return { url: session.url, expiresAt: new Date(session.expires_at * 1000), emailedTo: sendEmail ? store.contactEmail : null }; + return { + url: session.url, + expiresAt: new Date(session.expires_at * 1000), + emailedTo: opts.sendEmail ? store.contactEmail : null, + trial: trialAllowed, + }; + } + + /** + * Portail client Stripe : le commerçant change de formule, de moyen de + * paiement, résilie et retrouve ses factures Stripe, sans intervention. + */ + async portalLink(storeId: string, sendEmail: boolean) { + const { store, customerId } = await this.ensureCustomer(storeId); + const configuration: string = this.config.get('stripe.portalConfigId') || undefined!; + const webUrl: string = this.config.get('webUrl')!; + const session = await this.stripe.billingPortal.sessions.create({ + customer: customerId, + locale: 'fr', + return_url: `${webUrl}/`, + ...(configuration && { configuration }), + }); + if (sendEmail) { + const text = `Bonjour ${store.contactName},\n\nVoici l'accès à votre espace d'abonnement MonEspacePro (changer de formule, mettre à jour votre moyen de paiement, résilier) :\n${session.url}\n\nCe lien est personnel et expire rapidement : ne le partagez pas.\n\nMonEspacePro`; + const html = emailLayout({ + webUrl, + preheader: 'Gérez votre abonnement MonEspacePro.', + eyebrow: 'Abonnement', + title: 'Votre espace abonnement', + paragraphs: [ + `Bonjour ${esc(store.contactName)},`, + `Depuis cet espace sécurisé, vous pouvez changer de formule, mettre à jour votre carte bancaire ou votre IBAN, et résilier l'abonnement de ${esc(store.name)} à tout moment.`, + ], + cta: { label: 'Gérer mon abonnement', url: session.url }, + note: 'Ce lien est personnel et expire rapidement : ne le partagez pas.', + }); + await this.mail.send(store.contactEmail, 'Gérez votre abonnement MonEspacePro', text, html); + } + return { url: session.url, emailedTo: sendEmail ? store.contactEmail : null }; } // ── Webhook ──────────────────────────────────────────────── @@ -171,6 +238,9 @@ export class BillingService { case 'invoice.paid': await this.onInvoicePaid(event.data.object); break; + case 'customer.subscription.trial_will_end': + await this.onTrialWillEnd(event.data.object); + break; case 'invoice.payment_failed': await this.onPaymentFailed(event.data.object); break; @@ -186,15 +256,59 @@ export class BillingService { if (!storeId) return; const status = STATUS[sub.status] ?? 'INCOMPLETE'; const periodEnd = sub.current_period_end; - await this.prisma.subscription.upsert({ - where: { storeId }, - create: { storeId, stripeCustomerId: String(sub.customer), stripeSubscriptionId: sub.id, status, currentPeriodEnd: periodEnd ? new Date(periodEnd * 1000) : null }, - update: { stripeCustomerId: String(sub.customer), stripeSubscriptionId: sub.id, status, currentPeriodEnd: periodEnd ? new Date(periodEnd * 1000) : null }, - }); + // La formule se déduit du prix Stripe (lookup_key) : un changement fait + // depuis le portail client est donc repris automatiquement. + const price = sub.items.data[0]?.price; + const found = planFromLookupKey(price?.lookup_key); + if (!found && price) this.logger.warn(`Prix Stripe ${price.id} hors catalogue (lookup_key=${price.lookup_key}) : formule Essentiel appliquée`); + const data = { + stripeCustomerId: String(sub.customer), + stripeSubscriptionId: sub.id, + status, + plan: found?.plan ?? 'ESSENTIEL', + interval: found?.interval ?? (price?.recurring?.interval === 'year' ? 'YEAR' : 'MONTH'), + legacyPrice: found?.legacy ?? !found, + trialEndsAt: sub.trial_end ? new Date(sub.trial_end * 1000) : undefined, + cancelAtPeriodEnd: sub.cancel_at_period_end, + currentPeriodEnd: periodEnd ? new Date(periodEnd * 1000) : null, + } satisfies Prisma.SubscriptionUncheckedUpdateInput; + await this.prisma.subscription.upsert({ where: { storeId }, create: { storeId, ...data }, update: data }); if (status === 'ACTIVE') await this.reactivate(storeId); if (status === 'PAST_DUE' || status === 'CANCELED') await this.suspend(storeId, `abonnement ${sub.status}`); } + /** Stripe prévient 3 jours avant la fin de l'essai : on rappelle au commerçant ce qui va se passer. */ + private async onTrialWillEnd(sub: Stripe.Subscription) { + const storeId = sub.metadata.storeId; + if (!storeId || !sub.trial_end) return; + const store = await this.prisma.store.findUnique({ where: { id: storeId } }); + if (!store) return; + const found = planFromLookupKey(sub.items.data[0]?.price?.lookup_key); + const def = PLANS[found?.plan ?? 'ESSENTIEL']; + const interval = found?.interval ?? 'MONTH'; + const end = new Date(sub.trial_end * 1000).toLocaleDateString('fr-FR', { day: 'numeric', month: 'long', timeZone: 'Europe/Paris' }); + const webUrl: string = this.config.get('webUrl')!; + const portal = await this.portalLink(storeId, false); + const text = `Bonjour ${store.contactName},\n\nVotre essai gratuit de MonEspacePro se termine le ${end}. L'abonnement ${def.name} démarrera alors automatiquement (${euros(def.priceCents[interval])} ${interval === 'YEAR' ? 'par an' : 'par mois'}). Rien à faire si vous souhaitez continuer.\n\nChanger de formule ou résilier : ${portal.url}\n\nMonEspacePro`; + const html = emailLayout({ + webUrl, + preheader: `Votre essai se termine le ${end}.`, + eyebrow: 'Essai gratuit', + title: `Votre essai se termine le ${end}`, + paragraphs: [ + `Bonjour ${esc(store.contactName)},`, + `L'abonnement ${esc(def.name)} de ${esc(store.name)} démarrera automatiquement à la fin de l'essai. Rien à faire si vous souhaitez continuer.`, + ], + details: [ + ['Formule', esc(def.name)], + ['Prix', `${euros(def.priceCents[interval])} ${interval === 'YEAR' ? 'par an' : 'par mois'} — TVA non applicable, art. 293 B du CGI`], + ['Premier prélèvement', end], + ], + cta: { label: 'Changer de formule ou résilier', url: portal.url }, + }); + await this.mail.send(store.contactEmail, `Votre essai MonEspacePro se termine le ${end}`, text, html); + } + private async onPaymentFailed(invoice: Stripe.Invoice) { const storeId = await this.storeIdForCustomer(String(invoice.customer)); if (storeId) await this.suspend(storeId, `paiement de ${euros(invoice.amount_due)} refusé`); @@ -237,6 +351,11 @@ export class BillingService { const store = await this.prisma.store.findUniqueOrThrow({ where: { id: storeId } }); const period = si.lines.data[0]?.period; const paidAt = si.status_transitions?.paid_at ? new Date(si.status_transitions.paid_at * 1000) : new Date(); + // Libellé figé : formule et périodicité lues sur la ligne de la facture Stripe. + const found = planFromLookupKey(si.lines.data[0]?.price?.lookup_key); + const description = found + ? `Abonnement MonEspacePro — formule ${PLANS[found.plan].name}${found.legacy ? ' (tarif fondateur)' : ''}, ${found.interval === 'YEAR' ? 'annuel' : 'mensuel'}, 1 magasin` + : 'Abonnement MonEspacePro — carte de fidélité dématérialisée, 1 magasin'; // Numérotation continue : séquence globale, l'unicité en base empêche tout doublon. let invoice: Prisma.InvoiceGetPayload | null = null; @@ -256,6 +375,7 @@ export class BillingService { clientAddress: `${store.addressLine}\n${store.postalCode} ${store.city}`, clientSiret: store.siret.replace(/(\d{3})(\d{3})(\d{3})(\d{5})/, '$1 $2 $3 $4'), clientEmail: store.contactEmail, + description, periodStart: period ? new Date(period.start * 1000) : paidAt, periodEnd: period ? new Date(period.end * 1000) : paidAt, paidAt, @@ -319,6 +439,7 @@ export class BillingService { periodStart: inv.periodStart, periodEnd: inv.periodEnd, amountCents: inv.amountCents, + description: inv.description, issuer: this.config.get('issuer')!, client: { name: inv.clientName, address: inv.clientAddress, siret: inv.clientSiret, email: inv.clientEmail }, }); diff --git a/backend/src/billing/entitlements.service.ts b/backend/src/billing/entitlements.service.ts new file mode 100644 index 0000000..fe06714 --- /dev/null +++ b/backend/src/billing/entitlements.service.ts @@ -0,0 +1,57 @@ +import { ForbiddenException, Global, Injectable, Module } from '@nestjs/common'; +import { Plan } from '@prisma/client'; +import { PrismaService } from '../prisma/prisma.service'; +import { Feature, hasFeature, PLANS } from './plans'; + +/** + * Droits d'un magasin selon sa formule. Un magasin sans abonnement actif + * (brouillon, essai expiré, impayé) a les droits de la formule Essentiel : + * on ne casse jamais ce qui fonctionne, on bloque seulement les fonctions Pro. + */ +@Injectable() +export class EntitlementsService { + constructor(private prisma: PrismaService) {} + + async planOf(storeId: string): Promise { + const sub = await this.prisma.subscription.findUnique({ where: { storeId }, select: { plan: true, status: true } }); + return sub && sub.status === 'ACTIVE' ? sub.plan : 'ESSENTIEL'; + } + + async can(storeId: string, feature: Feature) { + return hasFeature(await this.planOf(storeId), feature); + } + + /** Erreur « 403 PLAN_REQUIRED » que l'admin et l'app Pro savent afficher. */ + async require(storeId: string, feature: Feature) { + const plan = await this.planOf(storeId); + if (!hasFeature(plan, feature)) { + const needed = (['PRO', 'RESEAU'] as const).find((p) => hasFeature(p, feature))!; + throw new ForbiddenException({ + statusCode: 403, + code: 'PLAN_REQUIRED', + requiredPlan: needed, + message: `Fonction disponible avec la formule ${PLANS[needed].name}.`, + }); + } + } + + /** Nombre d'employés actifs autorisé ; `adding` = 1 pour une création ou une réactivation. */ + async requireStaffSlot(storeId: string) { + const plan = await this.planOf(storeId); + const max = PLANS[plan].limits.maxStaff; + if (max === null) return; + const active = await this.prisma.staffUser.count({ where: { storeId, active: true } }); + if (active >= max) { + throw new ForbiddenException({ + statusCode: 403, + code: 'PLAN_REQUIRED', + requiredPlan: 'PRO', + message: `La formule ${PLANS[plan].name} est limitée à ${max} employés actifs. Désactivez un compte ou passez à la formule Pro.`, + }); + } + } +} + +@Global() +@Module({ providers: [EntitlementsService], exports: [EntitlementsService] }) +export class EntitlementsModule {} diff --git a/backend/src/billing/invoice-pdf.ts b/backend/src/billing/invoice-pdf.ts index c74eb5c..9d29469 100644 --- a/backend/src/billing/invoice-pdf.ts +++ b/backend/src/billing/invoice-pdf.ts @@ -7,6 +7,7 @@ export interface InvoicePdfData { periodStart: Date; periodEnd: Date; amountCents: number; + description: string; issuer: { name: string; tradeName: string; siret: string; address: string; email: string }; client: { name: string; address: string; siret: string; email: string }; } @@ -18,7 +19,6 @@ const MUTED = '#5F5E56'; const date = (d: Date) => d.toLocaleDateString('fr-FR', { day: '2-digit', month: '2-digit', year: 'numeric', timeZone: 'Europe/Paris' }); const euros = (cents: number) => (cents / 100).toLocaleString('fr-FR', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).replace(/ | /g, ' ') + ' €'; -const month = (d: Date) => d.toLocaleDateString('fr-FR', { month: 'long', year: 'numeric', timeZone: 'Europe/Paris' }); /** * Facture A4 conforme aux mentions obligatoires (art. L441-9 du Code de @@ -76,7 +76,7 @@ export function renderInvoicePdf(d: InvoicePdfData): Promise { .text('Total HT', left + width - 90, y + 8, { width: 80, align: 'right' }); y += 34; doc.fillColor(INK).font('Helvetica').fontSize(10) - .text(`Abonnement MonEspacePro — carte de fidélité dématérialisée, 1 magasin\nPériode : ${month(d.periodStart)} (du ${date(d.periodStart)} au ${date(d.periodEnd)})`, left + 10, y, { width: width - 250 }) + .text(`${d.description}\nPériode : du ${date(d.periodStart)} au ${date(d.periodEnd)}`, left + 10, y, { width: width - 250 }) .text('1', left + width - 230, y, { width: 40, align: 'right' }) .text(euros(d.amountCents), left + width - 180, y, { width: 90, align: 'right' }) .text(euros(d.amountCents), left + width - 90, y, { width: 80, align: 'right' }); diff --git a/backend/src/billing/plans.ts b/backend/src/billing/plans.ts new file mode 100644 index 0000000..e2ee71f --- /dev/null +++ b/backend/src/billing/plans.ts @@ -0,0 +1,102 @@ +import { BillingInterval, Plan } from '@prisma/client'; + +/** + * Catalogue des formules : la seule source de vérité sur ce que chaque + * formule autorise. Les prix sont créés dans Stripe par + * `scripts/stripe-setup.ts` avec les mêmes clés (lookup_key). + */ + +export type Feature = + | 'campaigns' // notifications push de campagne + | 'inactiveReminders' // relance automatique des clients inactifs + | 'birthday' // offre d'anniversaire + | 'googleReview' // collecte d'avis Google + | 'referral' // parrainage + | 'advancedStats' // statistiques avancées + | 'csvExport' // export CSV clients / opérations + | 'whiteLabel' // retrait de « Propulsé par MonEspacePro » + | 'multiStore'; // carte commune à plusieurs magasins + +export interface PlanDefinition { + plan: Plan; + name: string; + tagline: string; + /** Prix TTC = HT (franchise de TVA), en centimes. */ + priceCents: Record; + lookupKey: Record; + features: Feature[]; + limits: { maxStaff: number | null }; +} + +const PRO_FEATURES: Feature[] = [ + 'campaigns', + 'inactiveReminders', + 'birthday', + 'googleReview', + 'referral', + 'advancedStats', + 'csvExport', + 'whiteLabel', +]; + +export const PLANS: Record = { + ESSENTIEL: { + plan: 'ESSENTIEL', + name: 'Essentiel', + tagline: 'La carte de fidélité dans le Wallet de vos clients', + priceCents: { MONTH: 1900, YEAR: 19000 }, + lookupKey: { MONTH: 'mep_essentiel_mensuel', YEAR: 'mep_essentiel_annuel' }, + features: [], + limits: { maxStaff: 3 }, + }, + PRO: { + plan: 'PRO', + name: 'Pro', + tagline: 'Faites revenir vos clients', + priceCents: { MONTH: 3900, YEAR: 39000 }, + lookupKey: { MONTH: 'mep_pro_mensuel', YEAR: 'mep_pro_annuel' }, + features: PRO_FEATURES, + limits: { maxStaff: null }, + }, + RESEAU: { + plan: 'RESEAU', + name: 'Réseau', + tagline: 'Plusieurs magasins, une seule carte', + priceCents: { MONTH: 2900, YEAR: 29000 }, + lookupKey: { MONTH: 'mep_reseau_mensuel', YEAR: 'mep_reseau_annuel' }, + features: [...PRO_FEATURES, 'multiStore'], + limits: { maxStaff: null }, + }, +}; + +/** Ancien prix unique à 10 €/mois : traité comme Essentiel (tarif fondateur). */ +export const LEGACY_LOOKUP_KEYS = ['mep_magasin_mensuel']; + +export const TRIAL_DAYS = 30; + +export function planFromLookupKey(key: string | null | undefined): { plan: Plan; interval: BillingInterval; legacy: boolean } | null { + if (!key) return null; + if (LEGACY_LOOKUP_KEYS.includes(key)) return { plan: 'ESSENTIEL', interval: 'MONTH', legacy: true }; + for (const def of Object.values(PLANS)) { + for (const interval of ['MONTH', 'YEAR'] as const) { + if (def.lookupKey[interval] === key) return { plan: def.plan, interval, legacy: false }; + } + } + return null; +} + +export function hasFeature(plan: Plan, feature: Feature) { + return PLANS[plan].features.includes(feature); +} + +/** Catalogue lisible par l'admin (et plus tard la page Tarif). */ +export function publicCatalog() { + return Object.values(PLANS).map((p) => ({ + plan: p.plan, + name: p.name, + tagline: p.tagline, + priceCents: p.priceCents, + features: p.features, + limits: p.limits, + })); +} diff --git a/backend/src/config/configuration.ts b/backend/src/config/configuration.ts index a2019db..34a6183 100644 --- a/backend/src/config/configuration.ts +++ b/backend/src/config/configuration.ts @@ -29,7 +29,8 @@ export default () => ({ stripe: { secretKey: process.env.STRIPE_SECRET_KEY ?? '', webhookSecret: process.env.STRIPE_WEBHOOK_SECRET ?? '', - priceLookupKey: process.env.STRIPE_PRICE_LOOKUP_KEY || 'mep_magasin_mensuel', + /** Configuration du portail client (créée par scripts/stripe-setup.ts). */ + portalConfigId: process.env.STRIPE_PORTAL_CONFIG_ID ?? '', }, /** Émetteur des factures (mentions obligatoires). */ issuer: { diff --git a/backend/src/enrollment/enrollment.service.ts b/backend/src/enrollment/enrollment.service.ts index 5982786..77b634f 100644 --- a/backend/src/enrollment/enrollment.service.ts +++ b/backend/src/enrollment/enrollment.service.ts @@ -40,7 +40,7 @@ export class EnrollmentService { findStore(slug: string) { return this.prisma.store.findUnique({ where: { slug }, - include: { cardDesign: { include: { rewards: { where: { active: true }, orderBy: { cost: 'asc' } } } } }, + include: CARD_WITH_CONTEXT.store.include, }); } diff --git a/backend/src/enrollment/pages.ts b/backend/src/enrollment/pages.ts index 07ab18e..fe2c442 100644 --- a/backend/src/enrollment/pages.ts +++ b/backend/src/enrollment/pages.ts @@ -1,9 +1,16 @@ -import type { CardDesign, Reward, Store } from '@prisma/client'; +import type { CardDesign, Plan, Reward, Store, SubscriptionStatus } from '@prisma/client'; +import { hasFeature } from '../billing/plans'; import { nextRewardText, type CardWithContext } from '../wallet/wallet.types'; /** Pages publiques (clients finaux), rendues côté serveur aux couleurs du magasin. */ -export type StoreWithDesign = Store & { cardDesign: (CardDesign & { rewards: Reward[] }) | null }; +export type StoreWithDesign = Store & { + cardDesign: (CardDesign & { rewards: Reward[] }) | null; + subscription?: { plan: Plan; status: SubscriptionStatus } | null; +}; + +/** Formule Pro et plus : la mention « Propulsé par MonEspacePro » disparaît. */ +const whiteLabel = (s: StoreWithDesign) => s.subscription?.status === 'ACTIVE' && hasFeature(s.subscription.plan, 'whiteLabel'); export type Platform = 'apple' | 'google' | 'other'; export function escapeHtml(value: unknown) { @@ -128,7 +135,7 @@ ${body}
-${SYMBOL(14)}Propulsé par MonEspacePro +${whiteLabel(store) ? "" : `${SYMBOL(14)}Propulsé par MonEspacePro`}
${script ? `` : ''} diff --git a/backend/src/staff/staff.service.ts b/backend/src/staff/staff.service.ts index d012325..04db58e 100644 --- a/backend/src/staff/staff.service.ts +++ b/backend/src/staff/staff.service.ts @@ -4,6 +4,7 @@ import * as argon2 from 'argon2'; import { randomInt } from 'crypto'; import { PrismaService } from '../prisma/prisma.service'; import { CreateStaffDto, UpdateStaffDto } from './dto/staff.dto'; +import { EntitlementsService } from '../billing/entitlements.service'; const PUBLIC_FIELDS = { id: true, @@ -24,7 +25,10 @@ function provisionalPassword(length = 12) { @Injectable() export class StaffService { - constructor(private prisma: PrismaService) {} + constructor( + private prisma: PrismaService, + private entitlements: EntitlementsService, + ) {} async list(storeId: string) { await this.ensureStore(storeId); @@ -38,6 +42,7 @@ export class StaffService { /** Le mot de passe provisoire n'est renvoyé qu'ici, une seule fois ; il n'est stocké que haché. */ async create(storeId: string, dto: CreateStaffDto) { await this.ensureStore(storeId); + await this.entitlements.requireStaffSlot(storeId); const password = provisionalPassword(); try { const staff = await this.prisma.staffUser.create({ @@ -61,6 +66,7 @@ export class StaffService { async update(storeId: string, id: string, dto: UpdateStaffDto) { const current = await this.find(storeId, id); + if (dto.active === true && !current.active) await this.entitlements.requireStaffSlot(storeId); // Désactivation ou changement de rôle : les sessions ouvertes sont révoquées. const revoke = (dto.active === false && current.active) || (dto.role !== undefined && dto.role !== current.role); return this.prisma.staffUser.update({ diff --git a/backend/src/stores/stores.service.ts b/backend/src/stores/stores.service.ts index 7462ee1..4db6e39 100644 --- a/backend/src/stores/stores.service.ts +++ b/backend/src/stores/stores.service.ts @@ -29,7 +29,7 @@ export class StoresService { this.prisma.store.findMany({ where, orderBy: { createdAt: 'desc' }, - include: { subscription: { select: { status: true } }, _count: { select: { cards: true } } }, + include: { subscription: { select: { status: true, plan: true, stripeSubscriptionId: true } }, _count: { select: { cards: true } } }, }), this.prisma.store.groupBy({ by: ['status'], _count: true }), ]); @@ -38,6 +38,7 @@ export class StoresService { ...this.present(s), customers: _count.cards, subscriptionStatus: subscription?.status ?? null, + plan: subscription?.stripeSubscriptionId && subscription.status !== 'CANCELED' ? subscription.plan : null, })), counts: Object.fromEntries(byStatus.map((g) => [g.status, g._count])), }; diff --git a/backend/src/wallet/wallet.types.ts b/backend/src/wallet/wallet.types.ts index e1b9514..7f10695 100644 --- a/backend/src/wallet/wallet.types.ts +++ b/backend/src/wallet/wallet.types.ts @@ -3,7 +3,12 @@ import { Prisma } from '@prisma/client'; /** Tout ce qu'il faut pour dessiner une carte, chargé en une requête. */ export const CARD_WITH_CONTEXT = { customer: true, - store: { include: { cardDesign: { include: { rewards: { where: { active: true }, orderBy: { cost: 'asc' } } } } } }, + store: { + include: { + cardDesign: { include: { rewards: { where: { active: true }, orderBy: { cost: 'asc' } } } }, + subscription: { select: { plan: true, status: true } }, + }, + }, } satisfies Prisma.LoyaltyCardInclude; export type CardWithContext = Prisma.LoyaltyCardGetPayload<{ include: typeof CARD_WITH_CONTEXT }>;
FactureObjet Période Montant Statut
{i.number}{i.description.replace('Abonnement MonEspacePro — ', '')} {day(i.periodStart)} → {day(i.periodEnd)} {euros(i.amountCents)} {i.paidAt ? Payée le {day(i.paidAt)} : Impayée} {s.city} {s.customers}{subscriptionLabel(s.subscriptionStatus)}{subscriptionLabel(s.subscriptionStatus)}{s.plan && · {PLAN_LABEL[s.plan]}} {new Date(s.createdAt).toLocaleDateString('fr-FR', { day: 'numeric', month: 'short', year: 'numeric' })}