Socle des formules d'abonnement (Essentiel 19 €, Pro 39 €, Réseau 29 €/magasin)
- 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 <noreply@anthropic.com>
This commit is contained in:
parent
877dd481ea
commit
fe6874458d
19 changed files with 707 additions and 85 deletions
|
|
@ -131,6 +131,9 @@ export const api = {
|
||||||
// ── Types partagés avec l'API ─────────────────────────────────
|
// ── Types partagés avec l'API ─────────────────────────────────
|
||||||
export type StoreStatus = 'DRAFT' | 'ACTIVE' | 'SUSPENDED' | 'CLOSED';
|
export type StoreStatus = 'DRAFT' | 'ACTIVE' | 'SUSPENDED' | 'CLOSED';
|
||||||
export type SubscriptionStatus = 'INCOMPLETE' | 'ACTIVE' | 'PAST_DUE' | 'CANCELED';
|
export type SubscriptionStatus = 'INCOMPLETE' | 'ACTIVE' | 'PAST_DUE' | 'CANCELED';
|
||||||
|
export type Plan = 'ESSENTIEL' | 'PRO' | 'RESEAU';
|
||||||
|
export type BillingInterval = 'MONTH' | 'YEAR';
|
||||||
|
export const PLAN_LABEL: Record<Plan, string> = { ESSENTIEL: 'Essentiel', PRO: 'Pro', RESEAU: 'Réseau' };
|
||||||
|
|
||||||
export interface Store {
|
export interface Store {
|
||||||
id: string;
|
id: string;
|
||||||
|
|
@ -153,11 +156,12 @@ export interface Store {
|
||||||
export interface StoreListItem extends Store {
|
export interface StoreListItem extends Store {
|
||||||
customers: number;
|
customers: number;
|
||||||
subscriptionStatus: SubscriptionStatus | null;
|
subscriptionStatus: SubscriptionStatus | null;
|
||||||
|
plan: Plan | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface StoreDetail extends Store {
|
export interface StoreDetail extends Store {
|
||||||
counts: { cards: number; staff: number; transactions: number };
|
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. */
|
/** Lien encodé dans le QR d'inscription. */
|
||||||
enrollUrl: string;
|
enrollUrl: string;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,32 @@
|
||||||
import { useCallback, useEffect, useState } from 'react';
|
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<BillingInterval, number>;
|
||||||
|
features: string[];
|
||||||
|
limits: { maxStaff: number | null };
|
||||||
|
}
|
||||||
|
|
||||||
interface Billing {
|
interface Billing {
|
||||||
testMode: boolean;
|
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;
|
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<SubscriptionStatus, [string, string]> = {
|
const STATUS: Record<SubscriptionStatus, [string, string]> = {
|
||||||
|
|
@ -15,25 +36,42 @@ const STATUS: Record<SubscriptionStatus, [string, string]> = {
|
||||||
CANCELED: ['Résilié', 'CLOSED'],
|
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<string, string> = {
|
||||||
|
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' });
|
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 }) {
|
export function BillingTab({ storeId, contactEmail, onChange }: { storeId: string; contactEmail: string; onChange: () => void }) {
|
||||||
const [data, setData] = useState<Billing | null>(null);
|
const [data, setData] = useState<Billing | null>(null);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(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 [busy, setBusy] = useState(false);
|
||||||
|
const [plan, setPlan] = useState<Plan>('PRO');
|
||||||
|
const [interval, setInterval] = useState<BillingInterval>('MONTH');
|
||||||
|
const [trial, setTrial] = useState(true);
|
||||||
|
|
||||||
const reload = useCallback(() => {
|
const reload = useCallback(() => {
|
||||||
api.get<Billing>(`/api/admin/stores/${storeId}/billing`).then(setData).catch((e) => setError(e.message));
|
api.get<Billing>(`/api/admin/stores/${storeId}/billing`).then(setData).catch((e) => setError(e.message));
|
||||||
}, [storeId]);
|
}, [storeId]);
|
||||||
useEffect(reload, [reload]);
|
useEffect(reload, [reload]);
|
||||||
|
|
||||||
async function createLink(sendEmail: boolean) {
|
async function run(label: string, path: string, body: object) {
|
||||||
setBusy(true);
|
setBusy(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
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();
|
reload();
|
||||||
onChange();
|
onChange();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
|
@ -45,7 +83,10 @@ export function BillingTab({ storeId, contactEmail, onChange }: { storeId: strin
|
||||||
|
|
||||||
if (!data) return error ? <div className="alert error">{error}</div> : <p className="muted">Chargement…</p>;
|
if (!data) return error ? <div className="alert error">{error}</div> : <p className="muted">Chargement…</p>;
|
||||||
const sub = data.subscription;
|
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 (
|
return (
|
||||||
<>
|
<>
|
||||||
|
|
@ -56,35 +97,101 @@ export function BillingTab({ storeId, contactEmail, onChange }: { storeId: strin
|
||||||
<div className="row between">
|
<div className="row between">
|
||||||
<div>
|
<div>
|
||||||
<h2>Abonnement</h2>
|
<h2>Abonnement</h2>
|
||||||
<p className="muted" style={{ margin: 0 }}>10 € par mois, sans engagement — carte bancaire ou prélèvement SEPA.</p>
|
<p className="muted" style={{ margin: 0 }}>
|
||||||
|
{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.'}
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<span className={`badge ${sub ? STATUS[sub.status][1] : 'DRAFT'}`}>{sub ? STATUS[sub.status][0] : 'Aucun abonnement'}</span>
|
<span className={`badge ${sub ? STATUS[sub.status][1] : 'DRAFT'}`}>{sub ? STATUS[sub.status][0] : 'Aucun abonnement'}</span>
|
||||||
</div>
|
</div>
|
||||||
{sub?.currentPeriodEnd && active && <p style={{ margin: 0 }}>Prochain prélèvement le <strong>{day(sub.currentPeriodEnd)}</strong>.</p>}
|
{trialing && <div className="alert ok">Essai gratuit jusqu'au <strong>{day(sub!.trialEndsAt!)}</strong> : aucun prélèvement avant cette date.</div>}
|
||||||
{data.billingSuspended && (
|
{sub?.cancelAtPeriodEnd && sub.currentPeriodEnd && (
|
||||||
<div className="alert warn">Magasin suspendu automatiquement pour impayé. Il sera réactivé dès que le paiement passera.</div>
|
<div className="alert warn">Résiliation demandée : l'abonnement s'arrête le <strong>{day(sub.currentPeriodEnd)}</strong>.</div>
|
||||||
)}
|
)}
|
||||||
{!active && (
|
{sub?.currentPeriodEnd && sub.status === 'ACTIVE' && !sub.cancelAtPeriodEnd && !trialing && (
|
||||||
|
<p style={{ margin: 0 }}>Prochain prélèvement le <strong>{day(sub.currentPeriodEnd)}</strong>.</p>
|
||||||
|
)}
|
||||||
|
{data.billingSuspended && <div className="alert warn">Magasin suspendu automatiquement pour impayé. Il sera réactivé dès que le paiement passera.</div>}
|
||||||
|
|
||||||
|
{current && (
|
||||||
<div className="row" style={{ gap: 8 }}>
|
<div className="row" style={{ gap: 8 }}>
|
||||||
<button className="btn" disabled={busy} onClick={() => createLink(true)}>Envoyer le lien d'abonnement à {contactEmail}</button>
|
<button className="btn" disabled={busy} onClick={() => run('Espace abonnement', `/api/admin/stores/${storeId}/billing/portal-link`, { sendEmail: true })}>
|
||||||
<button className="btn secondary" disabled={busy} onClick={() => createLink(false)}>Créer le lien sans l'envoyer</button>
|
Envoyer l'espace abonnement à {contactEmail}
|
||||||
</div>
|
</button>
|
||||||
)}
|
<button className="btn secondary" disabled={busy} onClick={() => run('Espace abonnement', `/api/admin/stores/${storeId}/billing/portal-link`, { sendEmail: false })}>
|
||||||
{link && (
|
Ouvrir l'espace abonnement
|
||||||
<div className="alert ok">
|
</button>
|
||||||
{link.emailedTo ? <>Lien envoyé à <strong>{link.emailedTo}</strong>. </> : null}
|
<span className="muted" style={{ fontSize: 14 }}>Changer de formule, de moyen de paiement, résilier.</span>
|
||||||
Valable 24 h :{' '}
|
|
||||||
<a href={link.url} target="_blank" rel="noreferrer" style={{ wordBreak: 'break-all' }}>{link.url}</a>
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
{canSubscribe && (
|
||||||
|
<section className="card" style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
|
||||||
|
<div className="row between">
|
||||||
|
<h2>Choisir une formule</h2>
|
||||||
|
<div role="group" aria-label="Périodicité" className="row" style={{ gap: 8 }}>
|
||||||
|
<button type="button" className="chip" aria-pressed={interval === 'MONTH'} onClick={() => setInterval('MONTH')}>Mensuel</button>
|
||||||
|
<button type="button" className="chip" aria-pressed={interval === 'YEAR'} onClick={() => setInterval('YEAR')}>Annuel — 2 mois offerts</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="mode-cards" role="radiogroup" aria-label="Formule">
|
||||||
|
{data.catalog.map((c) => (
|
||||||
|
<label key={c.plan} className="mode-card" style={{ flexDirection: 'column', gap: 8 }}>
|
||||||
|
<span className="row" style={{ gap: 10 }}>
|
||||||
|
<input type="radio" name="plan" checked={plan === c.plan} onChange={() => setPlan(c.plan)} />
|
||||||
|
<strong style={{ fontSize: 18 }}>{c.name}</strong>
|
||||||
|
{c.plan === 'PRO' && <span className="badge ACTIVE" style={{ height: 22 }}>Conseillée</span>}
|
||||||
|
</span>
|
||||||
|
<span style={{ fontSize: 24, fontWeight: 800 }}>
|
||||||
|
{euros(c.priceCents[interval])}
|
||||||
|
<span className="muted" style={{ fontSize: 14, fontWeight: 500 }}> / {interval === 'YEAR' ? 'an' : 'mois'}{c.plan === 'RESEAU' ? ' / magasin' : ''}</span>
|
||||||
|
</span>
|
||||||
|
<span className="muted" style={{ fontSize: 14 }}>{c.tagline}</span>
|
||||||
|
<ul style={{ margin: 0, paddingLeft: 18, fontSize: 14, lineHeight: 1.6 }}>
|
||||||
|
<li>{c.limits.maxStaff ? `${c.limits.maxStaff} employés` : 'Employés illimités'}</li>
|
||||||
|
{c.features.length === 0 && <li>Carte Wallet, points ou tampons, récompenses, mises à jour en direct</li>}
|
||||||
|
{c.features.map((f) => <li key={f}>{FEATURE_LABEL[f] ?? f}</li>)}
|
||||||
|
</ul>
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<label className="row" style={{ gap: 10 }}>
|
||||||
|
<input type="checkbox" checked={trial && !trialUsed} disabled={trialUsed} onChange={(e) => setTrial(e.target.checked)} />
|
||||||
|
<span>
|
||||||
|
Offrir {data.trialDays} jours d'essai gratuit
|
||||||
|
{trialUsed && <span className="muted"> (déjà utilisé par ce magasin)</span>}
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
<p className="muted" style={{ margin: 0, fontSize: 14 }}>
|
||||||
|
Le commerçant pourra saisir un code promo sur la page de paiement (codes à créer dans Stripe → Coupons).
|
||||||
|
</p>
|
||||||
|
<div className="row" style={{ gap: 8 }}>
|
||||||
|
<button className="btn" disabled={busy} onClick={() => run("Lien d'abonnement", `/api/admin/stores/${storeId}/billing/checkout-link`, { plan, interval, trial: trial && !trialUsed, sendEmail: true })}>
|
||||||
|
Envoyer le lien à {contactEmail}
|
||||||
|
</button>
|
||||||
|
<button className="btn secondary" disabled={busy} onClick={() => run("Lien d'abonnement", `/api/admin/stores/${storeId}/billing/checkout-link`, { plan, interval, trial: trial && !trialUsed, sendEmail: false })}>
|
||||||
|
Créer le lien sans l'envoyer
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{link && (
|
||||||
|
<div className="alert ok">
|
||||||
|
{link.label} {link.emailedTo ? <>envoyé à <strong>{link.emailedTo}</strong>. </> : 'créé. '}
|
||||||
|
<a href={link.url} target="_blank" rel="noreferrer" style={{ wordBreak: 'break-all' }}>{link.url}</a>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
<div className="table-wrap">
|
<div className="table-wrap">
|
||||||
<div className="table-scroll">
|
<div className="table-scroll">
|
||||||
<table style={{ minWidth: 640 }}>
|
<table style={{ minWidth: 720 }}>
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th scope="col" style={{ paddingLeft: 24 }}>Facture</th>
|
<th scope="col" style={{ paddingLeft: 24 }}>Facture</th>
|
||||||
|
<th scope="col">Objet</th>
|
||||||
<th scope="col">Période</th>
|
<th scope="col">Période</th>
|
||||||
<th scope="col" className="num">Montant</th>
|
<th scope="col" className="num">Montant</th>
|
||||||
<th scope="col">Statut</th>
|
<th scope="col">Statut</th>
|
||||||
|
|
@ -95,6 +202,7 @@ export function BillingTab({ storeId, contactEmail, onChange }: { storeId: strin
|
||||||
{data.invoices.map((i) => (
|
{data.invoices.map((i) => (
|
||||||
<tr key={i.id}>
|
<tr key={i.id}>
|
||||||
<td style={{ paddingLeft: 24, fontWeight: 600 }}>{i.number}</td>
|
<td style={{ paddingLeft: 24, fontWeight: 600 }}>{i.number}</td>
|
||||||
|
<td style={{ fontSize: 14 }}>{i.description.replace('Abonnement MonEspacePro — ', '')}</td>
|
||||||
<td>{day(i.periodStart)} → {day(i.periodEnd)}</td>
|
<td>{day(i.periodStart)} → {day(i.periodEnd)}</td>
|
||||||
<td className="num">{euros(i.amountCents)}</td>
|
<td className="num">{euros(i.amountCents)}</td>
|
||||||
<td>{i.paidAt ? <span className="badge ACTIVE">Payée le {day(i.paidAt)}</span> : <span className="badge SUSPENDED">Impayée</span>}</td>
|
<td>{i.paidAt ? <span className="badge ACTIVE">Payée le {day(i.paidAt)}</span> : <span className="badge SUSPENDED">Impayée</span>}</td>
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
import { useCallback, useEffect, useState } from 'react';
|
import { useCallback, useEffect, useState } from 'react';
|
||||||
import { Link, NavLink, Navigate, Route, Routes, useParams } from 'react-router-dom';
|
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 { StatusBadge } from '../components/Layout';
|
||||||
import { StoreForm } from '../components/StoreForm';
|
import { StoreForm } from '../components/StoreForm';
|
||||||
import { CardWizard } from './CardWizard';
|
import { CardWizard } from './CardWizard';
|
||||||
|
|
@ -46,6 +46,11 @@ export function StorePage() {
|
||||||
<div className="row" style={{ gap: 12 }}>
|
<div className="row" style={{ gap: 12 }}>
|
||||||
<h1>{store.name}</h1>
|
<h1>{store.name}</h1>
|
||||||
<StatusBadge status={store.status} />
|
<StatusBadge status={store.status} />
|
||||||
|
{store.subscription?.stripeSubscriptionId && store.subscription.status !== 'CANCELED' && (
|
||||||
|
<NavLink to="facturation" className="badge DRAFT" style={{ textDecoration: 'none' }} title="Formule d'abonnement">
|
||||||
|
{PLAN_LABEL[store.subscription.plan]}
|
||||||
|
</NavLink>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<p className="muted" style={{ margin: 0 }}>
|
<p className="muted" style={{ margin: 0 }}>
|
||||||
{store.city} · {store.counts.cards} clients · {store.counts.staff} employés
|
{store.city} · {store.counts.cards} clients · {store.counts.staff} employés
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
import { Link } from 'react-router-dom';
|
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';
|
import { STATUS_LABEL, StatusBadge } from '../components/Layout';
|
||||||
|
|
||||||
const FILTERS: (StoreStatus | 'ALL')[] = ['ALL', 'DRAFT', 'ACTIVE', 'SUSPENDED', 'CLOSED'];
|
const FILTERS: (StoreStatus | 'ALL')[] = ['ALL', 'DRAFT', 'ACTIVE', 'SUSPENDED', 'CLOSED'];
|
||||||
|
|
@ -101,7 +101,7 @@ export function StoresPage() {
|
||||||
<td>{s.city}</td>
|
<td>{s.city}</td>
|
||||||
<td><StatusBadge status={s.status} /></td>
|
<td><StatusBadge status={s.status} /></td>
|
||||||
<td className="num">{s.customers}</td>
|
<td className="num">{s.customers}</td>
|
||||||
<td>{subscriptionLabel(s.subscriptionStatus)}</td>
|
<td>{subscriptionLabel(s.subscriptionStatus)}{s.plan && <span className="muted" style={{ fontSize: 14 }}> · {PLAN_LABEL[s.plan]}</span>}</td>
|
||||||
<td className="muted">{new Date(s.createdAt).toLocaleDateString('fr-FR', { day: 'numeric', month: 'short', year: 'numeric' })}</td>
|
<td className="muted">{new Date(s.createdAt).toLocaleDateString('fr-FR', { day: 'numeric', month: 'short', year: 'numeric' })}</td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
|
|
|
||||||
16
backend/prisma/manual-migrations/2026-10-07-formules.sql
Normal file
16
backend/prisma/manual-migrations/2026-10-07-formules.sql
Normal file
|
|
@ -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;
|
||||||
|
|
@ -201,6 +201,18 @@ model AppleRegistration {
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Facturation ───────────────────────────────────────────────
|
// ── Facturation ───────────────────────────────────────────────
|
||||||
|
/// Formule d'abonnement (catalogue : src/billing/plans.ts).
|
||||||
|
enum Plan {
|
||||||
|
ESSENTIEL
|
||||||
|
PRO
|
||||||
|
RESEAU
|
||||||
|
}
|
||||||
|
|
||||||
|
enum BillingInterval {
|
||||||
|
MONTH
|
||||||
|
YEAR
|
||||||
|
}
|
||||||
|
|
||||||
enum SubscriptionStatus {
|
enum SubscriptionStatus {
|
||||||
INCOMPLETE
|
INCOMPLETE
|
||||||
ACTIVE
|
ACTIVE
|
||||||
|
|
@ -215,6 +227,13 @@ model Subscription {
|
||||||
stripeCustomerId String? @unique
|
stripeCustomerId String? @unique
|
||||||
stripeSubscriptionId String? @unique
|
stripeSubscriptionId String? @unique
|
||||||
status SubscriptionStatus @default(INCOMPLETE)
|
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?
|
currentPeriodEnd DateTime?
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
}
|
}
|
||||||
|
|
@ -228,6 +247,8 @@ model Invoice {
|
||||||
store Store @relation(fields: [storeId], references: [id])
|
store Store @relation(fields: [storeId], references: [id])
|
||||||
stripeInvoiceId String? @unique
|
stripeInvoiceId String? @unique
|
||||||
amountCents Int
|
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).
|
/// Identité du client figée à l'émission (une facture ne change plus).
|
||||||
clientName String
|
clientName String
|
||||||
clientAddress String @db.Text
|
clientAddress String @db.Text
|
||||||
|
|
|
||||||
139
backend/scripts/stripe-setup.ts
Normal file
139
backend/scripts/stripe-setup.ts
Normal file
|
|
@ -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);
|
||||||
|
});
|
||||||
|
|
@ -11,6 +11,7 @@ import { EnrollmentModule } from './enrollment/enrollment.module';
|
||||||
import { CounterModule } from './counter/counter.module';
|
import { CounterModule } from './counter/counter.module';
|
||||||
import { ContactModule } from './contact/contact.controller';
|
import { ContactModule } from './contact/contact.controller';
|
||||||
import { BillingModule } from './billing/billing.controller';
|
import { BillingModule } from './billing/billing.controller';
|
||||||
|
import { EntitlementsModule } from './billing/entitlements.service';
|
||||||
import { WalletModule } from './wallet/wallet.module';
|
import { WalletModule } from './wallet/wallet.module';
|
||||||
import { HealthController } from './health.controller';
|
import { HealthController } from './health.controller';
|
||||||
|
|
||||||
|
|
@ -27,6 +28,7 @@ import { HealthController } from './health.controller';
|
||||||
CounterModule,
|
CounterModule,
|
||||||
ContactModule,
|
ContactModule,
|
||||||
BillingModule,
|
BillingModule,
|
||||||
|
EntitlementsModule,
|
||||||
],
|
],
|
||||||
controllers: [HealthController],
|
controllers: [HealthController],
|
||||||
providers: [{ provide: APP_GUARD, useClass: ThrottlerGuard }],
|
providers: [{ provide: APP_GUARD, useClass: ThrottlerGuard }],
|
||||||
|
|
|
||||||
|
|
@ -1,17 +1,33 @@
|
||||||
import { Body, Controller, Get, Headers, HttpCode, Logger, Module, Param, Post, Req, Res, UseGuards } from '@nestjs/common';
|
import { Body, Controller, Get, Headers, HttpCode, Logger, Module, Param, Post, Req, Res, UseGuards } from '@nestjs/common';
|
||||||
import type { RawBodyRequest } from '@nestjs/common';
|
import type { RawBodyRequest } from '@nestjs/common';
|
||||||
import { SkipThrottle } from '@nestjs/throttler';
|
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 type { Request, Response } from 'express';
|
||||||
import { AdminGuard, JwtAuthGuard } from '../common/guards';
|
import { AdminGuard, JwtAuthGuard } from '../common/guards';
|
||||||
import { BillingService } from './billing.service';
|
import { BillingService } from './billing.service';
|
||||||
|
|
||||||
class CheckoutLinkDto {
|
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. */
|
/** Envoyer le lien par e-mail au contact du magasin. */
|
||||||
@IsOptional() @IsBoolean()
|
@IsOptional() @IsBoolean()
|
||||||
sendEmail?: boolean;
|
sendEmail?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
class PortalLinkDto {
|
||||||
|
@IsOptional() @IsBoolean()
|
||||||
|
sendEmail?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
@Controller('admin')
|
@Controller('admin')
|
||||||
@UseGuards(JwtAuthGuard, AdminGuard)
|
@UseGuards(JwtAuthGuard, AdminGuard)
|
||||||
export class BillingAdminController {
|
export class BillingAdminController {
|
||||||
|
|
@ -25,7 +41,18 @@ export class BillingAdminController {
|
||||||
@Post('stores/:storeId/billing/checkout-link')
|
@Post('stores/:storeId/billing/checkout-link')
|
||||||
@HttpCode(200)
|
@HttpCode(200)
|
||||||
checkoutLink(@Param('storeId') storeId: string, @Body() dto: CheckoutLinkDto) {
|
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')
|
@Get('invoices/:id/pdf')
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
import { BadRequestException, Injectable, Logger, NotFoundException, ServiceUnavailableException } from '@nestjs/common';
|
import { BadRequestException, Injectable, Logger, NotFoundException, ServiceUnavailableException } from '@nestjs/common';
|
||||||
import { ConfigService } from '@nestjs/config';
|
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 { mkdir, readFile, writeFile } from 'fs/promises';
|
||||||
import { join } from 'path';
|
import { join } from 'path';
|
||||||
import Stripe from 'stripe';
|
import Stripe from 'stripe';
|
||||||
|
|
@ -8,6 +8,7 @@ import { PrismaService } from '../prisma/prisma.service';
|
||||||
import { MailService } from '../mail/mail.service';
|
import { MailService } from '../mail/mail.service';
|
||||||
import { emailLayout, esc } from '../mail/email-layout';
|
import { emailLayout, esc } from '../mail/email-layout';
|
||||||
import { renderInvoicePdf } from './invoice-pdf';
|
import { renderInvoicePdf } from './invoice-pdf';
|
||||||
|
import { PLANS, TRIAL_DAYS, planFromLookupKey, publicCatalog } from './plans';
|
||||||
|
|
||||||
/** Factures PDF : hors des dossiers servis publiquement. */
|
/** Factures PDF : hors des dossiers servis publiquement. */
|
||||||
export const INVOICES_DIR = join(process.cwd(), 'storage', 'invoices');
|
export const INVOICES_DIR = join(process.cwd(), 'storage', 'invoices');
|
||||||
|
|
@ -54,17 +55,27 @@ export class BillingService {
|
||||||
include: { subscription: true, invoices: { orderBy: { sequence: 'desc' } } },
|
include: { subscription: true, invoices: { orderBy: { sequence: 'desc' } } },
|
||||||
});
|
});
|
||||||
if (!store) throw new NotFoundException('Magasin introuvable');
|
if (!store) throw new NotFoundException('Magasin introuvable');
|
||||||
|
const sub = store.subscription;
|
||||||
return {
|
return {
|
||||||
testMode: (this.config.get<string>('stripe.secretKey') ?? '').startsWith('sk_test_'),
|
testMode: (this.config.get<string>('stripe.secretKey') ?? '').startsWith('sk_test_'),
|
||||||
subscription: store.subscription && {
|
catalog: publicCatalog(),
|
||||||
status: store.subscription.status,
|
trialDays: TRIAL_DAYS,
|
||||||
currentPeriodEnd: store.subscription.currentPeriodEnd,
|
subscription: sub && {
|
||||||
hasCustomer: !!store.subscription.stripeCustomerId,
|
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,
|
billingSuspended: store.billingSuspended,
|
||||||
invoices: store.invoices.map((i) => ({
|
invoices: store.invoices.map((i) => ({
|
||||||
id: i.id,
|
id: i.id,
|
||||||
number: i.number,
|
number: i.number,
|
||||||
|
description: i.description,
|
||||||
amountCents: i.amountCents,
|
amountCents: i.amountCents,
|
||||||
periodStart: i.periodStart,
|
periodStart: i.periodStart,
|
||||||
periodEnd: i.periodEnd,
|
periodEnd: i.periodEnd,
|
||||||
|
|
@ -74,35 +85,47 @@ export class BillingService {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** Client Stripe du magasin, créé à la première demande. */
|
||||||
* Crée (ou réutilise) le client Stripe du magasin et un lien Checkout
|
private async ensureCustomer(storeId: string) {
|
||||||
* d'abonnement ; l'envoie par e-mail au contact du magasin si demandé.
|
|
||||||
*/
|
|
||||||
async checkoutLink(storeId: string, sendEmail: boolean) {
|
|
||||||
const store = await this.prisma.store.findUnique({ where: { id: storeId }, include: { subscription: true } });
|
const store = await this.prisma.store.findUnique({ where: { id: storeId }, include: { subscription: true } });
|
||||||
if (!store) throw new NotFoundException('Magasin introuvable');
|
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;
|
private async priceFor(plan: Plan, interval: BillingInterval) {
|
||||||
if (!customerId) {
|
const key = PLANS[plan].lookupKey[interval];
|
||||||
const customer = await this.stripe.customers.create({
|
const price = (await this.stripe.prices.list({ lookup_keys: [key], active: true, limit: 1 })).data[0];
|
||||||
name: store.name,
|
if (!price) throw new ServiceUnavailableException(`Prix Stripe « ${key} » introuvable : lancer scripts/stripe-setup.ts`);
|
||||||
email: store.contactEmail,
|
return price;
|
||||||
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'],
|
* Lien Checkout pour souscrire une formule (mensuelle ou annuelle), avec
|
||||||
});
|
* essai gratuit éventuel et codes promo ; envoyé par e-mail si demandé.
|
||||||
customerId = customer.id;
|
*/
|
||||||
await this.prisma.subscription.upsert({
|
async checkoutLink(storeId: string, opts: { plan: Plan; interval: BillingInterval; trial: boolean; sendEmail: boolean }) {
|
||||||
where: { storeId },
|
const { store, customerId } = await this.ensureCustomer(storeId);
|
||||||
create: { storeId, stripeCustomerId: customerId },
|
if (store.subscription?.stripeSubscriptionId && store.subscription.status !== 'CANCELED') {
|
||||||
update: { stripeCustomerId: customerId },
|
throw new BadRequestException('Ce magasin a déjà un abonnement : changez de formule depuis le portail client');
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
// Un seul essai par magasin, même après résiliation.
|
||||||
const price = (await this.stripe.prices.list({ lookup_keys: [this.config.get('stripe.priceLookupKey')!], limit: 1 })).data[0];
|
const trialAllowed = opts.trial && !store.subscription?.trialEndsAt;
|
||||||
if (!price) throw new ServiceUnavailableException('Prix Stripe introuvable');
|
const price = await this.priceFor(opts.plan, opts.interval);
|
||||||
|
const def = PLANS[opts.plan];
|
||||||
|
|
||||||
const webUrl: string = this.config.get('webUrl')!;
|
const webUrl: string = this.config.get('webUrl')!;
|
||||||
const session = await this.stripe.checkout.sessions.create({
|
const session = await this.stripe.checkout.sessions.create({
|
||||||
|
|
@ -110,38 +133,82 @@ export class BillingService {
|
||||||
customer: customerId,
|
customer: customerId,
|
||||||
line_items: [{ price: price.id, quantity: 1 }],
|
line_items: [{ price: price.id, quantity: 1 }],
|
||||||
payment_method_types: ['card', 'sepa_debit'],
|
payment_method_types: ['card', 'sepa_debit'],
|
||||||
|
allow_promotion_codes: true,
|
||||||
locale: 'fr',
|
locale: 'fr',
|
||||||
client_reference_id: store.id,
|
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 },
|
metadata: { storeId: store.id },
|
||||||
success_url: `${webUrl}/abonnement/merci/`,
|
success_url: `${webUrl}/abonnement/merci/`,
|
||||||
cancel_url: `${webUrl}/tarif/`,
|
cancel_url: `${webUrl}/tarif/`,
|
||||||
expires_at: Math.floor(Date.now() / 1000) + 24 * 3600, // 24 h, maximum autorisé par Stripe
|
expires_at: Math.floor(Date.now() / 1000) + 24 * 3600, // 24 h, maximum autorisé par Stripe
|
||||||
});
|
});
|
||||||
|
|
||||||
if (sendEmail) {
|
const priceText = `${euros(def.priceCents[opts.interval])} ${opts.interval === 'YEAR' ? 'par an (2 mois offerts)' : 'par mois'}`;
|
||||||
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`;
|
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({
|
const html = emailLayout({
|
||||||
webUrl,
|
webUrl,
|
||||||
preheader: `Activez l'abonnement MonEspacePro de ${store.name} en quelques clics.`,
|
preheader: `Activez la formule ${def.name} de MonEspacePro pour ${store.name}.`,
|
||||||
eyebrow: 'Abonnement',
|
eyebrow: `Formule ${def.name}`,
|
||||||
title: `Activez MonEspacePro pour ${store.name}`,
|
title: `Activez MonEspacePro pour ${store.name}`,
|
||||||
paragraphs: [
|
paragraphs: [
|
||||||
`Bonjour ${esc(store.contactName)},`,
|
`Bonjour ${esc(store.contactName)},`,
|
||||||
`Votre carte de fidélité est prête. Il ne reste qu'à activer l'abonnement de <strong>${esc(store.name)}</strong> pour l'ouvrir à vos clients.`,
|
`Votre carte de fidélité est prête. Il ne reste qu'à activer la formule <strong>${esc(def.name)}</strong> de <strong>${esc(store.name)}</strong> 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: [
|
details: [
|
||||||
['Formule', 'Carte de fidélité dématérialisée, 1 magasin'],
|
['Formule', `${esc(def.name)} — ${esc(def.tagline)}`],
|
||||||
['Prix', '10 € par mois — TVA non applicable, art. 293 B du CGI'],
|
['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'],
|
['Engagement', 'Aucun, résiliable à tout moment'],
|
||||||
['Paiement', 'Carte bancaire ou prélèvement SEPA, factures automatiques'],
|
['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.',
|
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 <strong>${esc(store.name)}</strong> à 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 ────────────────────────────────────────────────
|
// ── Webhook ────────────────────────────────────────────────
|
||||||
|
|
@ -171,6 +238,9 @@ export class BillingService {
|
||||||
case 'invoice.paid':
|
case 'invoice.paid':
|
||||||
await this.onInvoicePaid(event.data.object);
|
await this.onInvoicePaid(event.data.object);
|
||||||
break;
|
break;
|
||||||
|
case 'customer.subscription.trial_will_end':
|
||||||
|
await this.onTrialWillEnd(event.data.object);
|
||||||
|
break;
|
||||||
case 'invoice.payment_failed':
|
case 'invoice.payment_failed':
|
||||||
await this.onPaymentFailed(event.data.object);
|
await this.onPaymentFailed(event.data.object);
|
||||||
break;
|
break;
|
||||||
|
|
@ -186,15 +256,59 @@ export class BillingService {
|
||||||
if (!storeId) return;
|
if (!storeId) return;
|
||||||
const status = STATUS[sub.status] ?? 'INCOMPLETE';
|
const status = STATUS[sub.status] ?? 'INCOMPLETE';
|
||||||
const periodEnd = sub.current_period_end;
|
const periodEnd = sub.current_period_end;
|
||||||
await this.prisma.subscription.upsert({
|
// La formule se déduit du prix Stripe (lookup_key) : un changement fait
|
||||||
where: { storeId },
|
// depuis le portail client est donc repris automatiquement.
|
||||||
create: { storeId, stripeCustomerId: String(sub.customer), stripeSubscriptionId: sub.id, status, currentPeriodEnd: periodEnd ? new Date(periodEnd * 1000) : null },
|
const price = sub.items.data[0]?.price;
|
||||||
update: { stripeCustomerId: String(sub.customer), stripeSubscriptionId: sub.id, status, currentPeriodEnd: periodEnd ? new Date(periodEnd * 1000) : null },
|
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 === 'ACTIVE') await this.reactivate(storeId);
|
||||||
if (status === 'PAST_DUE' || status === 'CANCELED') await this.suspend(storeId, `abonnement ${sub.status}`);
|
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 <strong>${esc(def.name)}</strong> 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) {
|
private async onPaymentFailed(invoice: Stripe.Invoice) {
|
||||||
const storeId = await this.storeIdForCustomer(String(invoice.customer));
|
const storeId = await this.storeIdForCustomer(String(invoice.customer));
|
||||||
if (storeId) await this.suspend(storeId, `paiement de ${euros(invoice.amount_due)} refusé`);
|
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 store = await this.prisma.store.findUniqueOrThrow({ where: { id: storeId } });
|
||||||
const period = si.lines.data[0]?.period;
|
const period = si.lines.data[0]?.period;
|
||||||
const paidAt = si.status_transitions?.paid_at ? new Date(si.status_transitions.paid_at * 1000) : new Date();
|
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.
|
// Numérotation continue : séquence globale, l'unicité en base empêche tout doublon.
|
||||||
let invoice: Prisma.InvoiceGetPayload<object> | null = null;
|
let invoice: Prisma.InvoiceGetPayload<object> | null = null;
|
||||||
|
|
@ -256,6 +375,7 @@ export class BillingService {
|
||||||
clientAddress: `${store.addressLine}\n${store.postalCode} ${store.city}`,
|
clientAddress: `${store.addressLine}\n${store.postalCode} ${store.city}`,
|
||||||
clientSiret: store.siret.replace(/(\d{3})(\d{3})(\d{3})(\d{5})/, '$1 $2 $3 $4'),
|
clientSiret: store.siret.replace(/(\d{3})(\d{3})(\d{3})(\d{5})/, '$1 $2 $3 $4'),
|
||||||
clientEmail: store.contactEmail,
|
clientEmail: store.contactEmail,
|
||||||
|
description,
|
||||||
periodStart: period ? new Date(period.start * 1000) : paidAt,
|
periodStart: period ? new Date(period.start * 1000) : paidAt,
|
||||||
periodEnd: period ? new Date(period.end * 1000) : paidAt,
|
periodEnd: period ? new Date(period.end * 1000) : paidAt,
|
||||||
paidAt,
|
paidAt,
|
||||||
|
|
@ -319,6 +439,7 @@ export class BillingService {
|
||||||
periodStart: inv.periodStart,
|
periodStart: inv.periodStart,
|
||||||
periodEnd: inv.periodEnd,
|
periodEnd: inv.periodEnd,
|
||||||
amountCents: inv.amountCents,
|
amountCents: inv.amountCents,
|
||||||
|
description: inv.description,
|
||||||
issuer: this.config.get('issuer')!,
|
issuer: this.config.get('issuer')!,
|
||||||
client: { name: inv.clientName, address: inv.clientAddress, siret: inv.clientSiret, email: inv.clientEmail },
|
client: { name: inv.clientName, address: inv.clientAddress, siret: inv.clientSiret, email: inv.clientEmail },
|
||||||
});
|
});
|
||||||
|
|
|
||||||
57
backend/src/billing/entitlements.service.ts
Normal file
57
backend/src/billing/entitlements.service.ts
Normal file
|
|
@ -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<Plan> {
|
||||||
|
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 {}
|
||||||
|
|
@ -7,6 +7,7 @@ export interface InvoicePdfData {
|
||||||
periodStart: Date;
|
periodStart: Date;
|
||||||
periodEnd: Date;
|
periodEnd: Date;
|
||||||
amountCents: number;
|
amountCents: number;
|
||||||
|
description: string;
|
||||||
issuer: { name: string; tradeName: string; siret: string; address: string; email: string };
|
issuer: { name: string; tradeName: string; siret: string; address: string; email: string };
|
||||||
client: { name: string; address: string; siret: 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 date = (d: Date) => d.toLocaleDateString('fr-FR', { day: '2-digit', month: '2-digit', year: 'numeric', timeZone: 'Europe/Paris' });
|
||||||
const euros = (cents: number) =>
|
const euros = (cents: number) =>
|
||||||
(cents / 100).toLocaleString('fr-FR', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).replace(/ | /g, ' ') + ' €';
|
(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
|
* Facture A4 conforme aux mentions obligatoires (art. L441-9 du Code de
|
||||||
|
|
@ -76,7 +76,7 @@ export function renderInvoicePdf(d: InvoicePdfData): Promise<Buffer> {
|
||||||
.text('Total HT', left + width - 90, y + 8, { width: 80, align: 'right' });
|
.text('Total HT', left + width - 90, y + 8, { width: 80, align: 'right' });
|
||||||
y += 34;
|
y += 34;
|
||||||
doc.fillColor(INK).font('Helvetica').fontSize(10)
|
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('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 - 180, y, { width: 90, align: 'right' })
|
||||||
.text(euros(d.amountCents), left + width - 90, y, { width: 80, align: 'right' });
|
.text(euros(d.amountCents), left + width - 90, y, { width: 80, align: 'right' });
|
||||||
|
|
|
||||||
102
backend/src/billing/plans.ts
Normal file
102
backend/src/billing/plans.ts
Normal file
|
|
@ -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<BillingInterval, number>;
|
||||||
|
lookupKey: Record<BillingInterval, string>;
|
||||||
|
features: Feature[];
|
||||||
|
limits: { maxStaff: number | null };
|
||||||
|
}
|
||||||
|
|
||||||
|
const PRO_FEATURES: Feature[] = [
|
||||||
|
'campaigns',
|
||||||
|
'inactiveReminders',
|
||||||
|
'birthday',
|
||||||
|
'googleReview',
|
||||||
|
'referral',
|
||||||
|
'advancedStats',
|
||||||
|
'csvExport',
|
||||||
|
'whiteLabel',
|
||||||
|
];
|
||||||
|
|
||||||
|
export const PLANS: Record<Plan, PlanDefinition> = {
|
||||||
|
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,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
@ -29,7 +29,8 @@ export default () => ({
|
||||||
stripe: {
|
stripe: {
|
||||||
secretKey: process.env.STRIPE_SECRET_KEY ?? '',
|
secretKey: process.env.STRIPE_SECRET_KEY ?? '',
|
||||||
webhookSecret: process.env.STRIPE_WEBHOOK_SECRET ?? '',
|
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). */
|
/** Émetteur des factures (mentions obligatoires). */
|
||||||
issuer: {
|
issuer: {
|
||||||
|
|
|
||||||
|
|
@ -40,7 +40,7 @@ export class EnrollmentService {
|
||||||
findStore(slug: string) {
|
findStore(slug: string) {
|
||||||
return this.prisma.store.findUnique({
|
return this.prisma.store.findUnique({
|
||||||
where: { slug },
|
where: { slug },
|
||||||
include: { cardDesign: { include: { rewards: { where: { active: true }, orderBy: { cost: 'asc' } } } } },
|
include: CARD_WITH_CONTEXT.store.include,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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';
|
import { nextRewardText, type CardWithContext } from '../wallet/wallet.types';
|
||||||
|
|
||||||
/** Pages publiques (clients finaux), rendues côté serveur aux couleurs du magasin. */
|
/** 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 type Platform = 'apple' | 'google' | 'other';
|
||||||
|
|
||||||
export function escapeHtml(value: unknown) {
|
export function escapeHtml(value: unknown) {
|
||||||
|
|
@ -128,7 +135,7 @@ ${body}
|
||||||
</main>
|
</main>
|
||||||
<footer>
|
<footer>
|
||||||
<nav><a href="/c/${e(store.slug)}/confidentialite">Confidentialité</a></nav>
|
<nav><a href="/c/${e(store.slug)}/confidentialite">Confidentialité</a></nav>
|
||||||
<span class="powered">${SYMBOL(14)}<span>Propulsé par <strong>MonEspacePro</strong></span></span>
|
${whiteLabel(store) ? "" : `<span class="powered">${SYMBOL(14)}<span>Propulsé par <strong>MonEspacePro</strong></span></span>`}
|
||||||
</footer>
|
</footer>
|
||||||
</div>
|
</div>
|
||||||
${script ? `<script>${script}</script>` : ''}
|
${script ? `<script>${script}</script>` : ''}
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,7 @@ import * as argon2 from 'argon2';
|
||||||
import { randomInt } from 'crypto';
|
import { randomInt } from 'crypto';
|
||||||
import { PrismaService } from '../prisma/prisma.service';
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
import { CreateStaffDto, UpdateStaffDto } from './dto/staff.dto';
|
import { CreateStaffDto, UpdateStaffDto } from './dto/staff.dto';
|
||||||
|
import { EntitlementsService } from '../billing/entitlements.service';
|
||||||
|
|
||||||
const PUBLIC_FIELDS = {
|
const PUBLIC_FIELDS = {
|
||||||
id: true,
|
id: true,
|
||||||
|
|
@ -24,7 +25,10 @@ function provisionalPassword(length = 12) {
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class StaffService {
|
export class StaffService {
|
||||||
constructor(private prisma: PrismaService) {}
|
constructor(
|
||||||
|
private prisma: PrismaService,
|
||||||
|
private entitlements: EntitlementsService,
|
||||||
|
) {}
|
||||||
|
|
||||||
async list(storeId: string) {
|
async list(storeId: string) {
|
||||||
await this.ensureStore(storeId);
|
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é. */
|
/** 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) {
|
async create(storeId: string, dto: CreateStaffDto) {
|
||||||
await this.ensureStore(storeId);
|
await this.ensureStore(storeId);
|
||||||
|
await this.entitlements.requireStaffSlot(storeId);
|
||||||
const password = provisionalPassword();
|
const password = provisionalPassword();
|
||||||
try {
|
try {
|
||||||
const staff = await this.prisma.staffUser.create({
|
const staff = await this.prisma.staffUser.create({
|
||||||
|
|
@ -61,6 +66,7 @@ export class StaffService {
|
||||||
|
|
||||||
async update(storeId: string, id: string, dto: UpdateStaffDto) {
|
async update(storeId: string, id: string, dto: UpdateStaffDto) {
|
||||||
const current = await this.find(storeId, id);
|
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.
|
// 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);
|
const revoke = (dto.active === false && current.active) || (dto.role !== undefined && dto.role !== current.role);
|
||||||
return this.prisma.staffUser.update({
|
return this.prisma.staffUser.update({
|
||||||
|
|
|
||||||
|
|
@ -29,7 +29,7 @@ export class StoresService {
|
||||||
this.prisma.store.findMany({
|
this.prisma.store.findMany({
|
||||||
where,
|
where,
|
||||||
orderBy: { createdAt: 'desc' },
|
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 }),
|
this.prisma.store.groupBy({ by: ['status'], _count: true }),
|
||||||
]);
|
]);
|
||||||
|
|
@ -38,6 +38,7 @@ export class StoresService {
|
||||||
...this.present(s),
|
...this.present(s),
|
||||||
customers: _count.cards,
|
customers: _count.cards,
|
||||||
subscriptionStatus: subscription?.status ?? null,
|
subscriptionStatus: subscription?.status ?? null,
|
||||||
|
plan: subscription?.stripeSubscriptionId && subscription.status !== 'CANCELED' ? subscription.plan : null,
|
||||||
})),
|
})),
|
||||||
counts: Object.fromEntries(byStatus.map((g) => [g.status, g._count])),
|
counts: Object.fromEntries(byStatus.map((g) => [g.status, g._count])),
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,12 @@ import { Prisma } from '@prisma/client';
|
||||||
/** Tout ce qu'il faut pour dessiner une carte, chargé en une requête. */
|
/** Tout ce qu'il faut pour dessiner une carte, chargé en une requête. */
|
||||||
export const CARD_WITH_CONTEXT = {
|
export const CARD_WITH_CONTEXT = {
|
||||||
customer: true,
|
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;
|
} satisfies Prisma.LoyaltyCardInclude;
|
||||||
|
|
||||||
export type CardWithContext = Prisma.LoyaltyCardGetPayload<{ include: typeof CARD_WITH_CONTEXT }>;
|
export type CardWithContext = Prisma.LoyaltyCardGetPayload<{ include: typeof CARD_WITH_CONTEXT }>;
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue