Chiffres clés (formule, montant, prochain prélèvement ou fin, total facturé et impayés), lien de paiement permanent à copier, titre de section pour les factures. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
244 lines
13 KiB
TypeScript
244 lines
13 KiB
TypeScript
import { useCallback, useEffect, useState } from 'react';
|
||
import { api, BillingInterval, downloadFile, Plan, PLAN_LABEL, SubscriptionStatus } from '../api';
|
||
|
||
interface CatalogEntry {
|
||
plan: Plan;
|
||
name: string;
|
||
tagline: string;
|
||
priceCents: Record<BillingInterval, number>;
|
||
modules: { id: string; name: string; tagline: string }[];
|
||
features: string[];
|
||
limits: { maxStaff: number | null };
|
||
}
|
||
|
||
interface Billing {
|
||
testMode: boolean;
|
||
catalog: CatalogEntry[];
|
||
/** Lien d'abonnement permanent du magasin. */
|
||
subscribeUrl: string;
|
||
subscription: {
|
||
status: SubscriptionStatus;
|
||
plan: Plan;
|
||
interval: BillingInterval;
|
||
legacyPrice: boolean;
|
||
cancelAtPeriodEnd: boolean;
|
||
currentPeriodEnd: string | null;
|
||
hasCustomer: boolean;
|
||
hasSubscription: boolean;
|
||
} | null;
|
||
billingSuspended: boolean;
|
||
invoices: { id: string; number: string; description: string; amountCents: number; periodStart: string; periodEnd: string; issuedAt: string; paidAt: string | null }[];
|
||
}
|
||
|
||
const STATUS: Record<SubscriptionStatus, [string, string]> = {
|
||
ACTIVE: ['Actif', 'ACTIVE'],
|
||
INCOMPLETE: ['En attente de paiement', 'DRAFT'],
|
||
PAST_DUE: ['Impayé', 'SUSPENDED'],
|
||
CANCELED: ['Résilié', 'CLOSED'],
|
||
};
|
||
|
||
/** Fonctions propres à une formule (hors modules). */
|
||
const FEATURE_LABEL: Record<string, string> = { 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<Billing | null>(null);
|
||
const [error, setError] = useState<string | null>(null);
|
||
const [link, setLink] = useState<{ url: string; emailedTo: string | null; label: string } | null>(null);
|
||
const [busy, setBusy] = useState(false);
|
||
const [plan, setPlan] = useState<Plan | null>(null);
|
||
const [interval, setInterval] = useState<BillingInterval | null>(null);
|
||
|
||
const reload = useCallback(() => {
|
||
api.get<Billing>(`/api/admin/stores/${storeId}/billing`).then(setData).catch((e) => setError(e.message));
|
||
}, [storeId]);
|
||
useEffect(reload, [reload]);
|
||
|
||
async function run(label: string, path: string, body: object) {
|
||
setBusy(true);
|
||
setError(null);
|
||
try {
|
||
const r = await api.post<{ url: string; emailedTo: string | null }>(path, body);
|
||
setLink({ ...r, label });
|
||
reload();
|
||
onChange();
|
||
} catch (e) {
|
||
setError((e as Error).message);
|
||
} finally {
|
||
setBusy(false);
|
||
}
|
||
}
|
||
|
||
if (!data) return error ? <div className="alert error">{error}</div> : <p className="muted">Chargement…</p>;
|
||
const sub = data.subscription;
|
||
const current = sub && sub.status !== 'CANCELED' && sub.hasSubscription ? data.catalog.find((c) => c.plan === sub.plan) : null;
|
||
const canSubscribe = !current;
|
||
// Par défaut : la formule choisie à la création (ou à l'inscription).
|
||
const chosenPlan = plan ?? sub?.plan ?? 'PRO';
|
||
const chosenInterval = interval ?? sub?.interval ?? 'MONTH';
|
||
|
||
const paidTotal = data.invoices.filter((i) => i.paidAt).reduce((n, i) => n + i.amountCents, 0);
|
||
const unpaid = data.invoices.filter((i) => !i.paidAt).length;
|
||
|
||
return (
|
||
<>
|
||
{data.testMode && <div className="alert warn">Stripe est en mode test : aucun paiement réel n'est encaissé (carte de test 4242 4242 4242 4242).</div>}
|
||
{error && <div className="alert error" role="alert">{error}</div>}
|
||
|
||
{/* Chiffres clés de l'abonnement */}
|
||
<div className="kpis">
|
||
<div className={`kpi${current ? ' ok' : ''}`}>
|
||
<b>{current ? current.name : '—'}</b>
|
||
<span>{current ? `formule ${sub!.interval === 'YEAR' ? 'annuelle' : 'mensuelle'}` : sub?.status === 'INCOMPLETE' ? `en attente · ${PLAN_LABEL[sub.plan]} choisie` : 'aucune formule'}</span>
|
||
</div>
|
||
<div className="kpi">
|
||
<b>{current ? euros(current.priceCents[sub!.interval]) : '—'}</b>
|
||
<span>{current ? `par ${sub!.interval === 'YEAR' ? 'an' : 'mois'}` : 'montant'}</span>
|
||
</div>
|
||
<div className={`kpi${sub?.cancelAtPeriodEnd ? ' warn' : ''}`}>
|
||
<b style={{ fontSize: 20, lineHeight: '34px' }}>{sub?.currentPeriodEnd && sub.status === 'ACTIVE' ? day(sub.currentPeriodEnd) : '—'}</b>
|
||
<span>{sub?.cancelAtPeriodEnd ? 'fin de l’abonnement' : 'prochain prélèvement'}</span>
|
||
</div>
|
||
<div className={`kpi${unpaid ? ' err' : ''}`}>
|
||
<b>{euros(paidTotal)}</b>
|
||
<span>{data.invoices.length} facture{data.invoices.length > 1 ? 's' : ''}{unpaid ? ` · ${unpaid} impayée${unpaid > 1 ? 's' : ''}` : ' · tout est réglé'}</span>
|
||
</div>
|
||
</div>
|
||
|
||
<section className="card" style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
|
||
<div className="row between">
|
||
<div>
|
||
<h2>Abonnement</h2>
|
||
<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>
|
||
<span className={`badge ${sub ? STATUS[sub.status][1] : 'DRAFT'}`}>{sub ? STATUS[sub.status][0] : 'Aucun abonnement'}</span>
|
||
</div>
|
||
{sub?.cancelAtPeriodEnd && sub.currentPeriodEnd && (
|
||
<div className="alert warn">Résiliation demandée : l'abonnement s'arrête le <strong>{day(sub.currentPeriodEnd)}</strong>.</div>
|
||
)}
|
||
{sub?.currentPeriodEnd && sub.status === 'ACTIVE' && !sub.cancelAtPeriodEnd && (
|
||
<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 }}>
|
||
<button className="btn" disabled={busy} onClick={() => run('Espace abonnement', `/api/admin/stores/${storeId}/billing/portal-link`, { sendEmail: true })}>
|
||
Envoyer l'espace abonnement à {contactEmail}
|
||
</button>
|
||
<button className="btn secondary" disabled={busy} onClick={() => run('Espace abonnement', `/api/admin/stores/${storeId}/billing/portal-link`, { sendEmail: false })}>
|
||
Ouvrir l'espace abonnement
|
||
</button>
|
||
<span className="muted" style={{ fontSize: 14 }}>Changer de formule, de moyen de paiement, résilier.</span>
|
||
</div>
|
||
)}
|
||
</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={chosenInterval === 'MONTH'} onClick={() => setInterval('MONTH')}>Mensuel</button>
|
||
<button type="button" className="chip" aria-pressed={chosenInterval === '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={chosenPlan === 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[chosenInterval])}
|
||
<span className="muted" style={{ fontSize: 14, fontWeight: 500 }}> / {chosenInterval === '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>
|
||
<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>
|
||
<span style={{ fontSize: 14, fontWeight: 700 }}>{c.modules.length ? `Modules inclus (${c.modules.length})` : 'Aucun module inclus'}</span>
|
||
{c.modules.length > 0 && (
|
||
<ul style={{ margin: 0, paddingLeft: 18, fontSize: 14, lineHeight: 1.6 }}>
|
||
{c.modules.map((m) => <li key={m.id} title={m.tagline}>{m.name}</li>)}
|
||
</ul>
|
||
)}
|
||
</label>
|
||
))}
|
||
</div>
|
||
<div className="copy-line" style={{ flexWrap: 'wrap' }}>
|
||
<span className="muted">Lien de paiement permanent :</span>
|
||
<code>{data.subscribeUrl}</code>
|
||
<button type="button" className="btn secondary small" onClick={() => navigator.clipboard?.writeText(data.subscribeUrl)}>Copier</button>
|
||
</div>
|
||
<p className="muted" style={{ margin: 0, fontSize: 14 }}>
|
||
Il ne périme pas. Le commerçant peut 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: chosenPlan, interval: chosenInterval, 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: chosenPlan, interval: chosenInterval, sendEmail: false })}>
|
||
Enregistrer la formule sans 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="row between" style={{ marginTop: 8 }}>
|
||
<h2>Factures</h2>
|
||
<span className="muted" style={{ fontSize: 14 }}>Émises et envoyées automatiquement à chaque paiement.</span>
|
||
</div>
|
||
<div className="table-wrap">
|
||
<div className="table-scroll">
|
||
<table style={{ minWidth: 720 }}>
|
||
<thead>
|
||
<tr>
|
||
<th scope="col" style={{ paddingLeft: 24 }}>Facture</th>
|
||
<th scope="col">Objet</th>
|
||
<th scope="col">Période</th>
|
||
<th scope="col" className="num">Montant</th>
|
||
<th scope="col">Statut</th>
|
||
<th scope="col"><span className="sr-only">PDF</span></th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
{data.invoices.map((i) => (
|
||
<tr key={i.id}>
|
||
<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 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 style={{ textAlign: 'right', paddingRight: 24 }}>
|
||
<button className="btn secondary small" onClick={() => downloadFile(`/api/admin/invoices/${i.id}/pdf`, `${i.number}.pdf`).catch((e) => setError(e.message))}>
|
||
PDF
|
||
</button>
|
||
</td>
|
||
</tr>
|
||
))}
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
{data.invoices.length === 0 && <p className="muted" style={{ padding: 24, margin: 0, textAlign: 'center' }}>Aucune facture pour l'instant. Elles sont créées automatiquement à chaque paiement.</p>}
|
||
</div>
|
||
</>
|
||
);
|
||
}
|