Espace web du Dirigeant, inscription en ligne, employés et cadeaux dans l'app Pro

- Admin : /inscription (formule, magasin, mot de passe, paiement Stripe) et
  /espace (connexion Dirigeant, état de l'abonnement, conception de la carte)
- Admin : formule obligatoire à la création d'un magasin, plus d'essai gratuit,
  lien d'abonnement permanent, titre des campagnes
- App Pro : écran Employés (création avec rôle Employé / Dirigeant), Mon compte
  (mot de passe), titre des campagnes, remise des cadeaux en caisse, accueil
  avant la conception de la carte
- Site : boutons « Choisir » vers l'inscription, avec la périodicité choisie

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Tony AVERTY 2026-10-07 11:52:09 +02:00
parent bf10beb89b
commit 226f3cedb8
25 changed files with 823 additions and 71 deletions

View file

@ -6,6 +6,18 @@
"runtimeExecutable": "npx", "runtimeExecutable": "npx",
"runtimeArgs": ["--yes", "http-server", "site", "-p", "4300", "-c-1", "--silent"], "runtimeArgs": ["--yes", "http-server", "site", "-p", "4300", "-c-1", "--silent"],
"port": 4300 "port": 4300
},
{
"name": "api",
"runtimeExecutable": "npm",
"runtimeArgs": ["--prefix", "backend", "run", "start:dev"],
"port": 3100
},
{
"name": "admin",
"runtimeExecutable": "npm",
"runtimeArgs": ["--prefix", "admin", "run", "dev"],
"port": 5173
} }
] ]
} }

View file

@ -2,6 +2,9 @@
const BASE = import.meta.env.VITE_API_URL ?? ''; const BASE = import.meta.env.VITE_API_URL ?? '';
const REFRESH_KEY = 'mep.admin.refresh'; const REFRESH_KEY = 'mep.admin.refresh';
/** Admin MonEspacePro, ou Dirigeant d'un magasin (espace web /espace). */
const KIND_KEY = 'mep.admin.kind';
export type SessionKind = 'admin' | 'staff';
let accessToken: string | null = null; let accessToken: string | null = null;
let onLogout: () => void = () => undefined; let onLogout: () => void = () => undefined;
@ -28,10 +31,21 @@ export function hasSession() {
} }
} }
function storeTokens(t: { accessToken: string; refreshToken: string }) { /** Type de la session ouverte dans ce navigateur, ou null. */
export function sessionKind(): SessionKind | null {
try {
if (!localStorage.getItem(REFRESH_KEY)) return null;
return localStorage.getItem(KIND_KEY) === 'staff' ? 'staff' : 'admin';
} catch {
return null;
}
}
function storeTokens(t: { accessToken: string; refreshToken: string }, kind?: SessionKind) {
accessToken = t.accessToken; accessToken = t.accessToken;
try { try {
localStorage.setItem(REFRESH_KEY, t.refreshToken); localStorage.setItem(REFRESH_KEY, t.refreshToken);
if (kind) localStorage.setItem(KIND_KEY, kind);
} catch { } catch {
/* navigation privée : la session durera le temps de l'onglet */ /* navigation privée : la session durera le temps de l'onglet */
} }
@ -41,6 +55,7 @@ export function logout() {
accessToken = null; accessToken = null;
try { try {
localStorage.removeItem(REFRESH_KEY); localStorage.removeItem(REFRESH_KEY);
localStorage.removeItem(KIND_KEY);
} catch { } catch {
/* rien */ /* rien */
} }
@ -52,9 +67,21 @@ export async function login(email: string, password: string) {
email, email,
password, password,
}, false); }, false);
storeTokens(t); storeTokens(t, 'admin');
} }
/** Connexion du Dirigeant (mêmes identifiants que l'app Pro). */
export async function loginStaff(email: string, password: string) {
const t = await request<{ accessToken: string; refreshToken: string }>('POST', '/api/auth/staff/login', { email, password }, false);
storeTokens(t, 'staff');
}
/** Appel sans session (inscription en ligne). */
export const publicApi = {
get: <T>(path: string) => request<T>('GET', path, undefined, false),
post: <T>(path: string, body: unknown) => request<T>('POST', path, body, false),
};
let refreshing: Promise<boolean> | null = null; let refreshing: Promise<boolean> | null = null;
async function refresh(): Promise<boolean> { async function refresh(): Promise<boolean> {
let token: string | null = null; let token: string | null = null;

View file

@ -1,36 +1,55 @@
import { StrictMode, useEffect, useState } from 'react'; import { StrictMode, useEffect, useState } from 'react';
import { createRoot } from 'react-dom/client'; import { createRoot } from 'react-dom/client';
import { BrowserRouter, Navigate, Route, Routes, useNavigate } from 'react-router-dom'; import { BrowserRouter, Navigate, Route, Routes, useLocation, useNavigate } from 'react-router-dom';
import { hasSession, setLogoutHandler } from './api'; import { SessionKind, sessionKind, setLogoutHandler } from './api';
import { Layout } from './components/Layout'; import { Layout } from './components/Layout';
import { LoginPage } from './pages/LoginPage'; import { LoginPage } from './pages/LoginPage';
import { StoresPage } from './pages/StoresPage'; import { StoresPage } from './pages/StoresPage';
import { NewStorePage } from './pages/NewStorePage'; import { NewStorePage } from './pages/NewStorePage';
import { StorePage } from './pages/StorePage'; import { StorePage } from './pages/StorePage';
import { PosterPage } from './pages/PosterPage'; import { PosterPage } from './pages/PosterPage';
import { SignupPage } from './pages/SignupPage';
import { MerchantLoginPage, MerchantSpace } from './pages/MerchantSpace';
import './styles.css'; import './styles.css';
function App() { function App() {
const navigate = useNavigate(); const navigate = useNavigate();
const [authed, setAuthed] = useState(hasSession()); const location = useLocation();
const [kind, setKind] = useState<SessionKind | null>(sessionKind());
const inSpace = location.pathname.startsWith('/espace');
useEffect(() => { useEffect(() => {
setLogoutHandler(() => { setLogoutHandler(() => {
setAuthed(false); setKind(null);
navigate('/connexion'); navigate(inSpace ? '/espace' : '/connexion');
}); });
}, [navigate]); }, [navigate, inSpace]);
if (!authed) { // Pages publiques et espace du Dirigeant (commerçants) : même application, autre session.
const merchantLogin = <MerchantLoginPage onLogin={() => setKind('staff')} />;
if (kind !== 'admin' || location.pathname === '/inscription') {
return ( return (
<Routes> <Routes>
<Route path="/connexion" element={<LoginPage onLogin={() => setAuthed(true)} />} /> <Route path="/inscription" element={<SignupPage />} />
<Route path="*" element={<Navigate to="/connexion" replace />} /> {kind === 'staff' ? (
<>
<Route path="/espace/affichette" element={<PosterPage merchant />} />
<Route path="/espace" element={<MerchantSpace />} />
<Route path="*" element={<Navigate to="/espace" replace />} />
</>
) : (
<>
<Route path="/espace" element={merchantLogin} />
<Route path="/connexion" element={<LoginPage onLogin={() => setKind('admin')} />} />
<Route path="*" element={<Navigate to={inSpace ? '/espace' : '/connexion'} replace />} />
</>
)}
</Routes> </Routes>
); );
} }
return ( return (
<Routes> <Routes>
<Route path="/espace" element={merchantLogin} />
<Route path="/magasins/:id/affichette" element={<PosterPage />} /> <Route path="/magasins/:id/affichette" element={<PosterPage />} />
<Route element={<Layout />}> <Route element={<Layout />}>
<Route path="/magasins" element={<StoresPage />} /> <Route path="/magasins" element={<StoresPage />} />

View file

@ -14,13 +14,13 @@ interface CatalogEntry {
interface Billing { interface Billing {
testMode: boolean; testMode: boolean;
catalog: CatalogEntry[]; catalog: CatalogEntry[];
trialDays: number; /** Lien d'abonnement permanent du magasin. */
subscribeUrl: string;
subscription: { subscription: {
status: SubscriptionStatus; status: SubscriptionStatus;
plan: Plan; plan: Plan;
interval: BillingInterval; interval: BillingInterval;
legacyPrice: boolean; legacyPrice: boolean;
trialEndsAt: string | null;
cancelAtPeriodEnd: boolean; cancelAtPeriodEnd: boolean;
currentPeriodEnd: string | null; currentPeriodEnd: string | null;
hasCustomer: boolean; hasCustomer: boolean;
@ -48,9 +48,8 @@ export function BillingTab({ storeId, contactEmail, onChange }: { storeId: strin
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [link, setLink] = useState<{ url: string; emailedTo: string | null; label: string } | 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 [plan, setPlan] = useState<Plan | null>(null);
const [interval, setInterval] = useState<BillingInterval>('MONTH'); const [interval, setInterval] = useState<BillingInterval | null>(null);
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));
@ -75,9 +74,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 current = sub && sub.status !== 'CANCELED' && sub.hasSubscription ? data.catalog.find((c) => c.plan === sub.plan) : null; 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; 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';
return ( return (
<> <>
@ -96,11 +96,10 @@ export function BillingTab({ storeId, contactEmail, onChange }: { storeId: strin
</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>
{trialing && <div className="alert ok">Essai gratuit jusqu'au <strong>{day(sub!.trialEndsAt!)}</strong> : aucun prélèvement avant cette date.</div>}
{sub?.cancelAtPeriodEnd && sub.currentPeriodEnd && ( {sub?.cancelAtPeriodEnd && sub.currentPeriodEnd && (
<div className="alert warn">Résiliation demandée : l'abonnement s'arrête le <strong>{day(sub.currentPeriodEnd)}</strong>.</div> <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 && !trialing && ( {sub?.currentPeriodEnd && sub.status === 'ACTIVE' && !sub.cancelAtPeriodEnd && (
<p style={{ margin: 0 }}>Prochain prélèvement le <strong>{day(sub.currentPeriodEnd)}</strong>.</p> <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>} {data.billingSuspended && <div className="alert warn">Magasin suspendu automatiquement pour impayé. Il sera réactivé dès que le paiement passera.</div>}
@ -123,21 +122,21 @@ export function BillingTab({ storeId, contactEmail, onChange }: { storeId: strin
<div className="row between"> <div className="row between">
<h2>Choisir une formule</h2> <h2>Choisir une formule</h2>
<div role="group" aria-label="Périodicité" className="row" style={{ gap: 8 }}> <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={chosenInterval === 'MONTH'} onClick={() => setInterval('MONTH')}>Mensuel</button>
<button type="button" className="chip" aria-pressed={interval === 'YEAR'} onClick={() => setInterval('YEAR')}>Annuel — 2 mois offerts</button> <button type="button" className="chip" aria-pressed={chosenInterval === 'YEAR'} onClick={() => setInterval('YEAR')}>Annuel — 2 mois offerts</button>
</div> </div>
</div> </div>
<div className="mode-cards" role="radiogroup" aria-label="Formule"> <div className="mode-cards" role="radiogroup" aria-label="Formule">
{data.catalog.map((c) => ( {data.catalog.map((c) => (
<label key={c.plan} className="mode-card" style={{ flexDirection: 'column', gap: 8 }}> <label key={c.plan} className="mode-card" style={{ flexDirection: 'column', gap: 8 }}>
<span className="row" style={{ gap: 10 }}> <span className="row" style={{ gap: 10 }}>
<input type="radio" name="plan" checked={plan === c.plan} onChange={() => setPlan(c.plan)} /> <input type="radio" name="plan" checked={chosenPlan === c.plan} onChange={() => setPlan(c.plan)} />
<strong style={{ fontSize: 18 }}>{c.name}</strong> <strong style={{ fontSize: 18 }}>{c.name}</strong>
{c.plan === 'PRO' && <span className="badge ACTIVE" style={{ height: 22 }}>Conseillée</span>} {c.plan === 'PRO' && <span className="badge ACTIVE" style={{ height: 22 }}>Conseillée</span>}
</span> </span>
<span style={{ fontSize: 24, fontWeight: 800 }}> <span style={{ fontSize: 24, fontWeight: 800 }}>
{euros(c.priceCents[interval])} {euros(c.priceCents[chosenInterval])}
<span className="muted" style={{ fontSize: 14, fontWeight: 500 }}> / {interval === 'YEAR' ? 'an' : 'mois'}{c.plan === 'RESEAU' ? ' / magasin' : ''}</span> <span className="muted" style={{ fontSize: 14, fontWeight: 500 }}> / {chosenInterval === 'YEAR' ? 'an' : 'mois'}{c.plan === 'RESEAU' ? ' / magasin' : ''}</span>
</span> </span>
<span className="muted" style={{ fontSize: 14 }}>{c.tagline}</span> <span className="muted" style={{ fontSize: 14 }}>{c.tagline}</span>
<ul style={{ margin: 0, paddingLeft: 18, fontSize: 14, lineHeight: 1.6 }}> <ul style={{ margin: 0, paddingLeft: 18, fontSize: 14, lineHeight: 1.6 }}>
@ -154,22 +153,16 @@ export function BillingTab({ storeId, contactEmail, onChange }: { storeId: strin
</label> </label>
))} ))}
</div> </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 }}> <p className="muted" style={{ margin: 0, fontSize: 14 }}>
Lien permanent (il ne périme pas) : <a href={data.subscribeUrl} target="_blank" rel="noreferrer" style={{ wordBreak: 'break-all' }}>{data.subscribeUrl}</a>.
Le commerçant pourra saisir un code promo sur la page de paiement (codes à créer dans Stripe → Coupons). Le commerçant pourra saisir un code promo sur la page de paiement (codes à créer dans Stripe → Coupons).
</p> </p>
<div className="row" style={{ gap: 8 }}> <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 })}> <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} Envoyer le lien à {contactEmail}
</button> </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 })}> <button className="btn secondary" disabled={busy} onClick={() => run("Lien d'abonnement", `/api/admin/stores/${storeId}/billing/checkout-link`, { plan: chosenPlan, interval: chosenInterval, sendEmail: false })}>
Créer le lien sans l'envoyer Enregistrer la formule sans envoyer
</button> </button>
</div> </div>
</section> </section>

View file

@ -2,6 +2,7 @@ import { useCallback, useEffect, useState } from 'react';
import { api } from '../api'; import { api } from '../api';
interface Campaign { interface Campaign {
title: string | null;
id: string; id: string;
message: string; message: string;
sentByName: string; sentByName: string;
@ -11,6 +12,7 @@ interface Campaign {
} }
interface Overview { interface Overview {
defaultTitle: string;
allowed: boolean; allowed: boolean;
maxLength: number; maxLength: number;
minIntervalHours: number; minIntervalHours: number;
@ -26,6 +28,7 @@ const when = (d: string) =>
export function CampaignSender({ storeId, storeName }: { storeId: string; storeName: string }) { export function CampaignSender({ storeId, storeName }: { storeId: string; storeName: string }) {
const [data, setData] = useState<Overview | null>(null); const [data, setData] = useState<Overview | null>(null);
const [message, setMessage] = useState(''); const [message, setMessage] = useState('');
const [title, setTitle] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null); const [notice, setNotice] = useState<string | null>(null);
const [busy, setBusy] = useState(false); const [busy, setBusy] = useState(false);
@ -45,7 +48,7 @@ export function CampaignSender({ storeId, storeName }: { storeId: string; storeN
setBusy(true); setBusy(true);
setError(null); setError(null);
try { try {
await api.post(`/api/admin/stores/${storeId}/campaigns`, { message: text }); await api.post(`/api/admin/stores/${storeId}/campaigns`, { message: text, title: (title ?? data!.defaultTitle).trim() });
setMessage(''); setMessage('');
setNotice('Campagne envoyée. Les cartes se mettent à jour dans les minutes qui suivent.'); setNotice('Campagne envoyée. Les cartes se mettent à jour dans les minutes qui suivent.');
load(); load();
@ -69,7 +72,19 @@ export function CampaignSender({ storeId, storeName }: { storeId: string; storeN
Audience : <strong>{data.audience.cards}</strong> cartes, dont <strong>{data.audience.appleDevices}</strong> iPhone joignables (Google Wallet : tous les clients qui ont ajouté la carte). Audience : <strong>{data.audience.cards}</strong> cartes, dont <strong>{data.audience.appleDevices}</strong> iPhone joignables (Google Wallet : tous les clients qui ont ajouté la carte).
</p> </p>
</div> </div>
<label htmlFor="campaign-msg" className="sr-only">Message</label> <div className="field">
<label htmlFor="campaign-title">Titre de la notification</label>
<input
id="campaign-title"
className="input"
maxLength={40}
value={title ?? data.defaultTitle}
onChange={(e) => setTitle(e.target.value)}
disabled={blocked || busy}
/>
<span className="muted" style={{ fontSize: 14 }}>Affiché sur Google Wallet. Sur iPhone, le nom du magasin apparaît toujours en titre.</span>
</div>
<label htmlFor="campaign-msg">Message</label>
<textarea <textarea
id="campaign-msg" id="campaign-msg"
className="input" className="input"
@ -81,7 +96,7 @@ export function CampaignSender({ storeId, storeName }: { storeId: string; storeN
disabled={blocked || busy} disabled={blocked || busy}
/> />
<div className="row between"> <div className="row between">
<span className="muted" style={{ fontSize: 14 }}>{text.length} / {data.maxLength} caractères · 1 campagne par jour maximum</span> <span className="muted" style={{ fontSize: 14 }}>{text.length} / {data.maxLength} caractères · 1 campagne toutes les {data.minIntervalHours} h maximum</span>
<button className="btn" disabled={blocked || busy || text.length < 5} onClick={send}> <button className="btn" disabled={blocked || busy || text.length < 5} onClick={send}>
{busy ? 'Envoi…' : 'Envoyer la campagne'} {busy ? 'Envoi…' : 'Envoyer la campagne'}
</button> </button>
@ -108,7 +123,7 @@ export function CampaignSender({ storeId, storeName }: { storeId: string; storeN
{data.items.map((c) => ( {data.items.map((c) => (
<tr key={c.id}> <tr key={c.id}>
<td className="muted" style={{ whiteSpace: 'nowrap' }}>{when(c.createdAt)}</td> <td className="muted" style={{ whiteSpace: 'nowrap' }}>{when(c.createdAt)}</td>
<td>{c.message}</td> <td>{c.title && <strong>{c.title} · </strong>}{c.message}</td>
<td>{c.sentByName}</td> <td>{c.sentByName}</td>
<td className="num">{c.cards}</td> <td className="num">{c.cards}</td>
</tr> </tr>

View file

@ -9,7 +9,7 @@ const STEPS = ['Identité', 'Couleurs', 'Règle de points', 'Récompenses', 'Ré
type Draft = Omit<CardDesign, 'logoUrl' | 'stripUrl'>; type Draft = Omit<CardDesign, 'logoUrl' | 'stripUrl'>;
function defaults(store: StoreDetail): Draft { function defaults(store: Pick<StoreDetail, 'name'>): Draft {
return { return {
programName: `Fidélité ${store.name}`.slice(0, 40), programName: `Fidélité ${store.name}`.slice(0, 40),
backgroundColor: '#1F2937', backgroundColor: '#1F2937',
@ -21,8 +21,25 @@ function defaults(store: StoreDetail): Draft {
}; };
} }
export function CardWizard({ store, onSaved }: { store: StoreDetail; onSaved: () => void }) { type WizardStore = Pick<StoreDetail, 'id' | 'name' | 'status' | 'enrollUrl'>;
const base = `/api/admin/stores/${store.id}/card-design`;
/**
* Conception de la carte. Admin : base par défaut. Espace du Dirigeant :
* `base` = /api/staff/card-design, `posterHref` et `draftNote` adaptés.
*/
export function CardWizard({
store,
onSaved,
base = `/api/admin/stores/${store.id}/card-design`,
posterHref = `/magasins/${store.id}/affichette`,
draftNote,
}: {
store: WizardStore;
onSaved: () => void;
base?: string;
posterHref?: string;
draftNote?: React.ReactNode;
}) {
const [step, setStep] = useState(0); const [step, setStep] = useState(0);
const [draft, setDraft] = useState<Draft | null>(null); const [draft, setDraft] = useState<Draft | null>(null);
const [images, setImages] = useState<{ logoUrl: string | null; stripUrl: string | null }>({ logoUrl: null, stripUrl: null }); const [images, setImages] = useState<{ logoUrl: string | null; stripUrl: string | null }>({ logoUrl: null, stripUrl: null });
@ -254,14 +271,15 @@ export function CardWizard({ store, onSaved }: { store: StoreDetail; onSaved: ()
<div style={{ display: 'flex', flexDirection: 'column', gap: 12, flex: '1 1 220px' }}> <div style={{ display: 'flex', flexDirection: 'column', gap: 12, flex: '1 1 220px' }}>
<p style={{ margin: 0 }}>Le QR mène à la page d'inscription :</p> <p style={{ margin: 0 }}>Le QR mène à la page d'inscription :</p>
<a href={store.enrollUrl} target="_blank" rel="noreferrer" style={{ wordBreak: 'break-all' }}>{store.enrollUrl}</a> <a href={store.enrollUrl} target="_blank" rel="noreferrer" style={{ wordBreak: 'break-all' }}>{store.enrollUrl}</a>
<Link to={`/magasins/${store.id}/affichette`} className="btn secondary">Imprimer l'affichette (A5 / A6)</Link> <Link to={posterHref} className="btn secondary">Imprimer l'affichette (A5 / A6)</Link>
</div> </div>
</div> </div>
{store.status === 'DRAFT' && ( {store.status === 'DRAFT' &&
(draftNote ?? (
<p style={{ margin: 0 }}> <p style={{ margin: 0 }}>
Utilisez le bouton <strong>Activer</strong> en haut de la fiche pour ouvrir le programme. Le programme s'ouvre automatiquement dès que l'abonnement est payé. Sinon, utilisez le bouton <strong>Activer</strong> en haut de la fiche.
</p> </p>
)} ))}
</> </>
)} )}

View file

@ -0,0 +1,137 @@
import { FormEvent, useCallback, useEffect, useState } from 'react';
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
import { api, ApiError, loginStaff, logout, Plan, PLAN_LABEL, StoreStatus, SubscriptionStatus } from '../api';
import { Brand } from '../components/Layout';
import { CardWizard } from './CardWizard';
interface MerchantStore {
id: string;
name: string;
status: StoreStatus;
enrollUrl: string;
subscription: { status: SubscriptionStatus; plan: Plan } | null;
subscribeUrl: string | null;
}
/** Connexion du Dirigeant à son espace web. */
export function MerchantLoginPage({ onLogin }: { onLogin: () => void }) {
const navigate = useNavigate();
const [params] = useSearchParams();
const welcome = params.has('bienvenue');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
async function submit(e: FormEvent) {
e.preventDefault();
setBusy(true);
setError(null);
try {
await loginStaff(email, password);
onLogin();
navigate('/espace', { replace: true });
} catch (err) {
// Juste après le paiement, le webhook Stripe peut avoir quelques secondes de retard.
setError(
welcome && err instanceof ApiError && err.status === 401
? 'Votre espace est en cours de création. Réessayez dans quelques secondes.'
: (err as Error).message,
);
} finally {
setBusy(false);
}
}
return (
<main style={{ minHeight: '100vh', display: 'grid', placeItems: 'center', padding: 16 }}>
<form className="card" onSubmit={submit} style={{ width: '100%', maxWidth: 420, display: 'flex', flexDirection: 'column', gap: 20 }}>
<Brand admin={false} />
{welcome && <div className="alert ok">Paiement reçu, merci ! Connectez-vous avec l’e-mail et le mot de passe choisis à l’inscription.</div>}
<div>
<h1 style={{ fontSize: 26 }}>Mon espace</h1>
<p className="muted" style={{ margin: 0 }}>Mêmes identifiants que l’app MonEspacePro Pro.</p>
</div>
{error && <div className="alert error" role="alert">{error}</div>}
<div className="field">
<label htmlFor="m-email">E-mail</label>
<input id="m-email" className="input" type="email" autoComplete="username" required value={email} onChange={(e) => setEmail(e.target.value)} />
</div>
<div className="field">
<label htmlFor="m-password">Mot de passe</label>
<input id="m-password" className="input" type="password" autoComplete="current-password" required value={password} onChange={(e) => setPassword(e.target.value)} />
</div>
<button className="btn" disabled={busy}>{busy ? 'Connexion…' : 'Se connecter'}</button>
<p className="muted" style={{ margin: 0, fontSize: 14, textAlign: 'center' }}>
Pas encore client ? <Link to="/inscription">Créer mon programme</Link>
</p>
</form>
</main>
);
}
/** Espace web du Dirigeant : état du magasin, abonnement, conception de la carte. */
export function MerchantSpace() {
const [store, setStore] = useState<MerchantStore | null>(null);
const [error, setError] = useState<string | null>(null);
const reload = useCallback(() => {
api
.get<MerchantStore>('/api/staff/store')
.then(setStore)
.catch((e) => setError(e instanceof ApiError && e.status === 403 ? 'Cet espace est réservé au Dirigeant du magasin. Utilisez l’app MonEspacePro Pro pour scanner les cartes.' : e.message));
}, []);
useEffect(reload, [reload]);
return (
<div style={{ minHeight: '100vh' }}>
<header className="row between" style={{ padding: '16px 24px', borderBottom: '1px solid var(--border)' }}>
<Brand admin={false} />
<button type="button" className="btn secondary small" onClick={logout}>Se déconnecter</button>
</header>
<main className="container" style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 24 }}>
{error && <div className="alert error" role="alert">{error}</div>}
{!store && !error && <p className="muted">Chargement…</p>}
{store && (
<>
<div>
<h1>{store.name}</h1>
<p className="muted" style={{ margin: 0 }}>
{store.subscription ? `Formule ${PLAN_LABEL[store.subscription.plan]}` : 'Aucune formule'} ·{' '}
{store.status === 'ACTIVE' ? 'Programme ouvert à vos clients' : store.status === 'DRAFT' ? 'Programme pas encore ouvert' : 'Programme suspendu'}
</p>
</div>
{store.subscribeUrl && (
<div className="alert warn row between" style={{ gap: 12 }}>
<span>Votre abonnement n’est pas encore actif : le programme s’ouvrira dès le paiement validé.</span>
<a className="btn small" href={store.subscribeUrl}>Activer mon abonnement</a>
</div>
)}
{store.status === 'SUSPENDED' && <div className="alert warn">Programme suspendu. Il rouvre automatiquement dès le paiement de l’abonnement régularisé.</div>}
{store.status === 'ACTIVE' && (
<div className="alert ok">
Vos clients s’inscrivent sur <a href={store.enrollUrl} target="_blank" rel="noreferrer">{store.enrollUrl}</a> (QR code de l’affichette).
</div>
)}
<p className="muted" style={{ margin: 0 }}>
Employés, modules (campagnes, anniversaire, relances…) et statistiques : dans l’app MonEspacePro Pro, avec les mêmes identifiants.
</p>
<CardWizard
store={store}
onSaved={reload}
base="/api/staff/card-design"
posterHref="/espace/affichette"
draftNote={
<p style={{ margin: 0 }}>
{store.subscribeUrl
? 'Votre programme s’ouvrira automatiquement dès votre abonnement activé.'
: 'Enregistrez la carte : votre programme s’ouvre automatiquement à vos clients.'}
</p>
}
/>
</>
)}
</main>
</div>
);
}

View file

@ -1,24 +1,78 @@
import { useState } from 'react';
import { Link, useNavigate } from 'react-router-dom'; import { Link, useNavigate } from 'react-router-dom';
import { api, Store } from '../api'; import { api, BillingInterval, Plan, PLAN_LABEL, Store, StaffUser } from '../api';
import { EMPTY_STORE, StoreForm } from '../components/StoreForm'; import { EMPTY_STORE, StoreForm } from '../components/StoreForm';
type Created = Store & { manager: StaffUser | null; link: { url: string | null; emailedTo: string | null; error?: string } };
export function NewStorePage() { export function NewStorePage() {
const navigate = useNavigate(); const navigate = useNavigate();
const [plan, setPlan] = useState<Plan>('PRO');
const [interval, setInterval] = useState<BillingInterval>('MONTH');
const [created, setCreated] = useState<Created | null>(null);
if (created) {
return (
<>
<div>
<Link to="/magasins">← Magasins</Link>
<h1>{created.name} est créé</h1>
</div>
<section className="card" style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
{created.link.emailedTo ? (
<div className="alert ok">
Lien de paiement (formule {PLAN_LABEL[plan]}, {interval === 'YEAR' ? 'annuelle' : 'mensuelle'}) envoyé à <strong>{created.link.emailedTo}</strong>
{created.manager && ', avec ses identifiants Dirigeant'}. Le magasin s'ouvrira automatiquement dès le paiement validé et la carte conçue.
</div>
) : (
<div className="alert warn">Le lien de paiement n'a pas pu être envoyé : {created.link.error}. Renvoyez-le depuis l'onglet Facturation.</div>
)}
{created.manager ? (
<>
<p style={{ margin: 0 }}>
Compte Dirigeant : <strong>{created.manager.email}</strong>, mot de passe provisoire :
</p>
<div className="password-box">{created.manager.provisionalPassword}</div>
</>
) : (
<div className="alert warn">Un compte existe déjà avec l'e-mail du contact : créez le Dirigeant à la main dans l'onglet Employés.</div>
)}
<div className="row" style={{ justifyContent: 'flex-end' }}>
<button className="btn" onClick={() => navigate(`/magasins/${created.id}/carte`)}>Concevoir la carte</button>
</div>
</section>
</>
);
}
return ( return (
<> <>
<div> <div>
<Link to="/magasins">← Magasins</Link> <Link to="/magasins">← Magasins</Link>
<h1>Nouveau magasin</h1> <h1>Nouveau magasin</h1>
<p className="muted" style={{ margin: 0 }}> <p className="muted" style={{ margin: 0 }}>
Après la création, vous passerez à la conception de la carte de fidélité. À la création, le contact reçoit automatiquement par e-mail le lien de paiement de la formule choisie et ses identifiants Dirigeant.
</p> </p>
</div> </div>
<section className="card" style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
<h2>Formule *</h2>
<div role="radiogroup" aria-label="Formule" className="row" style={{ gap: 8 }}>
{(['ESSENTIEL', 'PRO', 'RESEAU'] as const).map((p) => (
<button key={p} type="button" className="chip" role="radio" aria-checked={plan === p} aria-pressed={plan === p} onClick={() => setPlan(p)}>
{PLAN_LABEL[p]}
</button>
))}
</div>
<div role="radiogroup" aria-label="Périodicité" className="row" style={{ gap: 8 }}>
<button type="button" className="chip" role="radio" aria-checked={interval === 'MONTH'} aria-pressed={interval === 'MONTH'} onClick={() => setInterval('MONTH')}>Mensuel</button>
<button type="button" className="chip" role="radio" aria-checked={interval === 'YEAR'} aria-pressed={interval === 'YEAR'} onClick={() => setInterval('YEAR')}>Annuel — 2 mois offerts</button>
</div>
</section>
<StoreForm <StoreForm
initial={EMPTY_STORE} initial={EMPTY_STORE}
submitLabel="Créer le magasin" submitLabel="Créer le magasin"
onSubmit={async (v) => { onSubmit={async (v) => {
const store = await api.post<Store>('/api/admin/stores', v); setCreated(await api.post<Created>('/api/admin/stores', { ...v, plan, interval }));
navigate(`/magasins/${store.id}/carte`);
}} }}
/> />
</> </>

View file

@ -4,8 +4,10 @@ import { api, assetUrl, CardDesign, StoreDetail } from '../api';
import { Poster, PosterFormat } from '../components/Poster'; import { Poster, PosterFormat } from '../components/Poster';
/** Page d'impression de l'affichette, sans la mise en page de l'admin. */ /** Page d'impression de l'affichette, sans la mise en page de l'admin. */
export function PosterPage() { export function PosterPage({ merchant = false }: { merchant?: boolean }) {
const { id } = useParams<{ id: string }>(); const { id } = useParams<{ id: string }>();
const storePath = merchant ? '/api/staff/store' : `/api/admin/stores/${id}`;
const designPath = merchant ? '/api/staff/card-design' : `/api/admin/stores/${id}/card-design`;
const [params, setParams] = useSearchParams(); const [params, setParams] = useSearchParams();
const format: PosterFormat = params.get('format') === 'A6' ? 'A6' : 'A5'; const format: PosterFormat = params.get('format') === 'A6' ? 'A6' : 'A5';
const [store, setStore] = useState<StoreDetail | null>(null); const [store, setStore] = useState<StoreDetail | null>(null);
@ -13,13 +15,13 @@ export function PosterPage() {
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
useEffect(() => { useEffect(() => {
Promise.all([api.get<StoreDetail>(`/api/admin/stores/${id}`), api.get<CardDesign | null>(`/api/admin/stores/${id}/card-design`)]) Promise.all([api.get<StoreDetail>(storePath), api.get<CardDesign | null>(designPath)])
.then(([s, d]) => { .then(([s, d]) => {
setStore(s); setStore(s);
setDesign(d); setDesign(d);
}) })
.catch((e) => setError(e.message)); .catch((e) => setError(e.message));
}, [id]); }, [storePath, designPath]);
if (error) return <div className="alert error" style={{ margin: 24 }}>{error}</div>; if (error) return <div className="alert error" style={{ margin: 24 }}>{error}</div>;
if (!store) return <p className="muted" style={{ margin: 24 }}>Chargement…</p>; if (!store) return <p className="muted" style={{ margin: 24 }}>Chargement…</p>;
@ -29,7 +31,7 @@ export function PosterPage() {
<div className="poster-page"> <div className="poster-page">
<style>{`@page{size:${format};margin:0}@media print{.no-print{display:none!important}body{background:#fff}.poster-page{padding:0!important}}`}</style> <style>{`@page{size:${format};margin:0}@media print{.no-print{display:none!important}body{background:#fff}.poster-page{padding:0!important}}`}</style>
<div className="no-print row between" style={{ padding: 16 }}> <div className="no-print row between" style={{ padding: 16 }}>
<Link to={`/magasins/${id}/carte`}>← Retour à la carte</Link> <Link to={merchant ? '/espace' : `/magasins/${id}/carte`}>← Retour à la carte</Link>
<div className="row" style={{ gap: 8 }}> <div className="row" style={{ gap: 8 }}>
{(['A5', 'A6'] as const).map((f) => ( {(['A5', 'A6'] as const).map((f) => (
<button key={f} type="button" className="chip" aria-pressed={format === f} onClick={() => setParams({ format: f })}>{f}</button> <button key={f} type="button" className="chip" aria-pressed={format === f} onClick={() => setParams({ format: f })}>{f}</button>

View file

@ -0,0 +1,148 @@
import { FormEvent, useEffect, useState } from 'react';
import { Link, useSearchParams } from 'react-router-dom';
import { BillingInterval, Plan, PLAN_LABEL, publicApi } from '../api';
import { Brand } from '../components/Layout';
interface PlanInfo {
plan: Plan;
name: string;
tagline: string;
priceCents: Record<BillingInterval, number>;
modules: { id: string; name: string }[];
limits: { maxStaff: number | null };
}
const euros = (c: number) => (c / 100).toLocaleString('fr-FR', { style: 'currency', currency: 'EUR', minimumFractionDigits: c % 100 ? 2 : 0 });
const PLANS: Plan[] = ['ESSENTIEL', 'PRO', 'RESEAU'];
const FIELDS = [
['name', 'Nom du commerce', { autoComplete: 'organization', placeholder: 'Boulangerie Kerlann', maxLength: 120 }],
['siret', 'SIRET', { inputMode: 'numeric', placeholder: '123 456 789 00012' }],
['addressLine', 'Adresse', { autoComplete: 'street-address', maxLength: 200 }],
['postalCode', 'Code postal', { autoComplete: 'postal-code', inputMode: 'numeric', maxLength: 5 }],
['city', 'Ville', { autoComplete: 'address-level2', maxLength: 120 }],
['contactName', 'Prénom et nom du dirigeant', { autoComplete: 'name', maxLength: 120 }],
['contactPhone', 'Téléphone', { autoComplete: 'tel', type: 'tel' }],
['contactEmail', 'E-mail (votre identifiant)', { autoComplete: 'email', type: 'email' }],
] as const;
type Values = Record<(typeof FIELDS)[number][0] | 'password', string>;
/**
* Inscription en ligne (lien « Choisir » de la page Tarif) : formule, magasin,
* identifiants, puis paiement Stripe. Le magasin et le compte Dirigeant sont
* créés automatiquement dès le paiement validé.
*/
export function SignupPage() {
const [params] = useSearchParams();
const wanted = (params.get('formule') ?? '').toUpperCase() as Plan;
const [plan, setPlan] = useState<Plan>(PLANS.includes(wanted) ? wanted : 'PRO');
const [interval, setInterval] = useState<BillingInterval>(params.get('periode') === 'annuel' ? 'YEAR' : 'MONTH');
const [catalog, setCatalog] = useState<PlanInfo[]>([]);
const [v, setV] = useState<Values>({ name: '', siret: '', addressLine: '', postalCode: '', city: '', contactName: '', contactPhone: '', contactEmail: '', password: '' });
const [cgv, setCgv] = useState(false);
const [error, setError] = useState<string | null>(params.get('annule') ? 'Paiement annulé : rien n’a été prélevé. Vous pouvez reprendre quand vous voulez.' : null);
const [busy, setBusy] = useState(false);
useEffect(() => {
publicApi.get<PlanInfo[]>('/api/public/signup/plans').then(setCatalog).catch(() => undefined);
}, []);
async function submit(e: FormEvent) {
e.preventDefault();
setBusy(true);
setError(null);
try {
const { url } = await publicApi.post<{ url: string }>('/api/public/signup', { ...v, plan, interval, cgv });
window.location.assign(url);
} catch (err) {
setError((err as Error).message);
setBusy(false);
window.scrollTo({ top: 0, behavior: 'smooth' });
}
}
const current = catalog.find((c) => c.plan === plan);
return (
<main style={{ minHeight: '100vh', padding: '32px 16px' }}>
<form onSubmit={submit} style={{ maxWidth: 720, margin: '0 auto', display: 'flex', flexDirection: 'column', gap: 24 }}>
<a href="https://monespacepro.eu/tarif/" style={{ textDecoration: 'none', color: 'inherit' }}>
<Brand admin={false} />
</a>
<div>
<h1>Créer mon programme de fidélité</h1>
<p className="muted" style={{ margin: 0 }}>Sans engagement, résiliable à tout moment. Votre espace est prêt dès le paiement validé.</p>
</div>
{error && <div className="alert error" role="alert">{error}</div>}
<section className="card" style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
<h2>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 className="mode-cards" role="radiogroup" aria-label="Formule">
{(catalog.length ? catalog : PLANS.map((p) => ({ plan: p, name: PLAN_LABEL[p], tagline: '', priceCents: { MONTH: 0, YEAR: 0 }, modules: [], limits: { maxStaff: null } }))).map((c) => (
<label key={c.plan} className="mode-card" style={{ flexDirection: 'column', gap: 6 }}>
<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>
</span>
{c.priceCents[interval] > 0 && (
<span style={{ fontSize: 22, fontWeight: 800 }}>
{euros(c.priceCents[interval])}
<span className="muted" style={{ fontSize: 14, fontWeight: 500 }}> / {interval === 'YEAR' ? 'an' : 'mois'}</span>
</span>
)}
<span className="muted" style={{ fontSize: 14 }}>{c.tagline}</span>
</label>
))}
</div>
{current && (
<p className="muted" style={{ margin: 0, fontSize: 14 }}>
{current.limits.maxStaff ? `${current.limits.maxStaff} employés` : 'Employés illimités'} ·{' '}
{current.modules.length ? `Modules : ${current.modules.map((m) => m.name).join(', ')}` : 'Sans module complémentaire'}
</p>
)}
</section>
<section className="card" style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
<h2>Votre commerce</h2>
{FIELDS.map(([k, label, props]) => (
<div className="field" key={k}>
<label htmlFor={`s-${k}`}>{label} *</label>
<input id={`s-${k}`} className="input" required value={v[k]} onChange={(e) => setV({ ...v, [k]: e.target.value })} {...props} />
</div>
))}
<div className="field">
<label htmlFor="s-password">Mot de passe *</label>
<input
id="s-password"
className="input"
type="password"
required
minLength={10}
autoComplete="new-password"
value={v.password}
onChange={(e) => setV({ ...v, password: e.target.value })}
/>
<span className="muted" style={{ fontSize: 14 }}>10 caractères minimum. Il ouvre votre espace web et l’app MonEspacePro Pro.</span>
</div>
</section>
<label className="row" style={{ gap: 10, alignItems: 'flex-start' }}>
<input type="checkbox" required checked={cgv} onChange={(e) => setCgv(e.target.checked)} style={{ marginTop: 4 }} />
<span>
J’accepte les <a href="https://monespacepro.eu/cgv/" target="_blank" rel="noreferrer">conditions générales de vente</a> et la{' '}
<a href="https://monespacepro.eu/confidentialite/" target="_blank" rel="noreferrer">politique de confidentialité</a>.
</span>
</label>
<button className="btn" disabled={busy}>{busy ? 'Redirection vers le paiement…' : 'Continuer vers le paiement'}</button>
<p className="muted" style={{ margin: 0, fontSize: 14, textAlign: 'center' }}>
Paiement sécurisé par Stripe (carte ou prélèvement SEPA). Déjà inscrit ? <Link to="/espace">Se connecter</Link>
</p>
</form>
</main>
);
}

View file

@ -156,7 +156,7 @@ function NewStaffForm({ base, onCancel, onCreated }: { base: string; onCancel: (
<strong>{ROLE_LABEL[r]}</strong> <strong>{ROLE_LABEL[r]}</strong>
<br /> <br />
<span className="muted" style={{ fontSize: 14 }}> <span className="muted" style={{ fontSize: 14 }}>
{r === 'MANAGER' ? 'Voit toutes les opérations du magasin' : 'Scanne et crédite, voit ses opérations'} {r === 'MANAGER' ? 'Toute la configuration : carte, modules, campagnes, employés, statistiques' : 'Scanne les cartes et crédite les points, voit ses opérations'}
</span> </span>
</span> </span>
</label> </label>

View file

@ -13,6 +13,8 @@ SEED_ADMIN_PASSWORD=
PUBLIC_URL=http://localhost:3100 PUBLIC_URL=http://localhost:3100
# Adresse des pages clients (/c/…, /carte/…). Production : WEB_URL=https://monespacepro.eu # Adresse des pages clients (/c/…, /carte/…). Production : WEB_URL=https://monespacepro.eu
WEB_URL= WEB_URL=
# Admin et espace web des commerçants (/inscription, /espace). Défaut : https://admin.monespacepro.eu
ADMIN_URL=
# Apple Wallet — fichiers PEM hors du dépôt (voir docs/wallet.md) # Apple Wallet — fichiers PEM hors du dépôt (voir docs/wallet.md)
APPLE_PASS_TYPE_ID= APPLE_PASS_TYPE_ID=

View file

@ -1,4 +1,4 @@
import { Body, Controller, HttpCode, Post } from '@nestjs/common'; import { Body, Controller, Get, HttpCode, Post } from '@nestjs/common';
import { ConfigService } from '@nestjs/config'; import { ConfigService } from '@nestjs/config';
import { PickType } from '@nestjs/mapped-types'; import { PickType } from '@nestjs/mapped-types';
import { Throttle } from '@nestjs/throttler'; import { Throttle } from '@nestjs/throttler';
@ -6,6 +6,7 @@ import { BillingInterval, Plan } from '@prisma/client';
import { Equals, IsEnum, IsString, Length } from 'class-validator'; import { Equals, IsEnum, IsString, Length } from 'class-validator';
import { CreateStoreDto } from '../stores/dto/store.dto'; import { CreateStoreDto } from '../stores/dto/store.dto';
import { BillingService } from '../billing/billing.service'; import { BillingService } from '../billing/billing.service';
import { publicCatalog } from '../billing/plans';
import { SignupService } from './signup.service'; import { SignupService } from './signup.service';
class SignupDto extends PickType(CreateStoreDto, ['name', 'siret', 'addressLine', 'postalCode', 'city', 'contactName', 'contactEmail', 'contactPhone'] as const) { class SignupDto extends PickType(CreateStoreDto, ['name', 'siret', 'addressLine', 'postalCode', 'city', 'contactName', 'contactEmail', 'contactPhone'] as const) {
@ -32,6 +33,12 @@ export class SignupController {
private config: ConfigService, private config: ConfigService,
) {} ) {}
/** Formules et prix affichés sur le formulaire d'inscription. */
@Get('plans')
plans() {
return publicCatalog();
}
@Post() @Post()
@HttpCode(200) @HttpCode(200)
@Throttle({ default: { limit: 5, ttl: 10 * 60_000 } }) @Throttle({ default: { limit: 5, ttl: 10 * 60_000 } })

View file

@ -78,6 +78,14 @@ Si `node` est introuvable depuis cron, le journal donne le chemin exact à ajout
Mise à jour de l'admin : `npm run build` puis remplacer les fichiers. Pas de redémarrage. Mise à jour de l'admin : `npm run build` puis remplacer les fichiers. Pas de redémarrage.
Ce même site sert aussi les commerçants (aucune configuration en plus) :
- `/inscription` : inscription en ligne, liée depuis les boutons « Choisir » de la page Tarif ;
- `/espace` : espace web du Dirigeant (conception de la carte), mêmes identifiants que l'app Pro.
Après le paiement Stripe, le webhook `checkout.session.completed` (déjà abonné) crée le magasin, l'abonnement et le compte
Dirigeant, puis envoie l'e-mail de bienvenue. Le magasin s'ouvre tout seul dès que la carte est enregistrée.
Si le site admin change d'adresse, renseigner `ADMIN_URL` dans le `.env` de l'API.
## 5 bis. Site vitrine `monespacepro.eu` + pages clients ## 5 bis. Site vitrine `monespacepro.eu` + pages clients
Les liens montrés aux clients (QR d'inscription `/c/<slug>`, lien de la carte `/carte/<n°>`) sont sur **monespacepro.eu** Les liens montrés aux clients (QR d'inscription `/c/<slug>`, lien de la carte `/carte/<n°>`) sont sur **monespacepro.eu**
(`WEB_URL=https://monespacepro.eu` dans le `.env` de l'API). Le site vitrine est statique ; nginx transmet ces chemins à l'API. (`WEB_URL=https://monespacepro.eu` dans le `.env` de l'API). Le site vitrine est statique ; nginx transmet ces chemins à l'API.

View file

@ -52,6 +52,8 @@ function Navigator() {
<Stack.Screen name="stats" options={{ title: 'Statistiques' }} /> <Stack.Screen name="stats" options={{ title: 'Statistiques' }} />
<Stack.Screen name="loyalty" options={{ title: 'Modules' }} /> <Stack.Screen name="loyalty" options={{ title: 'Modules' }} />
<Stack.Screen name="module/[id]" options={{ title: 'Module' }} /> <Stack.Screen name="module/[id]" options={{ title: 'Module' }} />
<Stack.Screen name="team" options={{ title: 'Employés' }} />
<Stack.Screen name="account" options={{ title: 'Mon compte' }} />
</Stack.Protected> </Stack.Protected>
</Stack> </Stack>
); );

51
pro/app/account.tsx Normal file
View file

@ -0,0 +1,51 @@
import { useState } from 'react';
import { ScrollView, TextInput } from 'react-native';
import { api } from '../src/api';
import { describe } from '../src/errors';
import { useSession } from '../src/session';
import { Banner, Button, T } from '../src/ui';
import { font, useColors } from '../src/theme';
/** Mon compte : changement du mot de passe (tous les rôles). */
export default function Account() {
const c = useColors();
const { me } = useSession();
const [current, setCurrent] = useState('');
const [next, setNext] = useState('');
const [error, setError] = useState<string | null>(null);
const [done, setDone] = useState(false);
const [busy, setBusy] = useState(false);
async function save() {
setBusy(true);
setError(null);
setDone(false);
try {
await api.post('/api/staff/password', { current, next });
setCurrent('');
setNext('');
setDone(true);
} catch (e) {
setError(describe(e).detail);
} finally {
setBusy(false);
}
}
const input = { borderWidth: 1, borderColor: c.border, borderRadius: 14, padding: 14, backgroundColor: c.surface, color: c.text, fontFamily: font.regular, fontSize: 16 } as const;
return (
<ScrollView contentContainerStyle={{ padding: 20, gap: 14 }} keyboardShouldPersistTaps="handled">
<T v="muted">
{me?.displayName} · {me?.role === 'MANAGER' ? 'Dirigeant' : 'Employé'}
</T>
{error && <Banner tone="error">{error}</Banner>}
{done && <Banner tone="ok">Mot de passe modifié.</Banner>}
<T v="label">Mot de passe actuel</T>
<TextInput value={current} onChangeText={setCurrent} secureTextEntry autoComplete="current-password" accessibilityLabel="Mot de passe actuel" style={input} />
<T v="label">Nouveau mot de passe</T>
<TextInput value={next} onChangeText={setNext} secureTextEntry autoComplete="new-password" accessibilityLabel="Nouveau mot de passe" style={input} />
<T v="muted" style={{ fontSize: 13 }}>10 caractères minimum.</T>
<Button label="Changer le mot de passe" onPress={save} loading={busy} disabled={!current || next.length < 10} />
</ScrollView>
);
}

View file

@ -8,12 +8,13 @@ import { Banner, Button, Card, T } from '../src/ui';
import { font, useColors } from '../src/theme'; import { font, useColors } from '../src/theme';
interface Overview { interface Overview {
defaultTitle: string;
allowed: boolean; allowed: boolean;
maxLength: number; maxLength: number;
minIntervalHours: number; minIntervalHours: number;
audience: { cards: number; appleDevices: number }; audience: { cards: number; appleDevices: number };
nextAllowedAt: string | null; nextAllowedAt: string | null;
items: { id: string; message: string; sentByName: string; cards: number; createdAt: string }[]; items: { id: string; title: string | null; message: string; sentByName: string; cards: number; createdAt: string }[];
} }
const when = (d: string) => const when = (d: string) =>
@ -25,6 +26,7 @@ export default function Campaigns() {
const store = useStore(); const store = useStore();
const [data, setData] = useState<Overview | null>(null); const [data, setData] = useState<Overview | null>(null);
const [message, setMessage] = useState(''); const [message, setMessage] = useState('');
const [title, setTitle] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [sent, setSent] = useState(false); const [sent, setSent] = useState(false);
const [busy, setBusy] = useState(false); const [busy, setBusy] = useState(false);
@ -46,7 +48,7 @@ export default function Campaigns() {
const blocked = !data || !data.allowed || !!data.nextAllowedAt; const blocked = !data || !data.allowed || !!data.nextAllowedAt;
const send = () => const send = () =>
Alert.alert('Envoyer la campagne ?', `${data!.audience.cards} cartes de ${store.name} recevront :\n\n« ${text} »`, [ Alert.alert('Envoyer la campagne ?', `${data!.audience.cards} cartes de ${store.name} recevront :\n\n${(title ?? data!.defaultTitle).trim()}\n« ${text} »`, [
{ text: 'Annuler', style: 'cancel' }, { text: 'Annuler', style: 'cancel' },
{ {
text: 'Envoyer', text: 'Envoyer',
@ -54,7 +56,7 @@ export default function Campaigns() {
setBusy(true); setBusy(true);
setError(null); setError(null);
try { try {
await api.post('/api/staff/campaigns', { message: text }); await api.post('/api/staff/campaigns', { message: text, title: (title ?? data!.defaultTitle).trim() });
setMessage(''); setMessage('');
setSent(true); setSent(true);
await load(); await load();
@ -77,6 +79,19 @@ export default function Campaigns() {
Votre message apparaît en notification sur le téléphone de vos clients et reste visible sur leur carte. Votre message apparaît en notification sur le téléphone de vos clients et reste visible sur leur carte.
{data ? ` ${data.audience.cards} cartes au total.` : ''} {data ? ` ${data.audience.cards} cartes au total.` : ''}
</T> </T>
<T v="label">Titre de la notification</T>
<TextInput
value={title ?? data?.defaultTitle ?? ''}
onChangeText={setTitle}
editable={!blocked && !busy}
maxLength={40}
placeholder={store.name}
placeholderTextColor={c.text3}
accessibilityLabel="Titre de la notification"
style={{ borderWidth: 1, borderColor: c.border, borderRadius: 14, padding: 14, backgroundColor: c.surface, color: c.text, fontFamily: font.regular, fontSize: 17, opacity: blocked ? 0.6 : 1 }}
/>
<T v="muted" style={{ fontSize: 13, marginTop: -8 }}>Affiché sur Google Wallet ; sur iPhone, le nom du magasin apparaît toujours.</T>
<T v="label">Message</T>
<TextInput <TextInput
value={message} value={message}
onChangeText={setMessage} onChangeText={setMessage}
@ -109,6 +124,7 @@ export default function Campaigns() {
<T v="h2">Campagnes envoyées</T> <T v="h2">Campagnes envoyées</T>
{data.items.map((i) => ( {data.items.map((i) => (
<Card key={i.id} style={{ padding: 14, gap: 4 }}> <Card key={i.id} style={{ padding: 14, gap: 4 }}>
{!!i.title && <T v="label">{i.title}</T>}
<T>{i.message}</T> <T>{i.message}</T>
<T v="muted" style={{ fontSize: 13 }}> <T v="muted" style={{ fontSize: 13 }}>
{when(i.createdAt)} · {i.sentByName} · {i.cards} cartes {when(i.createdAt)} · {i.sentByName} · {i.cards} cartes

View file

@ -1,8 +1,10 @@
import { ActivityIndicator, View } from 'react-native'; import { useState } from 'react';
import { ActivityIndicator, Alert, View } from 'react-native';
import { router } from 'expo-router'; import { router } from 'expo-router';
import { useStore } from '../../../src/session'; import { useStore } from '../../../src/session';
import { useCard } from '../../../src/useCard'; import { useCard } from '../../../src/useCard';
import { ErrorScreen } from '../../../src/errors'; import { api, CardInfo } from '../../../src/api';
import { describe, ErrorScreen } from '../../../src/errors';
import { Banner, Button, Card, Screen, T, unit } from '../../../src/ui'; import { Banner, Button, Card, Screen, T, unit } from '../../../src/ui';
import { font, useColors } from '../../../src/theme'; import { font, useColors } from '../../../src/theme';
@ -19,7 +21,8 @@ function ago(iso: string) {
export default function ClientCard() { export default function ClientCard() {
const c = useColors(); const c = useColors();
const store = useStore(); const store = useStore();
const { serial, card, error, reload } = useCard(); const { serial, card, setCard, error, reload } = useCard();
const [giving, setGiving] = useState<string | null>(null);
if (error) return <ErrorScreen error={error} onRetry={reload} />; if (error) return <ErrorScreen error={error} onRetry={reload} />;
if (!card) return <Screen style={{ justifyContent: 'center' }}><ActivityIndicator /></Screen>; if (!card) return <Screen style={{ justifyContent: 'center' }}><ActivityIndicator /></Screen>;
@ -27,6 +30,25 @@ export default function ClientCard() {
const mode = store.design.pointsMode; const mode = store.design.pointsMode;
const cheapest = store.design.rewards[0]; const cheapest = store.design.rewards[0];
const reachable = store.design.rewards.filter((r) => r.cost <= card.balance).length; const reachable = store.design.rewards.filter((r) => r.cost <= card.balance).length;
const SOURCE = { BIRTHDAY: 'Anniversaire', REFERRAL: 'Parrainage', REFERRAL_FRIEND: 'Bienvenue (parrainage)' } as const;
const give = (g: CardInfo['gifts'][number]) =>
Alert.alert('Remettre le cadeau ?', `« ${g.label} » à ${card.firstName}`, [
{ text: 'Annuler', style: 'cancel' },
{
text: 'Remis',
onPress: async () => {
setGiving(g.id);
try {
setCard(await api.post<CardInfo>(`/api/staff/cards/${encodeURIComponent(serial)}/gifts/${g.id}/use`));
} catch (e) {
Alert.alert('Impossible', describe(e).detail);
} finally {
setGiving(null);
}
},
},
]);
return ( return (
<Screen scroll> <Screen scroll>
@ -52,6 +74,18 @@ export default function ClientCard() {
</T> </T>
) : null} ) : null}
{card.gifts?.map((g) => (
<Card key={g.id} style={{ padding: 14, gap: 10, borderColor: c.ok }}>
<View style={{ gap: 2 }}>
<T v="label">🎁 {g.label}</T>
<T v="muted" style={{ fontSize: 13 }}>
{SOURCE[g.source]} · {new Date(g.createdAt).toLocaleDateString('fr-FR', { day: 'numeric', month: 'short' })}
</T>
</View>
<Button label="Marquer comme remis" variant="secondary" loading={giving === g.id} onPress={() => give(g)} />
</Card>
))}
{card.nextCreditAt && ( {card.nextCreditAt && (
<Banner tone="warn"> <Banner tone="warn">
Déjà créditée récemment : nouveau crédit possible à{' '} Déjà créditée récemment : nouveau crédit possible à{' '}

View file

@ -1,11 +1,11 @@
import { useCallback, useState } from 'react'; import { useCallback, useState } from 'react';
import { Alert, Pressable, RefreshControl, ScrollView, View } from 'react-native'; import { Alert, Linking, Pressable, RefreshControl, ScrollView, View } from 'react-native';
import { router, useFocusEffect } from 'expo-router'; import { router, useFocusEffect } from 'expo-router';
import { SafeAreaView } from 'react-native-safe-area-context'; import { SafeAreaView } from 'react-native-safe-area-context';
import Svg, { Path } from 'react-native-svg'; import Svg, { Path } from 'react-native-svg';
import { api, Summary } from '../src/api'; import { api, Summary } from '../src/api';
import { useSession, useStore } from '../src/session'; import { useSession, useStore } from '../src/session';
import { BrandSymbol, Button, Card, T, unit } from '../src/ui'; import { Banner, BrandSymbol, Button, Card, T, unit } from '../src/ui';
import { font, useColors } from '../src/theme'; import { font, useColors } from '../src/theme';
function ScanIcon({ color }: { color: string }) { function ScanIcon({ color }: { color: string }) {
@ -16,7 +16,44 @@ function ScanIcon({ color }: { color: string }) {
); );
} }
/** Adresse de l'espace web du Dirigeant (conception de la carte). */
const ESPACE_URL = 'https://admin.monespacepro.eu/espace';
export default function Home() { export default function Home() {
const { me } = useSession();
// Magasin inscrit en ligne : tant que la carte n'est pas conçue, pas de scan possible.
return me?.store.cardDesign ? <Counter /> : <NoCardYet />;
}
function NoCardYet() {
const c = useColors();
const { me, logout, reload } = useSession();
const isManager = me?.role === 'MANAGER';
return (
<SafeAreaView style={{ flex: 1, backgroundColor: c.bg }}>
<ScrollView contentContainerStyle={{ padding: 20, gap: 16, flexGrow: 1 }}>
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 12 }}>
<BrandSymbol size={36} />
<T v="label" style={{ flex: 1 }} numberOfLines={1}>{me?.store.name}</T>
</View>
<Banner tone="warn">
{isManager
? 'Concevez votre carte de fidélité (logo, couleurs, récompenses) sur votre espace web : le scan des cartes s’active ensuite.'
: 'La carte de fidélité du magasin n’est pas encore prête. Revenez un peu plus tard.'}
</Banner>
{isManager && <Button label="Ouvrir mon espace web" onPress={() => Linking.openURL(ESPACE_URL)} />}
<Button label="Actualiser" variant="secondary" onPress={reload} />
{isManager && <Button label="Employés" variant="secondary" onPress={() => router.push('/team')} />}
{isManager && <Button label="Modules" variant="secondary" onPress={() => router.push('/loyalty')} />}
<View style={{ flex: 1 }} />
<Button label="Mon compte" variant="secondary" onPress={() => router.push('/account')} />
<Button label="Se déconnecter" variant="secondary" onPress={logout} />
</ScrollView>
</SafeAreaView>
);
}
function Counter() {
const c = useColors(); const c = useColors();
const { me, logout } = useSession(); const { me, logout } = useSession();
const store = useStore(); const store = useStore();
@ -113,8 +150,11 @@ export default function Home() {
<View style={{ flex: 1 }} /> <View style={{ flex: 1 }} />
{isManager && <Button label="Modules" variant="secondary" onPress={() => router.push('/loyalty')} />} {isManager && <Button label="Modules" variant="secondary" onPress={() => router.push('/loyalty')} />}
{isManager && <Button label="Campagnes" variant="secondary" onPress={() => router.push('/campaigns')} />}
{isManager && <Button label="Employés" variant="secondary" onPress={() => router.push('/team')} />}
{isManager && <Button label="Statistiques" variant="secondary" onPress={() => router.push('/stats')} />} {isManager && <Button label="Statistiques" variant="secondary" onPress={() => router.push('/stats')} />}
<Button label="Historique des opérations" variant="secondary" onPress={() => router.push('/history')} /> <Button label="Historique des opérations" variant="secondary" onPress={() => router.push('/history')} />
<Button label="Mon compte" variant="secondary" onPress={() => router.push('/account')} />
</ScrollView> </ScrollView>
</SafeAreaView> </SafeAreaView>
); );

158
pro/app/team.tsx Normal file
View file

@ -0,0 +1,158 @@
import { useCallback, useState } from 'react';
import { Alert, Pressable, ScrollView, Share, TextInput, View } from 'react-native';
import { useFocusEffect } from 'expo-router';
import { api } from '../src/api';
import { describe } from '../src/errors';
import { useSession } from '../src/session';
import { Banner, Button, Card, T } from '../src/ui';
import { font, useColors } from '../src/theme';
type Role = 'MANAGER' | 'EMPLOYEE';
interface Member {
id: string;
email: string;
displayName: string;
role: Role;
active: boolean;
provisionalPassword?: string;
}
const ROLE: Record<Role, [string, string]> = {
EMPLOYEE: ['Employé', 'Scanne les cartes et crédite les points'],
MANAGER: ['Dirigeant', 'Toute la configuration : modules, campagnes, employés, statistiques'],
};
/** Employés du magasin (Dirigeant) : création avec rôle, désactivation, nouveau mot de passe. */
export default function Team() {
const c = useColors();
const { me } = useSession();
const [list, setList] = useState<Member[] | null>(null);
const [error, setError] = useState<string | null>(null);
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [role, setRole] = useState<Role>('EMPLOYEE');
const [busy, setBusy] = useState(false);
const [created, setCreated] = useState<Member | null>(null);
const load = useCallback(async () => {
try {
setList(await api.get<Member[]>('/api/staff/team'));
} catch (e) {
setError(describe(e).detail);
}
}, []);
useFocusEffect(
useCallback(() => {
load();
}, [load]),
);
async function run(fn: () => Promise<unknown>) {
setError(null);
try {
await fn();
await load();
} catch (e) {
setError(describe(e).detail);
}
}
async function create() {
setBusy(true);
setCreated(null);
await run(async () => {
setCreated(await api.post<Member>('/api/staff/team', { displayName: name.trim(), email: email.trim(), role }));
setName('');
setEmail('');
setRole('EMPLOYEE');
});
setBusy(false);
}
const input = { borderWidth: 1, borderColor: c.border, borderRadius: 14, padding: 14, backgroundColor: c.surface, color: c.text, fontFamily: font.regular, fontSize: 16 } as const;
return (
<ScrollView contentContainerStyle={{ padding: 20, gap: 16 }} keyboardShouldPersistTaps="handled">
{error && <Banner tone="error">{error}</Banner>}
{created?.provisionalPassword && (
<Card style={{ padding: 16, gap: 8, borderColor: c.ok }}>
<T v="label">Compte créé pour {created.displayName}</T>
<T v="muted">Identifiant : {created.email}</T>
<T style={{ fontFamily: font.bold, fontSize: 22, letterSpacing: 1 }} selectable>{created.provisionalPassword}</T>
<T v="muted" style={{ fontSize: 13 }}>Mot de passe provisoire : il ne sera plus affiché ensuite.</T>
<Button
label="Partager les identifiants"
variant="secondary"
onPress={() => Share.share({ message: `MonEspacePro Pro\nIdentifiant : ${created.email}\nMot de passe : ${created.provisionalPassword}` })}
/>
</Card>
)}
<View style={{ gap: 10 }}>
<T v="h2">Nouvel employé</T>
<TextInput value={name} onChangeText={setName} placeholder="Prénom Nom" placeholderTextColor={c.text3} accessibilityLabel="Prénom et nom" style={input} maxLength={80} />
<TextInput
value={email}
onChangeText={setEmail}
placeholder="prenom@exemple.fr"
placeholderTextColor={c.text3}
accessibilityLabel="E-mail"
autoCapitalize="none"
autoCorrect={false}
keyboardType="email-address"
style={input}
/>
{(['EMPLOYEE', 'MANAGER'] as const).map((r) => (
<Pressable key={r} accessibilityRole="radio" accessibilityState={{ checked: role === r }} onPress={() => setRole(r)}>
<Card style={{ padding: 14, gap: 2, borderWidth: 2, borderColor: role === r ? c.primary : c.border }}>
<T v="label">{ROLE[r][0]}</T>
<T v="muted" style={{ fontSize: 13 }}>{ROLE[r][1]}</T>
</Card>
</Pressable>
))}
<Button label="Créer le compte" onPress={create} loading={busy} disabled={name.trim().length < 2 || !email.includes('@')} />
</View>
<View style={{ gap: 10, marginTop: 8 }}>
<T v="h2">Comptes</T>
{list?.map((m) => {
const self = m.id === me?.id;
return (
<Card key={m.id} style={{ padding: 14, gap: 8, opacity: m.active ? 1 : 0.6 }}>
<View>
<T v="label">
{m.displayName}
{self ? ' (vous)' : ''}
</T>
<T v="muted" style={{ fontSize: 13 }}>
{m.email} · {ROLE[m.role][0]}
{m.active ? '' : ' · désactivé'}
</T>
</View>
{!self && (
<View style={{ flexDirection: 'row', gap: 8, flexWrap: 'wrap' }}>
<Button
label={m.role === 'MANAGER' ? 'Passer Employé' : 'Passer Dirigeant'}
variant="secondary"
onPress={() => run(() => api.patch(`/api/staff/team/${m.id}`, { role: m.role === 'MANAGER' ? 'EMPLOYEE' : 'MANAGER' }))}
/>
<Button label={m.active ? 'Désactiver' : 'Réactiver'} variant="secondary" onPress={() => run(() => api.patch(`/api/staff/team/${m.id}`, { active: !m.active }))} />
<Button
label="Nouveau mot de passe"
variant="secondary"
onPress={() =>
Alert.alert('Nouveau mot de passe ?', `${m.displayName} sera déconnecté(e) de ses appareils.`, [
{ text: 'Annuler', style: 'cancel' },
{ text: 'Générer', onPress: () => run(async () => setCreated(await api.post<Member>(`/api/staff/team/${m.id}/reset-password`))) },
])
}
/>
</View>
)}
</Card>
);
})}
</View>
</ScrollView>
);
}

View file

@ -101,6 +101,7 @@ export const api = {
get: <T>(path: string) => request<T>('GET', path), get: <T>(path: string) => request<T>('GET', path),
post: <T>(path: string, body: unknown = {}) => request<T>('POST', path, body), post: <T>(path: string, body: unknown = {}) => request<T>('POST', path, body),
put: <T>(path: string, body: unknown) => request<T>('PUT', path, body), put: <T>(path: string, body: unknown) => request<T>('PUT', path, body),
patch: <T>(path: string, body: unknown) => request<T>('PATCH', path, body),
}; };
// ── Types de l'API ───────────────────────────────────────────── // ── Types de l'API ─────────────────────────────────────────────
@ -142,6 +143,8 @@ export interface CardInfo {
memberSince: string; memberSince: string;
lastCreditAt: string | null; lastCreditAt: string | null;
nextCreditAt: string | null; nextCreditAt: string | null;
/** Cadeaux en nature à remettre (anniversaire, parrainage). */
gifts: { id: string; label: string; source: 'BIRTHDAY' | 'REFERRAL' | 'REFERRAL_FRIEND'; createdAt: string }[];
} }
export interface Summary { export interface Summary {

View file

@ -21,5 +21,5 @@ export function useCard() {
load(); load();
}, [load]); }, [load]);
return { serial, card, error, reload: load }; return { serial, card, setCard, error, reload: load };
} }

View file

@ -40,6 +40,8 @@ const euros = (cents) =>
(cents / 100).toLocaleString('fr-FR', { minimumFractionDigits: cents % 100 ? 2 : 0, maximumFractionDigits: 2 }).replace(/ /g, '&nbsp;'); (cents / 100).toLocaleString('fr-FR', { minimumFractionDigits: cents % 100 ? 2 : 0, maximumFractionDigits: 2 }).replace(/ /g, '&nbsp;');
const plans = Object.values(PLANS); const plans = Object.values(PLANS);
const min = Math.min(...plans.map((p) => p.priceCents.MONTH)); const min = Math.min(...plans.map((p) => p.priceCents.MONTH));
/** Inscription en ligne (application web, voir admin/src/pages/SignupPage.tsx). */
const SIGNUP_URL = 'https://admin.monespacepro.eu/inscription';
const FROM = `${euros(min)}&nbsp;€`; const FROM = `${euros(min)}&nbsp;€`;
function planCard(def) { function planCard(def) {
@ -53,7 +55,7 @@ ${pro ? '<span class="pill plan-tag">Conseillée</span>' : ''}
<p class="mu" style="min-height:3em">${def.tagline}</p> <p class="mu" style="min-height:3em">${def.tagline}</p>
<p class="plan-price"><span data-price data-month="${euros(def.priceCents.MONTH)}" data-year="${euros(def.priceCents.YEAR)}">${euros(def.priceCents.MONTH)}</span>&nbsp;€<small data-per data-month="/ mois${perStore}" data-year="/ an${perStore}">/ mois${perStore}</small></p> <p class="plan-price"><span data-price data-month="${euros(def.priceCents.MONTH)}" data-year="${euros(def.priceCents.YEAR)}">${euros(def.priceCents.MONTH)}</span>&nbsp;€<small data-per data-month="/ mois${perStore}" data-year="/ an${perStore}">/ mois${perStore}</small></p>
<p class="mu plan-note" data-note data-month="Sans engagement, résiliable à tout moment" data-year="Soit ${monthlyEquivalent}&nbsp;€ par mois — 2 mois offerts">Sans engagement, résiliable à tout moment</p> <p class="mu plan-note" data-note data-month="Sans engagement, résiliable à tout moment" data-year="Soit ${monthlyEquivalent}&nbsp;€ par mois — 2 mois offerts">Sans engagement, résiliable à tout moment</p>
<a href="/contact/?formule=${def.plan.toLowerCase()}" data-plan-link class="${pro ? 'btn' : 'btn2'}" style="width:100%;margin:20px 0 4px">Choisir ${def.name}</a> <a href="${SIGNUP_URL}?formule=${def.plan.toLowerCase()}" data-plan-link class="${pro ? 'btn' : 'btn2'}" style="width:100%;margin:20px 0 4px">Choisir ${def.name}</a>
${m.intro ? `<p style="font-weight:700;margin:20px 0 0">${m.intro}</p>` : ''} ${m.intro ? `<p style="font-weight:700;margin:20px 0 0">${m.intro}</p>` : ''}
<ul class="fl" style="margin-top:${m.intro ? '12px' : '20px'}"> <ul class="fl" style="margin-top:${m.intro ? '12px' : '20px'}">
${m.items ${m.items

View file

@ -43,6 +43,10 @@
document.querySelectorAll('[data-price],[data-per],[data-note]').forEach(function (el) { document.querySelectorAll('[data-price],[data-per],[data-note]').forEach(function (el) {
el.innerHTML = el.getAttribute('data-' + interval); el.innerHTML = el.getAttribute('data-' + interval);
}); });
// Les boutons « Choisir » emportent la périodicité vers l'inscription.
document.querySelectorAll('[data-plan-link]').forEach(function (a) {
a.href = a.href.replace(/&periode=\w+/, '') + (interval === 'year' ? '&periode=annuel' : '');
});
renderSim(); renderSim();
}); });
}); });

View file

@ -95,7 +95,7 @@
<p class="mu" style="min-height:3em">La carte de fidélité dans le Wallet de vos clients</p> <p class="mu" style="min-height:3em">La carte de fidélité dans le Wallet de vos clients</p>
<p class="plan-price"><span data-price data-month="19" data-year="190">19</span>&nbsp;€<small data-per data-month="/ mois" data-year="/ an">/ mois</small></p> <p class="plan-price"><span data-price data-month="19" data-year="190">19</span>&nbsp;€<small data-per data-month="/ mois" data-year="/ an">/ mois</small></p>
<p class="mu plan-note" data-note data-month="Sans engagement, résiliable à tout moment" data-year="Soit 15,83&nbsp;€ par mois — 2 mois offerts">Sans engagement, résiliable à tout moment</p> <p class="mu plan-note" data-note data-month="Sans engagement, résiliable à tout moment" data-year="Soit 15,83&nbsp;€ par mois — 2 mois offerts">Sans engagement, résiliable à tout moment</p>
<a href="/contact/?formule=essentiel" data-plan-link class="btn2" style="width:100%;margin:20px 0 4px">Choisir Essentiel</a> <a href="https://admin.monespacepro.eu/inscription?formule=essentiel" data-plan-link class="btn2" style="width:100%;margin:20px 0 4px">Choisir Essentiel</a>
<ul class="fl" style="margin-top:20px"> <ul class="fl" style="margin-top:20px">
<li><svg class="ico"><use href="#i-check"/></svg><span>La carte à vos couleurs, dans Apple Wallet et Google Wallet</span></li> <li><svg class="ico"><use href="#i-check"/></svg><span>La carte à vos couleurs, dans Apple Wallet et Google Wallet</span></li>
@ -114,7 +114,7 @@
<p class="mu" style="min-height:3em">Faites revenir vos clients</p> <p class="mu" style="min-height:3em">Faites revenir vos clients</p>
<p class="plan-price"><span data-price data-month="39" data-year="390">39</span>&nbsp;€<small data-per data-month="/ mois" data-year="/ an">/ mois</small></p> <p class="plan-price"><span data-price data-month="39" data-year="390">39</span>&nbsp;€<small data-per data-month="/ mois" data-year="/ an">/ mois</small></p>
<p class="mu plan-note" data-note data-month="Sans engagement, résiliable à tout moment" data-year="Soit 32,50&nbsp;€ par mois — 2 mois offerts">Sans engagement, résiliable à tout moment</p> <p class="mu plan-note" data-note data-month="Sans engagement, résiliable à tout moment" data-year="Soit 32,50&nbsp;€ par mois — 2 mois offerts">Sans engagement, résiliable à tout moment</p>
<a href="/contact/?formule=pro" data-plan-link class="btn" style="width:100%;margin:20px 0 4px">Choisir Pro</a> <a href="https://admin.monespacepro.eu/inscription?formule=pro" data-plan-link class="btn" style="width:100%;margin:20px 0 4px">Choisir Pro</a>
<p style="font-weight:700;margin:20px 0 0">Tout Essentiel, plus :</p> <p style="font-weight:700;margin:20px 0 0">Tout Essentiel, plus :</p>
<ul class="fl" style="margin-top:12px"> <ul class="fl" style="margin-top:12px">
<li><svg class="ico"><use href="#i-check"/></svg><span>Employés illimités</span></li> <li><svg class="ico"><use href="#i-check"/></svg><span>Employés illimités</span></li>
@ -136,7 +136,7 @@
<p class="mu" style="min-height:3em">Plusieurs magasins, une seule carte</p> <p class="mu" style="min-height:3em">Plusieurs magasins, une seule carte</p>
<p class="plan-price"><span data-price data-month="29" data-year="290">29</span>&nbsp;€<small data-per data-month="/ mois / magasin" data-year="/ an / magasin">/ mois / magasin</small></p> <p class="plan-price"><span data-price data-month="29" data-year="290">29</span>&nbsp;€<small data-per data-month="/ mois / magasin" data-year="/ an / magasin">/ mois / magasin</small></p>
<p class="mu plan-note" data-note data-month="Sans engagement, résiliable à tout moment" data-year="Soit 24,17&nbsp;€ par mois — 2 mois offerts">Sans engagement, résiliable à tout moment</p> <p class="mu plan-note" data-note data-month="Sans engagement, résiliable à tout moment" data-year="Soit 24,17&nbsp;€ par mois — 2 mois offerts">Sans engagement, résiliable à tout moment</p>
<a href="/contact/?formule=reseau" data-plan-link class="btn2" style="width:100%;margin:20px 0 4px">Choisir Réseau</a> <a href="https://admin.monespacepro.eu/inscription?formule=reseau" data-plan-link class="btn2" style="width:100%;margin:20px 0 4px">Choisir Réseau</a>
<p style="font-weight:700;margin:20px 0 0">Tout Pro, plus :</p> <p style="font-weight:700;margin:20px 0 0">Tout Pro, plus :</p>
<ul class="fl" style="margin-top:12px"> <ul class="fl" style="margin-top:12px">
<li class="soon"><svg class="ico"><use href="#i-check"/></svg><span>Une carte commune à tous vos magasins <span class="soon-tag">Bientôt</span></span></li> <li class="soon"><svg class="ico"><use href="#i-check"/></svg><span>Une carte commune à tous vos magasins <span class="soon-tag">Bientôt</span></span></li>