Compare commits
2 commits
5064421c48
...
226f3cedb8
| Author | SHA1 | Date | |
|---|---|---|---|
| 226f3cedb8 | |||
| bf10beb89b |
63 changed files with 1540 additions and 241 deletions
|
|
@ -6,6 +6,18 @@
|
|||
"runtimeExecutable": "npx",
|
||||
"runtimeArgs": ["--yes", "http-server", "site", "-p", "4300", "-c-1", "--silent"],
|
||||
"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
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,6 +2,9 @@
|
|||
|
||||
const BASE = import.meta.env.VITE_API_URL ?? '';
|
||||
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 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;
|
||||
try {
|
||||
localStorage.setItem(REFRESH_KEY, t.refreshToken);
|
||||
if (kind) localStorage.setItem(KIND_KEY, kind);
|
||||
} catch {
|
||||
/* navigation privée : la session durera le temps de l'onglet */
|
||||
}
|
||||
|
|
@ -41,6 +55,7 @@ export function logout() {
|
|||
accessToken = null;
|
||||
try {
|
||||
localStorage.removeItem(REFRESH_KEY);
|
||||
localStorage.removeItem(KIND_KEY);
|
||||
} catch {
|
||||
/* rien */
|
||||
}
|
||||
|
|
@ -52,9 +67,21 @@ export async function login(email: string, password: string) {
|
|||
email,
|
||||
password,
|
||||
}, 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;
|
||||
async function refresh(): Promise<boolean> {
|
||||
let token: string | null = null;
|
||||
|
|
|
|||
|
|
@ -1,36 +1,55 @@
|
|||
import { StrictMode, useEffect, useState } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { BrowserRouter, Navigate, Route, Routes, useNavigate } from 'react-router-dom';
|
||||
import { hasSession, setLogoutHandler } from './api';
|
||||
import { BrowserRouter, Navigate, Route, Routes, useLocation, useNavigate } from 'react-router-dom';
|
||||
import { SessionKind, sessionKind, setLogoutHandler } from './api';
|
||||
import { Layout } from './components/Layout';
|
||||
import { LoginPage } from './pages/LoginPage';
|
||||
import { StoresPage } from './pages/StoresPage';
|
||||
import { NewStorePage } from './pages/NewStorePage';
|
||||
import { StorePage } from './pages/StorePage';
|
||||
import { PosterPage } from './pages/PosterPage';
|
||||
import { SignupPage } from './pages/SignupPage';
|
||||
import { MerchantLoginPage, MerchantSpace } from './pages/MerchantSpace';
|
||||
import './styles.css';
|
||||
|
||||
function App() {
|
||||
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(() => {
|
||||
setLogoutHandler(() => {
|
||||
setAuthed(false);
|
||||
navigate('/connexion');
|
||||
setKind(null);
|
||||
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 (
|
||||
<Routes>
|
||||
<Route path="/connexion" element={<LoginPage onLogin={() => setAuthed(true)} />} />
|
||||
<Route path="*" element={<Navigate to="/connexion" replace />} />
|
||||
<Route path="/inscription" element={<SignupPage />} />
|
||||
{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>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Routes>
|
||||
<Route path="/espace" element={merchantLogin} />
|
||||
<Route path="/magasins/:id/affichette" element={<PosterPage />} />
|
||||
<Route element={<Layout />}>
|
||||
<Route path="/magasins" element={<StoresPage />} />
|
||||
|
|
|
|||
|
|
@ -14,13 +14,13 @@ interface CatalogEntry {
|
|||
interface Billing {
|
||||
testMode: boolean;
|
||||
catalog: CatalogEntry[];
|
||||
trialDays: number;
|
||||
/** Lien d'abonnement permanent du magasin. */
|
||||
subscribeUrl: string;
|
||||
subscription: {
|
||||
status: SubscriptionStatus;
|
||||
plan: Plan;
|
||||
interval: BillingInterval;
|
||||
legacyPrice: boolean;
|
||||
trialEndsAt: string | null;
|
||||
cancelAtPeriodEnd: boolean;
|
||||
currentPeriodEnd: string | null;
|
||||
hasCustomer: boolean;
|
||||
|
|
@ -48,9 +48,8 @@ export function BillingTab({ storeId, contactEmail, onChange }: { storeId: strin
|
|||
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>('PRO');
|
||||
const [interval, setInterval] = useState<BillingInterval>('MONTH');
|
||||
const [trial, setTrial] = useState(true);
|
||||
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));
|
||||
|
|
@ -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>;
|
||||
const sub = data.subscription;
|
||||
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;
|
||||
// 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 (
|
||||
<>
|
||||
|
|
@ -96,11 +96,10 @@ export function BillingTab({ storeId, contactEmail, onChange }: { storeId: strin
|
|||
</div>
|
||||
<span className={`badge ${sub ? STATUS[sub.status][1] : 'DRAFT'}`}>{sub ? STATUS[sub.status][0] : 'Aucun abonnement'}</span>
|
||||
</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 && (
|
||||
<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>
|
||||
)}
|
||||
{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">
|
||||
<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>
|
||||
<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={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>
|
||||
{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>
|
||||
{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 }}>
|
||||
|
|
@ -154,22 +153,16 @@ export function BillingTab({ storeId, contactEmail, onChange }: { storeId: strin
|
|||
</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 }}>
|
||||
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).
|
||||
</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 })}>
|
||||
<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, interval, trial: trial && !trialUsed, sendEmail: false })}>
|
||||
Créer le lien sans l'envoyer
|
||||
<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>
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import { useCallback, useEffect, useState } from 'react';
|
|||
import { api } from '../api';
|
||||
|
||||
interface Campaign {
|
||||
title: string | null;
|
||||
id: string;
|
||||
message: string;
|
||||
sentByName: string;
|
||||
|
|
@ -11,6 +12,7 @@ interface Campaign {
|
|||
}
|
||||
|
||||
interface Overview {
|
||||
defaultTitle: string;
|
||||
allowed: boolean;
|
||||
maxLength: number;
|
||||
minIntervalHours: number;
|
||||
|
|
@ -26,6 +28,7 @@ const when = (d: string) =>
|
|||
export function CampaignSender({ storeId, storeName }: { storeId: string; storeName: string }) {
|
||||
const [data, setData] = useState<Overview | null>(null);
|
||||
const [message, setMessage] = useState('');
|
||||
const [title, setTitle] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [notice, setNotice] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
|
@ -45,7 +48,7 @@ export function CampaignSender({ storeId, storeName }: { storeId: string; storeN
|
|||
setBusy(true);
|
||||
setError(null);
|
||||
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('');
|
||||
setNotice('Campagne envoyée. Les cartes se mettent à jour dans les minutes qui suivent.');
|
||||
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).
|
||||
</p>
|
||||
</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
|
||||
id="campaign-msg"
|
||||
className="input"
|
||||
|
|
@ -81,7 +96,7 @@ export function CampaignSender({ storeId, storeName }: { storeId: string; storeN
|
|||
disabled={blocked || busy}
|
||||
/>
|
||||
<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}>
|
||||
{busy ? 'Envoi…' : 'Envoyer la campagne'}
|
||||
</button>
|
||||
|
|
@ -108,7 +123,7 @@ export function CampaignSender({ storeId, storeName }: { storeId: string; storeN
|
|||
{data.items.map((c) => (
|
||||
<tr key={c.id}>
|
||||
<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 className="num">{c.cards}</td>
|
||||
</tr>
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ const STEPS = ['Identité', 'Couleurs', 'Règle de points', 'Récompenses', 'Ré
|
|||
|
||||
type Draft = Omit<CardDesign, 'logoUrl' | 'stripUrl'>;
|
||||
|
||||
function defaults(store: StoreDetail): Draft {
|
||||
function defaults(store: Pick<StoreDetail, 'name'>): Draft {
|
||||
return {
|
||||
programName: `Fidélité ${store.name}`.slice(0, 40),
|
||||
backgroundColor: '#1F2937',
|
||||
|
|
@ -21,8 +21,25 @@ function defaults(store: StoreDetail): Draft {
|
|||
};
|
||||
}
|
||||
|
||||
export function CardWizard({ store, onSaved }: { store: StoreDetail; onSaved: () => void }) {
|
||||
const base = `/api/admin/stores/${store.id}/card-design`;
|
||||
type WizardStore = Pick<StoreDetail, 'id' | 'name' | 'status' | 'enrollUrl'>;
|
||||
|
||||
/**
|
||||
* 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 [draft, setDraft] = useState<Draft | null>(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' }}>
|
||||
<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>
|
||||
<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>
|
||||
{store.status === 'DRAFT' && (
|
||||
<p style={{ margin: 0 }}>
|
||||
Utilisez le bouton <strong>Activer</strong> en haut de la fiche pour ouvrir le programme.
|
||||
</p>
|
||||
)}
|
||||
{store.status === 'DRAFT' &&
|
||||
(draftNote ?? (
|
||||
<p style={{ margin: 0 }}>
|
||||
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>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
|
||||
|
|
|
|||
137
admin/src/pages/MerchantSpace.tsx
Normal file
137
admin/src/pages/MerchantSpace.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
|
|
@ -214,7 +214,7 @@ export function ModulesTab({ storeId, storeName }: { storeId: string; storeName:
|
|||
<>
|
||||
<p className="muted" style={{ margin: 0 }}>
|
||||
{active} module(s) actif(s) sur {list.length}. Chaque module est inclus ou non dans la formule ; vous pouvez l'ajouter ou le retirer sur mesure,
|
||||
et tous ses textes et réglages sont personnalisables. Le gérant peut aussi les régler depuis l'app Pro.
|
||||
et tous ses textes et réglages sont personnalisables. Le dirigeant peut aussi les régler depuis l'app Pro.
|
||||
</p>
|
||||
{list.map((m) => (
|
||||
<ModulePanel key={m.id} storeId={storeId} storeName={storeName} initial={m} onChanged={load} />
|
||||
|
|
|
|||
|
|
@ -1,24 +1,78 @@
|
|||
import { useState } from 'react';
|
||||
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';
|
||||
|
||||
type Created = Store & { manager: StaffUser | null; link: { url: string | null; emailedTo: string | null; error?: string } };
|
||||
|
||||
export function NewStorePage() {
|
||||
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 (
|
||||
<>
|
||||
<div>
|
||||
<Link to="/magasins">← Magasins</Link>
|
||||
<h1>Nouveau magasin</h1>
|
||||
<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>
|
||||
</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
|
||||
initial={EMPTY_STORE}
|
||||
submitLabel="Créer le magasin"
|
||||
onSubmit={async (v) => {
|
||||
const store = await api.post<Store>('/api/admin/stores', v);
|
||||
navigate(`/magasins/${store.id}/carte`);
|
||||
setCreated(await api.post<Created>('/api/admin/stores', { ...v, plan, interval }));
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
|
|
|
|||
|
|
@ -4,8 +4,10 @@ import { api, assetUrl, CardDesign, StoreDetail } from '../api';
|
|||
import { Poster, PosterFormat } from '../components/Poster';
|
||||
|
||||
/** 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 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 format: PosterFormat = params.get('format') === 'A6' ? 'A6' : 'A5';
|
||||
const [store, setStore] = useState<StoreDetail | null>(null);
|
||||
|
|
@ -13,13 +15,13 @@ export function PosterPage() {
|
|||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
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]) => {
|
||||
setStore(s);
|
||||
setDesign(d);
|
||||
})
|
||||
.catch((e) => setError(e.message));
|
||||
}, [id]);
|
||||
}, [storePath, designPath]);
|
||||
|
||||
if (error) return <div className="alert error" style={{ margin: 24 }}>{error}</div>;
|
||||
if (!store) return <p className="muted" style={{ margin: 24 }}>Chargement…</p>;
|
||||
|
|
@ -29,7 +31,7 @@ export function PosterPage() {
|
|||
<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>
|
||||
<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 }}>
|
||||
{(['A5', 'A6'] as const).map((f) => (
|
||||
<button key={f} type="button" className="chip" aria-pressed={format === f} onClick={() => setParams({ format: f })}>{f}</button>
|
||||
|
|
|
|||
148
admin/src/pages/SignupPage.tsx
Normal file
148
admin/src/pages/SignupPage.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
import { FormEvent, useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { api, StaffRole, StaffUser } from '../api';
|
||||
|
||||
const ROLE_LABEL: Record<StaffRole, string> = { MANAGER: 'Gérant', EMPLOYEE: 'Employé' };
|
||||
const ROLE_LABEL: Record<StaffRole, string> = { MANAGER: 'Dirigeant', EMPLOYEE: 'Employé' };
|
||||
|
||||
export function StaffTab({ storeId }: { storeId: string }) {
|
||||
const base = `/api/admin/stores/${storeId}/staff`;
|
||||
|
|
@ -78,7 +78,7 @@ export function StaffTab({ storeId }: { storeId: string }) {
|
|||
</div>
|
||||
{staff.length === 0 && (
|
||||
<p className="muted" style={{ padding: 24, margin: 0, textAlign: 'center' }}>
|
||||
Aucun employé. Créez au moins un gérant pour que le magasin puisse utiliser l'app Pro.
|
||||
Aucun employé. Créez au moins un dirigeant pour que le magasin puisse utiliser l'app Pro.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
|
@ -156,7 +156,7 @@ function NewStaffForm({ base, onCancel, onCreated }: { base: string; onCancel: (
|
|||
<strong>{ROLE_LABEL[r]}</strong>
|
||||
<br />
|
||||
<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>
|
||||
</label>
|
||||
|
|
|
|||
|
|
@ -13,6 +13,8 @@ SEED_ADMIN_PASSWORD=
|
|||
PUBLIC_URL=http://localhost:3100
|
||||
# Adresse des pages clients (/c/…, /carte/…). Production : WEB_URL=https://monespacepro.eu
|
||||
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_PASS_TYPE_ID=
|
||||
|
|
|
|||
|
|
@ -0,0 +1,30 @@
|
|||
-- Inscription en ligne, titre des campagnes, cadeaux en nature (anniversaire, parrainage).
|
||||
-- À exécuter APRÈS 2026-10-08-modules.sql.
|
||||
ALTER TABLE `Campaign` ADD COLUMN `title` VARCHAR(40) NULL;
|
||||
|
||||
CREATE TABLE `Gift` (
|
||||
`id` VARCHAR(191) NOT NULL,
|
||||
`cardId` VARCHAR(191) NOT NULL,
|
||||
`label` VARCHAR(80) NOT NULL,
|
||||
`source` ENUM('BIRTHDAY', 'REFERRAL', 'REFERRAL_FRIEND') NOT NULL,
|
||||
`createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
`usedAt` DATETIME(3) NULL,
|
||||
`usedByName` VARCHAR(191) NULL,
|
||||
INDEX `Gift_cardId_usedAt_idx`(`cardId`, `usedAt`),
|
||||
PRIMARY KEY (`id`),
|
||||
CONSTRAINT `Gift_cardId_fkey` FOREIGN KEY (`cardId`) REFERENCES `LoyaltyCard`(`id`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE `PendingSignup` (
|
||||
`id` VARCHAR(191) NOT NULL,
|
||||
`email` VARCHAR(191) NOT NULL,
|
||||
`data` JSON NOT NULL,
|
||||
`passwordHash` VARCHAR(191) NOT NULL,
|
||||
`plan` ENUM('ESSENTIEL', 'PRO', 'RESEAU') NOT NULL,
|
||||
`interval` ENUM('MONTH', 'YEAR') NOT NULL,
|
||||
`storeId` VARCHAR(191) NULL,
|
||||
`createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
UNIQUE INDEX `PendingSignup_storeId_key`(`storeId`),
|
||||
INDEX `PendingSignup_email_idx`(`email`),
|
||||
PRIMARY KEY (`id`)
|
||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
|
@ -169,6 +169,7 @@ model LoyaltyCard {
|
|||
updatedAt DateTime @updatedAt
|
||||
transactions Transaction[]
|
||||
devices AppleRegistration[]
|
||||
gifts Gift[]
|
||||
|
||||
@@unique([storeId, customerId])
|
||||
}
|
||||
|
|
@ -294,6 +295,8 @@ model Campaign {
|
|||
id String @id @default(cuid())
|
||||
storeId String
|
||||
store Store @relation(fields: [storeId], references: [id], onDelete: Cascade)
|
||||
/// Titre de la notification (Google Wallet) ; vide : réglage du module.
|
||||
title String? @db.VarChar(40)
|
||||
message String @db.VarChar(160)
|
||||
/// « MonEspacePro » (admin) ou nom du gérant qui l'a envoyée.
|
||||
sentByName String
|
||||
|
|
@ -304,3 +307,41 @@ model Campaign {
|
|||
|
||||
@@index([storeId, createdAt])
|
||||
}
|
||||
|
||||
/// Cadeau en nature (« Un café offert ») gagné par un client : présenté en caisse, puis marqué remis.
|
||||
enum GiftSource {
|
||||
BIRTHDAY
|
||||
REFERRAL /// parrain
|
||||
REFERRAL_FRIEND /// filleul
|
||||
}
|
||||
|
||||
model Gift {
|
||||
id String @id @default(cuid())
|
||||
cardId String
|
||||
card LoyaltyCard @relation(fields: [cardId], references: [id], onDelete: Cascade)
|
||||
label String @db.VarChar(80)
|
||||
source GiftSource
|
||||
createdAt DateTime @default(now())
|
||||
usedAt DateTime?
|
||||
/// Employé qui a remis le cadeau.
|
||||
usedByName String?
|
||||
|
||||
@@index([cardId, usedAt])
|
||||
}
|
||||
|
||||
/// Inscription en ligne en attente du paiement Stripe : le magasin et le compte
|
||||
/// Dirigeant ne sont créés qu'au paiement réussi (webhook).
|
||||
model PendingSignup {
|
||||
id String @id @default(cuid())
|
||||
email String
|
||||
/// Champs du magasin (nom, adresse, SIRET, contact…).
|
||||
data Json
|
||||
passwordHash String
|
||||
plan Plan
|
||||
interval BillingInterval
|
||||
/// Magasin créé (inscription terminée).
|
||||
storeId String? @unique
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([email])
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,14 +1,18 @@
|
|||
import { Module } from '@nestjs/common';
|
||||
import { BillingModule } from './billing/billing.controller';
|
||||
import { StoresController } from './stores/stores.controller';
|
||||
import { StoresService } from './stores/stores.service';
|
||||
import { CardDesignController } from './card-design/card-design.controller';
|
||||
import { CardDesignService } from './card-design/card-design.service';
|
||||
import { StaffController } from './staff/staff.controller';
|
||||
import { StaffService } from './staff/staff.service';
|
||||
import { StaffPasswordController, StaffSpaceController } from './staff/staff-space.controller';
|
||||
|
||||
/** Back-office : magasins, design des cartes, comptes du personnel. */
|
||||
@Module({
|
||||
controllers: [StoresController, CardDesignController, StaffController],
|
||||
imports: [BillingModule],
|
||||
controllers: [StoresController, CardDesignController, StaffController, StaffSpaceController, StaffPasswordController],
|
||||
providers: [StoresService, CardDesignService, StaffService],
|
||||
exports: [CardDesignService, StaffService],
|
||||
})
|
||||
export class AdminModule {}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { Body, Controller, Get, Headers, HttpCode, Logger, Module, Param, Post, Req, Res, UseGuards } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { Body, Controller, Get, Headers, HttpCode, Logger, Module, NotFoundException, Param, Post, Req, Res, UseGuards } from '@nestjs/common';
|
||||
import type { RawBodyRequest } from '@nestjs/common';
|
||||
import { SkipThrottle } from '@nestjs/throttler';
|
||||
import { BillingInterval, Plan } from '@prisma/client';
|
||||
|
|
@ -6,6 +7,8 @@ import { IsBoolean, IsEnum, IsOptional } from 'class-validator';
|
|||
import type { Request, Response } from 'express';
|
||||
import { AdminGuard, JwtAuthGuard } from '../common/guards';
|
||||
import { BillingService } from './billing.service';
|
||||
import { SignupModule } from '../signup/signup.module';
|
||||
import { SignupController } from '../signup/signup.controller';
|
||||
|
||||
class CheckoutLinkDto {
|
||||
@IsEnum(Plan)
|
||||
|
|
@ -14,10 +17,6 @@ class CheckoutLinkDto {
|
|||
@IsEnum(BillingInterval)
|
||||
interval!: BillingInterval;
|
||||
|
||||
/** Proposer l'essai gratuit (une seule fois par magasin). */
|
||||
@IsOptional() @IsBoolean()
|
||||
trial?: boolean;
|
||||
|
||||
/** Envoyer le lien par e-mail au contact du magasin. */
|
||||
@IsOptional() @IsBoolean()
|
||||
sendEmail?: boolean;
|
||||
|
|
@ -44,7 +43,6 @@ export class BillingAdminController {
|
|||
return this.billing.checkoutLink(storeId, {
|
||||
plan: dto.plan,
|
||||
interval: dto.interval,
|
||||
trial: dto.trial ?? false,
|
||||
sendEmail: dto.sendEmail ?? true,
|
||||
});
|
||||
}
|
||||
|
|
@ -66,6 +64,23 @@ export class BillingAdminController {
|
|||
}
|
||||
}
|
||||
|
||||
/** Lien d'abonnement permanent envoyé au commerçant : redirige vers une session Stripe neuve. */
|
||||
@Controller('public/subscribe')
|
||||
export class SubscribeController {
|
||||
constructor(
|
||||
private billing: BillingService,
|
||||
private config: ConfigService,
|
||||
) {}
|
||||
|
||||
@Get(':storeId/:sig')
|
||||
async go(@Param('storeId') storeId: string, @Param('sig') sig: string, @Res() res: Response) {
|
||||
if (!this.billing.checkSubscribeSignature(storeId, sig)) throw new NotFoundException('Lien invalide');
|
||||
const session = await this.billing.checkoutSession(storeId);
|
||||
// Déjà abonné : page de remerciement plutôt qu'un second abonnement.
|
||||
res.redirect(303, session?.url ?? `${this.config.get('webUrl')}/abonnement/merci/`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Notifications Stripe : signature vérifiée sur le corps brut. */
|
||||
@Controller('stripe')
|
||||
@SkipThrottle()
|
||||
|
|
@ -90,7 +105,9 @@ export class StripeWebhookController {
|
|||
}
|
||||
|
||||
@Module({
|
||||
controllers: [BillingAdminController, StripeWebhookController],
|
||||
imports: [SignupModule],
|
||||
controllers: [BillingAdminController, SubscribeController, SignupController, StripeWebhookController],
|
||||
providers: [BillingService],
|
||||
exports: [BillingService],
|
||||
})
|
||||
export class BillingModule {}
|
||||
|
|
|
|||
|
|
@ -3,12 +3,15 @@ import { ConfigService } from '@nestjs/config';
|
|||
import { BillingInterval, Plan, Prisma, SubscriptionStatus } from '@prisma/client';
|
||||
import { mkdir, readFile, writeFile } from 'fs/promises';
|
||||
import { join } from 'path';
|
||||
import { createHmac, timingSafeEqual } from 'crypto';
|
||||
import Stripe from 'stripe';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { MailService } from '../mail/mail.service';
|
||||
import { emailLayout, esc } from '../mail/email-layout';
|
||||
import { renderInvoicePdf } from './invoice-pdf';
|
||||
import { PLANS, TRIAL_DAYS, planFromLookupKey, publicCatalog } from './plans';
|
||||
import { PLANS, planFromLookupKey, publicCatalog } from './plans';
|
||||
import { activateIfReady } from '../stores/activation';
|
||||
import { SignupService } from '../signup/signup.service';
|
||||
|
||||
/** Factures PDF : hors des dossiers servis publiquement. */
|
||||
export const INVOICES_DIR = join(process.cwd(), 'storage', 'invoices');
|
||||
|
|
@ -39,6 +42,7 @@ export class BillingService {
|
|||
private prisma: PrismaService,
|
||||
private config: ConfigService,
|
||||
private mail: MailService,
|
||||
private signup: SignupService,
|
||||
) {}
|
||||
|
||||
get stripe(): Stripe {
|
||||
|
|
@ -59,13 +63,12 @@ export class BillingService {
|
|||
return {
|
||||
testMode: (this.config.get<string>('stripe.secretKey') ?? '').startsWith('sk_test_'),
|
||||
catalog: publicCatalog(),
|
||||
trialDays: TRIAL_DAYS,
|
||||
subscribeUrl: this.subscribeUrl(store.id),
|
||||
subscription: sub && {
|
||||
status: sub.status,
|
||||
plan: sub.plan,
|
||||
interval: sub.interval,
|
||||
legacyPrice: sub.legacyPrice,
|
||||
trialEndsAt: sub.trialEndsAt,
|
||||
cancelAtPeriodEnd: sub.cancelAtPeriodEnd,
|
||||
currentPeriodEnd: sub.currentPeriodEnd,
|
||||
hasCustomer: !!sub.stripeCustomerId,
|
||||
|
|
@ -106,7 +109,7 @@ export class BillingService {
|
|||
return { store, customerId: customer.id };
|
||||
}
|
||||
|
||||
private async priceFor(plan: Plan, interval: BillingInterval) {
|
||||
async priceFor(plan: Plan, interval: BillingInterval) {
|
||||
const key = PLANS[plan].lookupKey[interval];
|
||||
const price = (await this.stripe.prices.list({ lookup_keys: [key], active: true, limit: 1 })).data[0];
|
||||
if (!price) throw new ServiceUnavailableException(`Prix Stripe « ${key} » introuvable : lancer scripts/stripe-setup.ts`);
|
||||
|
|
@ -114,21 +117,41 @@ export class BillingService {
|
|||
}
|
||||
|
||||
/**
|
||||
* Lien Checkout pour souscrire une formule (mensuelle ou annuelle), avec
|
||||
* essai gratuit éventuel et codes promo ; envoyé par e-mail si demandé.
|
||||
* Lien d'abonnement permanent du magasin : chaque clic crée une session
|
||||
* Stripe Checkout neuve pour la formule choisie (une session Stripe expire
|
||||
* au bout de 24 h, ce lien jamais). Signé : impossible à deviner.
|
||||
*/
|
||||
async checkoutLink(storeId: string, opts: { plan: Plan; interval: BillingInterval; trial: boolean; sendEmail: boolean }) {
|
||||
const { store, customerId } = await this.ensureCustomer(storeId);
|
||||
if (store.subscription?.stripeSubscriptionId && store.subscription.status !== 'CANCELED') {
|
||||
subscribeUrl(storeId: string) {
|
||||
const sig = createHmac('sha256', this.config.get<string>('jwt.accessSecret')!).update(`subscribe:${storeId}`).digest('base64url').slice(0, 24);
|
||||
return `${this.config.get('publicUrl')}/api/public/subscribe/${storeId}/${sig}`;
|
||||
}
|
||||
|
||||
checkSubscribeSignature(storeId: string, sig: string) {
|
||||
const expected = this.subscribeUrl(storeId).split('/').pop()!;
|
||||
return sig.length === expected.length && timingSafeEqual(Buffer.from(sig), Buffer.from(expected));
|
||||
}
|
||||
|
||||
/** Formule choisie (création du magasin, ou admin) : elle sera proposée au paiement. */
|
||||
async choosePlan(storeId: string, plan: Plan, interval: BillingInterval) {
|
||||
const sub = await this.prisma.subscription.findUnique({ where: { storeId } });
|
||||
if (sub?.stripeSubscriptionId && sub.status !== 'CANCELED') {
|
||||
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 trialAllowed = opts.trial && !store.subscription?.trialEndsAt;
|
||||
const price = await this.priceFor(opts.plan, opts.interval);
|
||||
const def = PLANS[opts.plan];
|
||||
await this.prisma.subscription.upsert({
|
||||
where: { storeId },
|
||||
create: { storeId, plan, interval },
|
||||
update: { plan, interval, ...(sub?.status === 'CANCELED' && { status: 'INCOMPLETE', stripeSubscriptionId: null }) },
|
||||
});
|
||||
}
|
||||
|
||||
/** Session Stripe Checkout pour la formule enregistrée du magasin (lien permanent). */
|
||||
async checkoutSession(storeId: string) {
|
||||
const { store, customerId } = await this.ensureCustomer(storeId);
|
||||
const sub = store.subscription;
|
||||
if (sub?.stripeSubscriptionId && sub.status !== 'CANCELED') return null; // déjà abonné
|
||||
const price = await this.priceFor(sub?.plan ?? 'ESSENTIEL', sub?.interval ?? 'MONTH');
|
||||
const webUrl: string = this.config.get('webUrl')!;
|
||||
const session = await this.stripe.checkout.sessions.create({
|
||||
return this.stripe.checkout.sessions.create({
|
||||
mode: 'subscription',
|
||||
customer: customerId,
|
||||
line_items: [{ price: price.id, quantity: 1 }],
|
||||
|
|
@ -136,19 +159,30 @@ export class BillingService {
|
|||
allow_promotion_codes: true,
|
||||
locale: 'fr',
|
||||
client_reference_id: store.id,
|
||||
subscription_data: {
|
||||
metadata: { storeId: store.id },
|
||||
...(trialAllowed && { trial_period_days: TRIAL_DAYS }),
|
||||
},
|
||||
subscription_data: { metadata: { storeId: store.id } },
|
||||
metadata: { storeId: store.id },
|
||||
success_url: `${webUrl}/abonnement/merci/`,
|
||||
cancel_url: `${webUrl}/tarif/`,
|
||||
expires_at: Math.floor(Date.now() / 1000) + 24 * 3600, // 24 h, maximum autorisé par Stripe
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Enregistre la formule et envoie (ou renvoie) au commerçant le lien
|
||||
* d'abonnement permanent.
|
||||
*/
|
||||
async checkoutLink(storeId: string, opts: { plan: Plan; interval: BillingInterval; sendEmail: boolean; credentials?: { email: string; password: string } }) {
|
||||
await this.choosePlan(storeId, opts.plan, opts.interval);
|
||||
const store = await this.prisma.store.findUniqueOrThrow({ where: { id: storeId } });
|
||||
const def = PLANS[opts.plan];
|
||||
const url = this.subscribeUrl(storeId);
|
||||
const webUrl: string = this.config.get('webUrl')!;
|
||||
const priceText = `${euros(def.priceCents[opts.interval])} ${opts.interval === 'YEAR' ? 'par an (2 mois offerts)' : 'par mois'}`;
|
||||
if (opts.sendEmail) {
|
||||
const text = `Bonjour ${store.contactName},\n\nVoici le lien pour activer la formule ${def.name} de MonEspacePro pour ${store.name} (${priceText}${trialAllowed ? `, ${TRIAL_DAYS} jours d'essai gratuit` : ''}, sans engagement) :\n${session.url}\n\nCe lien est valable 24 heures.\n\nMonEspacePro`;
|
||||
const espace = `${this.config.get('adminUrl')}/espace`;
|
||||
const c = opts.credentials;
|
||||
const text = `Bonjour ${store.contactName},\n\nVoici le lien pour activer la formule ${def.name} de MonEspacePro pour ${store.name} (${priceText}, sans engagement) :\n${url}\n${
|
||||
c ? `\nVotre compte Dirigeant (app MonEspacePro Pro et espace web ${espace}) :\nE-mail : ${c.email}\nMot de passe provisoire : ${c.password}\n` : ''
|
||||
}\nMonEspacePro`;
|
||||
const html = emailLayout({
|
||||
webUrl,
|
||||
preheader: `Activez la formule ${def.name} de MonEspacePro pour ${store.name}.`,
|
||||
|
|
@ -156,26 +190,27 @@ export class BillingService {
|
|||
title: `Activez MonEspacePro pour ${store.name}`,
|
||||
paragraphs: [
|
||||
`Bonjour ${esc(store.contactName)},`,
|
||||
`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.`,
|
||||
`Il ne reste qu'à activer la formule <strong>${esc(def.name)}</strong> de <strong>${esc(store.name)}</strong>. Dès le paiement validé, votre programme de fidélité s'ouvre automatiquement à vos clients.`,
|
||||
],
|
||||
cta: { label: trialAllowed ? `Commencer l'essai gratuit de ${TRIAL_DAYS} jours` : 'Activer mon abonnement', url: session.url! },
|
||||
cta: { label: 'Activer mon abonnement', url },
|
||||
details: [
|
||||
['Formule', `${esc(def.name)} — ${esc(def.tagline)}`],
|
||||
['Prix', `${priceText} — TVA non applicable, art. 293 B du CGI`],
|
||||
...(trialAllowed ? ([['Essai', `${TRIAL_DAYS} jours gratuits, aucun prélèvement avant la fin de l'essai`]] as [string, string][]) : []),
|
||||
['Engagement', 'Aucun, résiliable à tout moment'],
|
||||
['Paiement', 'Carte bancaire ou prélèvement SEPA, factures automatiques'],
|
||||
...(c
|
||||
? ([
|
||||
['Votre identifiant', esc(c.email)],
|
||||
['Mot de passe provisoire', `<strong>${esc(c.password)}</strong>`],
|
||||
['Espace web', `<a href="${esc(espace)}">${esc(espace)}</a> (conception de la carte)`],
|
||||
] as [string, string][])
|
||||
: []),
|
||||
],
|
||||
note: 'Ce lien est valable 24 heures. Passé ce délai, demandez-nous simplement un nouveau lien.',
|
||||
note: 'Vos identifiants ouvrent aussi l’app MonEspacePro Pro, pour scanner les cartes de vos clients.',
|
||||
});
|
||||
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: opts.sendEmail ? store.contactEmail : null,
|
||||
trial: trialAllowed,
|
||||
};
|
||||
return { url, emailedTo: opts.sendEmail ? store.contactEmail : null };
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -227,7 +262,10 @@ export class BillingService {
|
|||
switch (event.type) {
|
||||
case 'checkout.session.completed': {
|
||||
const s = event.data.object;
|
||||
if (s.mode === 'subscription' && s.subscription) await this.syncSubscription(String(s.subscription));
|
||||
if (s.mode !== 'subscription' || !s.subscription) break;
|
||||
// Inscription en ligne : le magasin et le compte Dirigeant naissent ici.
|
||||
const storeId = s.metadata?.signupId ? await this.signup.complete(s, this.stripe) : undefined;
|
||||
await this.syncSubscription(String(s.subscription), storeId);
|
||||
break;
|
||||
}
|
||||
case 'customer.subscription.created':
|
||||
|
|
@ -238,9 +276,6 @@ export class BillingService {
|
|||
case 'invoice.paid':
|
||||
await this.onInvoicePaid(event.data.object);
|
||||
break;
|
||||
case 'customer.subscription.trial_will_end':
|
||||
await this.onTrialWillEnd(event.data.object);
|
||||
break;
|
||||
case 'invoice.payment_failed':
|
||||
await this.onPaymentFailed(event.data.object);
|
||||
break;
|
||||
|
|
@ -250,9 +285,9 @@ export class BillingService {
|
|||
}
|
||||
|
||||
/** Recopie l'état de l'abonnement Stripe et applique suspension / réactivation. */
|
||||
private async syncSubscription(subscriptionId: string) {
|
||||
private async syncSubscription(subscriptionId: string, knownStoreId?: string) {
|
||||
const sub = await this.stripe.subscriptions.retrieve(subscriptionId);
|
||||
const storeId = sub.metadata.storeId;
|
||||
const storeId = knownStoreId ?? sub.metadata.storeId;
|
||||
if (!storeId) return;
|
||||
const status = STATUS[sub.status] ?? 'INCOMPLETE';
|
||||
const periodEnd = sub.current_period_end;
|
||||
|
|
@ -273,42 +308,13 @@ export class BillingService {
|
|||
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);
|
||||
await activateIfReady(this.prisma, storeId);
|
||||
}
|
||||
if (status === 'PAST_DUE' || status === 'CANCELED') await this.suspend(storeId, `abonnement ${sub.status}`);
|
||||
}
|
||||
|
||||
/** Stripe prévient 3 jours avant la fin de l'essai : on rappelle au commerçant ce qui va se passer. */
|
||||
private async onTrialWillEnd(sub: Stripe.Subscription) {
|
||||
const storeId = sub.metadata.storeId;
|
||||
if (!storeId || !sub.trial_end) return;
|
||||
const store = await this.prisma.store.findUnique({ where: { id: storeId } });
|
||||
if (!store) return;
|
||||
const found = planFromLookupKey(sub.items.data[0]?.price?.lookup_key);
|
||||
const def = PLANS[found?.plan ?? 'ESSENTIEL'];
|
||||
const interval = found?.interval ?? 'MONTH';
|
||||
const end = new Date(sub.trial_end * 1000).toLocaleDateString('fr-FR', { day: 'numeric', month: 'long', timeZone: 'Europe/Paris' });
|
||||
const webUrl: string = this.config.get('webUrl')!;
|
||||
const portal = await this.portalLink(storeId, false);
|
||||
const text = `Bonjour ${store.contactName},\n\nVotre essai gratuit de MonEspacePro se termine le ${end}. L'abonnement ${def.name} démarrera alors automatiquement (${euros(def.priceCents[interval])} ${interval === 'YEAR' ? 'par an' : 'par mois'}). Rien à faire si vous souhaitez continuer.\n\nChanger de formule ou résilier : ${portal.url}\n\nMonEspacePro`;
|
||||
const html = emailLayout({
|
||||
webUrl,
|
||||
preheader: `Votre essai se termine le ${end}.`,
|
||||
eyebrow: 'Essai gratuit',
|
||||
title: `Votre essai se termine le ${end}`,
|
||||
paragraphs: [
|
||||
`Bonjour ${esc(store.contactName)},`,
|
||||
`L'abonnement <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) {
|
||||
const storeId = await this.storeIdForCustomer(String(invoice.customer));
|
||||
if (storeId) await this.suspend(storeId, `paiement de ${euros(invoice.amount_due)} refusé`);
|
||||
|
|
|
|||
|
|
@ -62,7 +62,6 @@ export const PLANS: Record<Plan, PlanDefinition> = {
|
|||
/** 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;
|
||||
|
|
|
|||
|
|
@ -85,7 +85,7 @@ export class BirthdaysService implements OnModuleInit, OnApplicationBootstrap, O
|
|||
if (!moduleActive(store, 'birthday')) continue;
|
||||
const config = moduleConfig(store, 'birthday');
|
||||
if (today.hour < Number(config.hourFrom) || today.hour >= Number(config.hourTo)) continue;
|
||||
const sent = await this.runStore(store.id, Number(config.points), today, now);
|
||||
const sent = await this.runStore(store.id, Number(config.points), String(config.gift).trim(), today, now);
|
||||
if (sent) this.logger.log(`Anniversaire : ${sent} client(s) de ${store.name}`);
|
||||
}
|
||||
} catch (e) {
|
||||
|
|
@ -95,7 +95,7 @@ export class BirthdaysService implements OnModuleInit, OnApplicationBootstrap, O
|
|||
}
|
||||
}
|
||||
|
||||
private async runStore(storeId: string, points: number, today: ReturnType<typeof parisDate>, now: Date) {
|
||||
private async runStore(storeId: string, points: number, gift: string, today: ReturnType<typeof parisDate>, now: Date) {
|
||||
const notBefore = new Date(now.getTime() - MIN_GAP_MS);
|
||||
const cards = await this.prisma.loyaltyCard.findMany({
|
||||
where: {
|
||||
|
|
@ -113,6 +113,8 @@ export class BirthdaysService implements OnModuleInit, OnApplicationBootstrap, O
|
|||
data: { birthdayGiftAt: now, passUpdatedAt: now, ...(points > 0 && { balance: { increment: points } }) },
|
||||
});
|
||||
if (!count) continue;
|
||||
// Cadeau en nature : à remettre en caisse depuis l'app Pro.
|
||||
if (gift) await this.prisma.gift.create({ data: { cardId: id, label: gift, source: 'BIRTHDAY' } });
|
||||
const card = await this.prisma.loyaltyCard.findUniqueOrThrow({ where: { id }, include: CARD_WITH_CONTEXT });
|
||||
try {
|
||||
await this.cardUpdates.remind(card.id, birthdayText(card), notificationTitle(card.store, 'birthday'));
|
||||
|
|
|
|||
|
|
@ -1,12 +1,16 @@
|
|||
import { Body, Controller, Get, Module, Param, Post, UseGuards } from '@nestjs/common';
|
||||
import { Throttle } from '@nestjs/throttler';
|
||||
import { IsString, MaxLength, MinLength } from 'class-validator';
|
||||
import { IsOptional, IsString, MaxLength, MinLength } from 'class-validator';
|
||||
import { JwtPayload } from '../common/auth.types';
|
||||
import { AdminGuard, CurrentUser, JwtAuthGuard, StaffGuard, StaffRoles } from '../common/guards';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { CampaignsService } from './campaigns.service';
|
||||
|
||||
class SendCampaignDto {
|
||||
/** Titre de la notification ; absent ou vide : titre par défaut du module. */
|
||||
@IsOptional() @IsString() @MaxLength(40)
|
||||
title?: string;
|
||||
|
||||
@IsString() @MinLength(5) @MaxLength(160)
|
||||
message!: string;
|
||||
}
|
||||
|
|
@ -23,11 +27,11 @@ export class AdminCampaignsController {
|
|||
|
||||
@Post()
|
||||
send(@Param('id') id: string, @Body() dto: SendCampaignDto) {
|
||||
return this.campaigns.send(id, dto.message, 'MonEspacePro');
|
||||
return this.campaigns.send(id, dto.message, 'MonEspacePro', dto.title);
|
||||
}
|
||||
}
|
||||
|
||||
/** App Pro : réservé aux gérants. */
|
||||
/** App Pro : réservé aux dirigeants. */
|
||||
@Controller('staff/campaigns')
|
||||
@UseGuards(JwtAuthGuard, StaffGuard)
|
||||
@StaffRoles('MANAGER')
|
||||
|
|
@ -45,7 +49,7 @@ export class StaffCampaignsController {
|
|||
async send(@CurrentUser() user: JwtPayload, @Body() dto: SendCampaignDto) {
|
||||
if (user.kind !== 'staff') throw new Error('StaffGuard manquant');
|
||||
const staff = await this.prisma.staffUser.findUniqueOrThrow({ where: { id: user.sub }, select: { displayName: true } });
|
||||
return this.campaigns.send(user.storeId, dto.message, staff.displayName);
|
||||
return this.campaigns.send(user.storeId, dto.message, staff.displayName, dto.title);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -29,10 +29,10 @@ export class CampaignsService {
|
|||
last && last.createdAt.getTime() + interval > Date.now()
|
||||
? new Date(last.createdAt.getTime() + interval)
|
||||
: null;
|
||||
return { allowed, maxLength: Number(config.maxLength), minIntervalHours: Number(config.minIntervalHours), audience: { cards, appleDevices }, nextAllowedAt, items };
|
||||
return { allowed, defaultTitle: fill(String(config.title), { magasin: store.name }), maxLength: Number(config.maxLength), minIntervalHours: Number(config.minIntervalHours), audience: { cards, appleDevices }, nextAllowedAt, items };
|
||||
}
|
||||
|
||||
async send(storeId: string, rawMessage: string, sentByName: string) {
|
||||
async send(storeId: string, rawMessage: string, sentByName: string, rawTitle?: string) {
|
||||
const config = await this.modules.require(storeId, 'campaigns');
|
||||
const interval = Number(config.minIntervalHours) * 3600_000;
|
||||
const store = await this.prisma.store.findUnique({ where: { id: storeId } });
|
||||
|
|
@ -44,6 +44,8 @@ export class CampaignsService {
|
|||
if (message.length < 5) throw new BadRequestException('Le message est trop court.');
|
||||
if (message.length > Number(config.maxLength)) throw new BadRequestException(`Le message dépasse ${config.maxLength} caractères.`);
|
||||
|
||||
const title = (rawTitle ?? '').replace(/s+/g, ' ').trim().slice(0, 40) || null;
|
||||
|
||||
const last = await this.prisma.campaign.findFirst({ where: { storeId }, orderBy: { createdAt: 'desc' } });
|
||||
if (last && last.createdAt.getTime() + interval > Date.now()) {
|
||||
const at = new Date(last.createdAt.getTime() + interval);
|
||||
|
|
@ -62,9 +64,9 @@ export class CampaignsService {
|
|||
this.prisma.appleDevice.count({ where: { registrations: { some: { card: { storeId } } } } }),
|
||||
]);
|
||||
const campaign = await this.prisma.campaign.create({
|
||||
data: { storeId, message, sentByName, cards, appleDevices },
|
||||
data: { storeId, title, message, sentByName, cards, appleDevices },
|
||||
});
|
||||
this.cardUpdates.broadcast(storeId, campaign, fill(String(config.title), { magasin: store.name }) || store.name);
|
||||
this.cardUpdates.broadcast(storeId, campaign, fill(title ?? String(config.title), { magasin: store.name }) || store.name);
|
||||
return campaign;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { Prisma } from '@prisma/client';
|
|||
import { mkdir, unlink, writeFile } from 'fs/promises';
|
||||
import { join } from 'path';
|
||||
import { randomBytes } from 'crypto';
|
||||
import { activateIfReady } from '../stores/activation';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { SaveCardDesignDto } from './dto/card-design.dto';
|
||||
import { CardUpdatesService } from '../wallet/card-updates.service';
|
||||
|
|
@ -68,6 +69,8 @@ export class CardDesignService {
|
|||
});
|
||||
// Les cartes déjà dans les Wallets reprennent le nouveau design.
|
||||
this.cardUpdates.notifyStore(storeId);
|
||||
// Abonnement déjà payé (inscription en ligne) : le programme s'ouvre tout seul.
|
||||
await activateIfReady(this.prisma, storeId);
|
||||
return this.get(storeId);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -5,6 +5,8 @@ export default () => ({
|
|||
publicUrl: (process.env.PUBLIC_URL ?? 'http://localhost:3100').replace(/\/$/, ''),
|
||||
/** Adresse des pages vues par les clients (QR d'inscription, lien de la carte). Par défaut : PUBLIC_URL. */
|
||||
webUrl: (process.env.WEB_URL || process.env.PUBLIC_URL || 'http://localhost:3100').replace(/\/$/, ''),
|
||||
/** Admin MonEspacePro et espace web des commerçants (/espace, /inscription). */
|
||||
adminUrl: (process.env.ADMIN_URL || 'https://admin.monespacepro.eu').replace(/\/$/, ''),
|
||||
cors: { origins: process.env.CORS_ORIGINS ?? '' },
|
||||
jwt: {
|
||||
accessSecret: process.env.JWT_ACCESS_SECRET ?? 'dev-access-secret',
|
||||
|
|
|
|||
|
|
@ -63,6 +63,12 @@ export class CounterController {
|
|||
return this.counter.redeem(ctx(user), serial, dto.rewardId);
|
||||
}
|
||||
|
||||
@Post('cards/:serial/gifts/:giftId/use')
|
||||
@HttpCode(200)
|
||||
useGift(@CurrentUser() user: JwtPayload, @Param('serial') serial: string, @Param('giftId') giftId: string) {
|
||||
return this.counter.useGift(ctx(user), serial, giftId);
|
||||
}
|
||||
|
||||
@Get('transactions')
|
||||
history(@CurrentUser() user: JwtPayload, @Query() q: HistoryQuery) {
|
||||
return this.counter.history(ctx(user), q.period ?? 'today', q.cursor);
|
||||
|
|
|
|||
|
|
@ -74,7 +74,24 @@ export class CounterService {
|
|||
|
||||
async lookup(ctx: StaffContext, serial: string) {
|
||||
const card = await this.cardOfStore(ctx, serial);
|
||||
return this.presentCard(card);
|
||||
const gifts = await this.prisma.gift.findMany({
|
||||
where: { cardId: card.id, usedAt: null },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
select: { id: true, label: true, source: true, createdAt: true },
|
||||
});
|
||||
return { ...this.presentCard(card), gifts };
|
||||
}
|
||||
|
||||
/** Cadeau en nature remis en caisse (anniversaire, parrainage) : marqué remis, une seule fois. */
|
||||
async useGift(ctx: StaffContext, serial: string, giftId: string) {
|
||||
const card = await this.cardOfStore(ctx, serial);
|
||||
const staff = await this.prisma.staffUser.findUniqueOrThrow({ where: { id: ctx.staffId }, select: { displayName: true } });
|
||||
const { count } = await this.prisma.gift.updateMany({
|
||||
where: { id: giftId, cardId: card.id, usedAt: null },
|
||||
data: { usedAt: new Date(), usedByName: staff.displayName },
|
||||
});
|
||||
if (!count) throw new BadRequestException('Cadeau introuvable ou déjà remis');
|
||||
return this.lookup(ctx, serial);
|
||||
}
|
||||
|
||||
async credit(ctx: StaffContext, serial: string, amountCents: number | undefined) {
|
||||
|
|
@ -155,7 +172,7 @@ export class CounterService {
|
|||
return { reward: { id: reward.id, label: reward.label, cost: reward.cost }, balance, firstName: card.customer.firstName };
|
||||
}
|
||||
|
||||
/** Le gérant voit tout le magasin ; l'employé, seulement ses opérations. */
|
||||
/** Le dirigeant voit tout le magasin ; l'employé, seulement ses opérations. */
|
||||
async history(ctx: StaffContext, period: 'today' | 'week', cursor?: string) {
|
||||
const where = this.scope(ctx, period);
|
||||
const items = await this.prisma.transaction.findMany({
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import type { CardDesign, Plan, Reward, Store, SubscriptionStatus } from '@prisma/client';
|
||||
import { fill, moduleActive, moduleConfig, quantity } from '../modules/catalog';
|
||||
import { fill, moduleActive, moduleConfig, quantity, rewardVars } from '../modules/catalog';
|
||||
import { nextRewardText, reviewOffered, type CardWithContext } from '../wallet/wallet.types';
|
||||
|
||||
/** Pages publiques (clients finaux), rendues côté serveur aux couleurs du magasin. */
|
||||
|
|
@ -32,11 +32,16 @@ function birthdaySelects() {
|
|||
const BIRTHDAY_JS = `function readBirthday(){var d=+document.getElementById('bday').value,m=+document.getElementById('bmonth').value;if(!d&&!m)return null;if(!d||!m||d>[31,29,31,30,31,30,31,31,30,31,30,31][m-1])return false;return {day:d,month:m}}`;
|
||||
|
||||
const stamp = (s: StoreWithDesign) => s.cardDesign?.pointsMode === 'STAMP';
|
||||
/** Récompense du filleul (points et/ou cadeau en nature). */
|
||||
const friendReward = (s: StoreWithDesign) => {
|
||||
const c = moduleConfig(s, 'referral');
|
||||
return rewardVars(Number(c.friendPoints), c.friendGift, stamp(s));
|
||||
};
|
||||
/** Textes du module Anniversaire, avec {cadeau} (« 3 tampons offerts sur votre carte. » ou vide). */
|
||||
function birthdayTexts(store: StoreWithDesign) {
|
||||
const c = moduleConfig(store, 'birthday');
|
||||
const n = Number(c.points);
|
||||
const cadeau = n > 0 ? fill(String(c.giftText), { quantite: quantity(n, stamp(store)) }) : '';
|
||||
const vars = rewardVars(Number(c.points), c.gift, stamp(store));
|
||||
const cadeau = vars.recompense ? fill(String(c.giftText), vars) : '';
|
||||
return { enrollHint: fill(String(c.enrollHint), { cadeau }), askTitle: String(c.askTitle), askText: fill(String(c.askText), { cadeau }) };
|
||||
}
|
||||
|
||||
|
|
@ -200,9 +205,7 @@ export function enrollPage(store: StoreWithDesign, referrer: { code: string; fir
|
|||
${
|
||||
referrer
|
||||
? `<div class="notice" style="margin-bottom:16px"><strong>${e(fill(String(moduleConfig(store, 'referral').inviteText), { parrain: referrer.firstName }))}</strong> ${e(
|
||||
Number(moduleConfig(store, 'referral').friendPoints) > 0
|
||||
? fill(String(moduleConfig(store, 'referral').inviteGiftText), { quantite: quantity(Number(moduleConfig(store, 'referral').friendPoints), stamp(store)) })
|
||||
: '',
|
||||
friendReward(store).recompense ? fill(String(moduleConfig(store, 'referral').inviteGiftText), friendReward(store)) : '',
|
||||
)}</div>`
|
||||
: ''
|
||||
}
|
||||
|
|
@ -384,8 +387,8 @@ ${
|
|||
opts.referralUrl
|
||||
? `<section class="notice" style="display:flex;flex-direction:column;gap:10px">
|
||||
<strong>${e(String(referral.sectionTitle))}</strong>
|
||||
<span>${e(fill(String(referral.sectionText), { quantite: quantity(Number(referral.points), stamp(store)) }))}${
|
||||
Number(referral.friendPoints) > 0 ? ` ${e(fill(String(referral.sectionFriendText), { quantite: quantity(Number(referral.friendPoints), stamp(store)) }))}` : ''
|
||||
<span>${e(fill(String(referral.sectionText), rewardVars(Number(referral.points), referral.gift, stamp(store))))}${
|
||||
friendReward(store).recompense ? ` ${e(fill(String(referral.sectionFriendText), friendReward(store)))}` : ''
|
||||
}</span>
|
||||
<input type="text" id="reflink" readonly value="${e(opts.referralUrl)}" aria-label="Votre lien de parrainage" onclick="this.select()">
|
||||
<button class="btn" id="share" type="button">Partager mon lien</button>
|
||||
|
|
|
|||
|
|
@ -38,6 +38,15 @@ const title = (def = '{magasin}'): FieldDef => ({
|
|||
maxLength: 40,
|
||||
variables: ['{magasin}'],
|
||||
});
|
||||
/** Cadeau en nature (« Un café offert ») : remis en caisse depuis l'app Pro. */
|
||||
const GIFT = (key: string, label: string): FieldDef => ({
|
||||
key,
|
||||
type: 'text',
|
||||
label,
|
||||
help: 'Ex. : « Un café offert ». Le client le présente en caisse et l’employé le remet depuis l’app Pro. Vide = pas de cadeau en nature.',
|
||||
default: '',
|
||||
maxLength: 60,
|
||||
});
|
||||
const hours = (from: number, to: number): FieldDef[] => [
|
||||
{ key: 'hourFrom', type: 'hour', label: 'Envoi à partir de', default: from, min: 0, max: 23, help: 'Heure de Paris.' },
|
||||
{ key: 'hourTo', type: 'hour', label: "Envoi jusqu'à", default: to, min: 1, max: 24, help: 'Heure de Paris (exclue).' },
|
||||
|
|
@ -75,12 +84,13 @@ export const MODULES: ModuleDef[] = [
|
|||
id: 'birthday',
|
||||
name: "Offre d'anniversaire",
|
||||
tagline: 'Un cadeau le jour de l’anniversaire',
|
||||
description: 'Les clients indiquent leur anniversaire (jour et mois). Le jour J, ils reçoivent une notification et, si vous le souhaitez, des points offerts. Un cadeau par an.',
|
||||
description: 'Les clients indiquent leur anniversaire (jour et mois). Le jour J, ils reçoivent une notification et la récompense de votre choix : points ou tampons offerts, et/ou un cadeau à retirer en magasin. Un cadeau par an.',
|
||||
enabledByDefault: false,
|
||||
fields: [
|
||||
{ key: 'points', type: 'int', label: 'Points ou tampons offerts', unit: '(0 = message seulement)', default: 0, min: 0, max: 1000 },
|
||||
{ key: 'points', type: 'int', label: 'Points ou tampons offerts', unit: '(0 = aucun)', default: 0, min: 0, max: 1000 },
|
||||
GIFT('gift', 'Cadeau à retirer en magasin'),
|
||||
{ key: 'message', type: 'textarea', label: 'Message du jour J', default: 'Joyeux anniversaire, {prenom} ! {cadeau}', maxLength: 160, variables: [...V_CLIENT, '{cadeau}'] },
|
||||
{ key: 'giftText', type: 'text', label: 'Texte du cadeau', default: '{quantite} offerts sur votre carte.', maxLength: 80, variables: ['{quantite}'], help: 'Remplace {cadeau} quand des points sont offerts.' },
|
||||
{ key: 'giftText', type: 'text', label: 'Texte du cadeau', default: 'Pour vous : {recompense}.', maxLength: 80, variables: ['{recompense}', '{quantite}'], help: 'Remplace {cadeau} quand une récompense est prévue.' },
|
||||
title(),
|
||||
{ key: 'askTitle', type: 'text', label: 'Titre de la demande (page de la carte)', default: 'Un cadeau pour votre anniversaire ?', maxLength: 60 },
|
||||
{ key: 'askText', type: 'textarea', label: 'Texte de la demande', default: '{cadeau} Indiquez le jour et le mois (l’année n’est pas demandée).', maxLength: 200, variables: ['{cadeau}'] },
|
||||
|
|
@ -108,20 +118,22 @@ export const MODULES: ModuleDef[] = [
|
|||
id: 'referral',
|
||||
name: 'Parrainage',
|
||||
tagline: 'Vos clients recrutent leurs proches',
|
||||
description: 'Chaque client partage un lien personnel. Quand un ami s’inscrit avec ce lien puis fait son premier passage, le parrain (et le filleul si vous le souhaitez) est récompensé.',
|
||||
description: 'Chaque client partage un lien personnel. Quand un ami s’inscrit avec ce lien puis fait son premier passage, le parrain (et le filleul si vous le souhaitez) reçoit la récompense de votre choix : points ou tampons, et/ou un cadeau à retirer en magasin.',
|
||||
enabledByDefault: false,
|
||||
fields: [
|
||||
{ key: 'points', type: 'int', label: 'Offerts au parrain', unit: 'points / tampons', default: 5, min: 0, max: 1000 },
|
||||
GIFT('gift', 'Cadeau du parrain à retirer en magasin'),
|
||||
{ key: 'friendPoints', type: 'int', label: 'Offerts au filleul', unit: 'points / tampons', default: 0, min: 0, max: 1000 },
|
||||
GIFT('friendGift', 'Cadeau du filleul à retirer en magasin'),
|
||||
{ key: 'maxRewardsPer30Days', type: 'int', label: 'Récompenses maximum par parrain', unit: 'sur 30 jours', default: 10, min: 1, max: 1000 },
|
||||
{ key: 'referrerMessage', type: 'textarea', label: 'Message au parrain', default: 'Merci {prenom} ! {filleul} est venu(e) grâce à vous : {quantite} offerts.', maxLength: 160, variables: [...V_CLIENT, '{filleul}', '{quantite}'] },
|
||||
{ key: 'friendMessage', type: 'textarea', label: 'Message au filleul', default: 'Bienvenue, {prenom} ! {quantite} offerts grâce à votre parrainage.', maxLength: 160, variables: [...V_CLIENT, '{quantite}'] },
|
||||
{ key: 'referrerMessage', type: 'textarea', label: 'Message au parrain', default: 'Merci {prenom} ! {filleul} est venu(e) grâce à vous : {recompense}.', maxLength: 160, variables: [...V_CLIENT, '{filleul}', '{recompense}', '{quantite}'] },
|
||||
{ key: 'friendMessage', type: 'textarea', label: 'Message au filleul', default: 'Bienvenue, {prenom} ! Grâce à votre parrainage : {recompense}.', maxLength: 160, variables: [...V_CLIENT, '{recompense}', '{quantite}'] },
|
||||
title(),
|
||||
{ key: 'inviteText', type: 'text', label: "Bandeau de la page d'inscription", default: '{parrain} vous invite !', maxLength: 80, variables: ['{parrain}'] },
|
||||
{ key: 'inviteGiftText', type: 'text', label: 'Annonce du cadeau du filleul (inscription)', default: '{quantite} offerts à votre premier passage en magasin.', maxLength: 120, variables: ['{quantite}'], help: 'Affichée si le filleul reçoit des points.' },
|
||||
{ key: 'inviteGiftText', type: 'text', label: 'Annonce du cadeau du filleul (inscription)', default: 'À votre premier passage en magasin : {recompense}.', maxLength: 120, variables: ['{recompense}', '{quantite}'], help: 'Affichée si le filleul reçoit une récompense.' },
|
||||
{ key: 'sectionTitle', type: 'text', label: 'Titre de la section (page de la carte)', default: 'Parrainez vos proches', maxLength: 60 },
|
||||
{ key: 'sectionText', type: 'textarea', label: 'Texte de la section', default: 'Gagnez {quantite} pour chaque ami qui s’inscrit avec votre lien et passe en magasin.', maxLength: 200, variables: ['{quantite}'] },
|
||||
{ key: 'sectionFriendText', type: 'text', label: 'Phrase sur le cadeau du filleul (page de la carte)', default: 'Votre ami reçoit {quantite} lui aussi.', maxLength: 120, variables: ['{quantite}'], help: 'Affichée si le filleul reçoit des points.' },
|
||||
{ key: 'sectionText', type: 'textarea', label: 'Texte de la section', default: 'Pour chaque ami qui s’inscrit avec votre lien et passe en magasin : {recompense}.', maxLength: 200, variables: ['{recompense}', '{quantite}'] },
|
||||
{ key: 'sectionFriendText', type: 'text', label: 'Phrase sur le cadeau du filleul (page de la carte)', default: 'Votre ami reçoit lui aussi : {recompense}.', maxLength: 120, variables: ['{recompense}', '{quantite}'], help: 'Affichée si le filleul reçoit une récompense.' },
|
||||
{ key: 'shareText', type: 'text', label: 'Texte du partage', default: 'Rejoignez le programme de fidélité de {magasin} :', maxLength: 120, variables: ['{magasin}'] },
|
||||
{ key: 'linkLabel', type: 'text', label: 'Texte du lien au dos de la carte', default: 'Mon lien de parrainage', maxLength: 40 },
|
||||
],
|
||||
|
|
@ -207,6 +219,18 @@ export function quantity(n: number, stamp: boolean) {
|
|||
return `${n} ${stamp ? 'tampon' : 'point'}${n > 1 ? 's' : ''}`;
|
||||
}
|
||||
|
||||
/** « 3 tampons offerts », « Un café offert », « 3 tampons offerts et un café offert » ; vide si rien. */
|
||||
export function rewardText(points: number, gift: unknown, stamp: boolean) {
|
||||
const g = typeof gift === 'string' ? gift.trim() : '';
|
||||
const parts: string[] = [];
|
||||
if (points > 0) parts.push(`${quantity(points, stamp)} offert${points > 1 ? 's' : ''}`);
|
||||
if (g) parts.push(parts.length ? g.charAt(0).toLowerCase() + g.slice(1) : g);
|
||||
return parts.join(' et ');
|
||||
}
|
||||
|
||||
/** Variables {recompense} et {quantite} des textes de récompense. */
|
||||
export const rewardVars = (points: number, gift: unknown, stamp: boolean) => ({ recompense: rewardText(points, gift, stamp), quantite: quantity(points, stamp) });
|
||||
|
||||
/** Valide et normalise les réglages envoyés par un formulaire ; renvoie les erreurs lisibles. */
|
||||
export function validateConfig(id: ModuleId, input: Record<string, unknown>): { values: Values; errors: string[] } {
|
||||
const def = moduleDef(id);
|
||||
|
|
|
|||
|
|
@ -42,7 +42,7 @@ export class AdminModulesController {
|
|||
}
|
||||
}
|
||||
|
||||
/** App Pro : les gérants règlent eux-mêmes leurs modules. */
|
||||
/** App Pro : les dirigeants règlent eux-mêmes leurs modules. */
|
||||
@Controller('staff/modules')
|
||||
@UseGuards(JwtAuthGuard, StaffGuard)
|
||||
@StaffRoles('MANAGER')
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import { Global, Injectable, Logger, Module, OnModuleInit } from '@nestjs/common
|
|||
import { randomInt } from 'crypto';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { fill, moduleActive, moduleConfig, quantity, StoreModules } from '../modules/catalog';
|
||||
import { fill, moduleActive, moduleConfig, rewardVars, StoreModules } from '../modules/catalog';
|
||||
import { ModulesService } from '../modules/modules.service';
|
||||
import { CardUpdatesService } from '../wallet/card-updates.service';
|
||||
|
||||
|
|
@ -86,31 +86,37 @@ export class ReferralsService implements OnModuleInit {
|
|||
const base = { magasin: store.name };
|
||||
|
||||
const friendPoints = Number(c.friendPoints);
|
||||
const friendNews = friendPoints > 0 ? fill(String(c.friendMessage), { ...base, prenom: friend.customer.firstName, quantite: quantity(friendPoints, stamp) }) : null;
|
||||
const friendGift = String(c.friendGift).trim();
|
||||
const friendVars = rewardVars(friendPoints, friendGift, stamp);
|
||||
const friendNews = friendVars.recompense ? fill(String(c.friendMessage), { ...base, prenom: friend.customer.firstName, ...friendVars }) : null;
|
||||
// Conditionnel : un seul cadeau même si deux crédits arrivent en même temps.
|
||||
const { count } = await this.prisma.loyaltyCard.updateMany({
|
||||
where: { id: friend.id, referralRewardedAt: null },
|
||||
data: {
|
||||
referralRewardedAt: now,
|
||||
...(friendNews && { balance: { increment: friendPoints }, personalNews: friendNews, personalNewsAt: now, passUpdatedAt: now }),
|
||||
...(friendNews && { balance: { increment: friendPoints }, personalNews: friendNews.slice(0, 200), personalNewsAt: now, passUpdatedAt: now }),
|
||||
},
|
||||
});
|
||||
if (!count) return;
|
||||
if (friendGift) await this.prisma.gift.create({ data: { cardId: friend.id, label: friendGift, source: 'REFERRAL_FRIEND' } });
|
||||
if (friendNews) await this.cardUpdates.remind(friend.id, friendNews, title);
|
||||
|
||||
const points = Number(c.points);
|
||||
const gift = String(c.gift).trim();
|
||||
const vars = rewardVars(points, gift, stamp);
|
||||
const since = new Date(now.getTime() - 30 * 24 * 3600_000);
|
||||
const recent = await this.prisma.loyaltyCard.count({
|
||||
where: { referredById: friend.referredById, referralRewardedAt: { gte: since }, id: { not: friend.id } },
|
||||
});
|
||||
if (points <= 0 || recent >= Number(c.maxRewardsPer30Days)) return;
|
||||
if (!vars.recompense || recent >= Number(c.maxRewardsPer30Days)) return;
|
||||
const referrer = await this.prisma.loyaltyCard.findUnique({ where: { id: friend.referredById }, include: { customer: true } });
|
||||
if (!referrer || referrer.storeId !== store.id) return;
|
||||
const news = fill(String(c.referrerMessage), { ...base, prenom: referrer.customer.firstName, filleul: friend.customer.firstName, quantite: quantity(points, stamp) });
|
||||
const news = fill(String(c.referrerMessage), { ...base, prenom: referrer.customer.firstName, filleul: friend.customer.firstName, ...vars });
|
||||
await this.prisma.loyaltyCard.update({
|
||||
where: { id: referrer.id },
|
||||
data: { balance: { increment: points }, personalNews: news, personalNewsAt: now, passUpdatedAt: now },
|
||||
data: { balance: { increment: points }, personalNews: news.slice(0, 200), personalNewsAt: now, passUpdatedAt: now },
|
||||
});
|
||||
if (gift) await this.prisma.gift.create({ data: { cardId: referrer.id, label: gift, source: 'REFERRAL' } });
|
||||
await this.cardUpdates.remind(referrer.id, news, title);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
65
backend/src/signup/signup.controller.ts
Normal file
65
backend/src/signup/signup.controller.ts
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
import { Body, Controller, Get, HttpCode, Post } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { PickType } from '@nestjs/mapped-types';
|
||||
import { Throttle } from '@nestjs/throttler';
|
||||
import { BillingInterval, Plan } from '@prisma/client';
|
||||
import { Equals, IsEnum, IsString, Length } from 'class-validator';
|
||||
import { CreateStoreDto } from '../stores/dto/store.dto';
|
||||
import { BillingService } from '../billing/billing.service';
|
||||
import { publicCatalog } from '../billing/plans';
|
||||
import { SignupService } from './signup.service';
|
||||
|
||||
class SignupDto extends PickType(CreateStoreDto, ['name', 'siret', 'addressLine', 'postalCode', 'city', 'contactName', 'contactEmail', 'contactPhone'] as const) {
|
||||
@IsString() @Length(10, 128, { message: 'Mot de passe : 10 caractères minimum' })
|
||||
password!: string;
|
||||
|
||||
@IsEnum(Plan)
|
||||
plan!: Plan;
|
||||
|
||||
@IsEnum(BillingInterval)
|
||||
interval!: BillingInterval;
|
||||
|
||||
/** Acceptation des CGV. */
|
||||
@Equals(true, { message: 'Acceptez les conditions générales de vente' })
|
||||
cgv!: boolean;
|
||||
}
|
||||
|
||||
/** Inscription en ligne : renvoie l'adresse de paiement Stripe. */
|
||||
@Controller('public/signup')
|
||||
export class SignupController {
|
||||
constructor(
|
||||
private signup: SignupService,
|
||||
private billing: BillingService,
|
||||
private config: ConfigService,
|
||||
) {}
|
||||
|
||||
/** Formules et prix affichés sur le formulaire d'inscription. */
|
||||
@Get('plans')
|
||||
plans() {
|
||||
return publicCatalog();
|
||||
}
|
||||
|
||||
@Post()
|
||||
@HttpCode(200)
|
||||
@Throttle({ default: { limit: 5, ttl: 10 * 60_000 } })
|
||||
async start(@Body() dto: SignupDto) {
|
||||
const { password, plan, interval, cgv: _cgv, ...data } = dto;
|
||||
const pending = await this.signup.prepare(data, password, plan, interval);
|
||||
const price = await this.billing.priceFor(plan, interval);
|
||||
const espace = `${this.config.get('adminUrl')}/espace`;
|
||||
const session = await this.billing.stripe.checkout.sessions.create({
|
||||
mode: 'subscription',
|
||||
customer_email: pending.email,
|
||||
line_items: [{ price: price.id, quantity: 1 }],
|
||||
payment_method_types: ['card', 'sepa_debit'],
|
||||
allow_promotion_codes: true,
|
||||
locale: 'fr',
|
||||
client_reference_id: pending.id,
|
||||
subscription_data: { metadata: { signupId: pending.id } },
|
||||
metadata: { signupId: pending.id },
|
||||
success_url: `${espace}?bienvenue=1`,
|
||||
cancel_url: `${this.config.get('adminUrl')}/inscription?formule=${plan.toLowerCase()}&annule=1`,
|
||||
});
|
||||
return { url: session.url };
|
||||
}
|
||||
}
|
||||
5
backend/src/signup/signup.module.ts
Normal file
5
backend/src/signup/signup.module.ts
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
import { Module } from '@nestjs/common';
|
||||
import { SignupService } from './signup.service';
|
||||
|
||||
@Module({ providers: [SignupService], exports: [SignupService] })
|
||||
export class SignupModule {}
|
||||
117
backend/src/signup/signup.service.ts
Normal file
117
backend/src/signup/signup.service.ts
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
import { ConflictException, Injectable, Logger } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { BillingInterval, Plan, Prisma } from '@prisma/client';
|
||||
import * as argon2 from 'argon2';
|
||||
import Stripe from 'stripe';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { MailService } from '../mail/mail.service';
|
||||
import { emailLayout, esc } from '../mail/email-layout';
|
||||
import { uniqueSlug } from '../stores/slug';
|
||||
import { PLANS } from '../billing/plans';
|
||||
|
||||
/** Champs du magasin saisis à l'inscription (copiés tels quels dans Store). */
|
||||
export interface SignupStoreData {
|
||||
name: string;
|
||||
siret: string;
|
||||
addressLine: string;
|
||||
postalCode: string;
|
||||
city: string;
|
||||
contactName: string;
|
||||
contactEmail: string;
|
||||
contactPhone: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inscription en ligne depuis la page Tarif : formulaire → paiement Stripe →
|
||||
* création automatique du magasin et du compte Dirigeant (webhook) → e-mail
|
||||
* de bienvenue avec le lien vers l'espace web pour concevoir la carte.
|
||||
*/
|
||||
@Injectable()
|
||||
export class SignupService {
|
||||
private readonly logger = new Logger(SignupService.name);
|
||||
|
||||
constructor(
|
||||
private prisma: PrismaService,
|
||||
private config: ConfigService,
|
||||
private mail: MailService,
|
||||
) {}
|
||||
|
||||
/** Enregistre la demande ; rien n'est créé avant le paiement. */
|
||||
async prepare(data: SignupStoreData, password: string, plan: Plan, interval: BillingInterval) {
|
||||
const email = data.contactEmail.toLowerCase();
|
||||
if (await this.prisma.staffUser.findUnique({ where: { email }, select: { id: true } })) {
|
||||
throw new ConflictException('Un compte existe déjà avec cet e-mail. Connectez-vous à votre espace, ou utilisez une autre adresse.');
|
||||
}
|
||||
return this.prisma.pendingSignup.create({
|
||||
data: { email, data: { ...data, contactEmail: email } as unknown as Prisma.InputJsonValue, passwordHash: await argon2.hash(password), plan, interval },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Paiement réussi : crée le magasin (brouillon), le compte Dirigeant et
|
||||
* l'abonnement. Idempotent (webhook rejoué). Renvoie l'id du magasin.
|
||||
*/
|
||||
async complete(session: Stripe.Checkout.Session, stripe: Stripe): Promise<string | undefined> {
|
||||
const pending = await this.prisma.pendingSignup.findUnique({ where: { id: session.metadata!.signupId } });
|
||||
if (!pending) {
|
||||
this.logger.error(`Inscription ${session.metadata!.signupId} introuvable (session ${session.id})`);
|
||||
return undefined;
|
||||
}
|
||||
if (pending.storeId) return pending.storeId;
|
||||
const data = pending.data as unknown as SignupStoreData;
|
||||
const customerId = String(session.customer);
|
||||
|
||||
const store = await this.prisma.$transaction(async (tx) => {
|
||||
const store = await tx.store.create({ data: { ...data, slug: await uniqueSlug(this.prisma, data.name) } });
|
||||
await tx.subscription.create({ data: { storeId: store.id, stripeCustomerId: customerId, plan: pending.plan, interval: pending.interval } });
|
||||
await tx.pendingSignup.update({ where: { id: pending.id }, data: { storeId: store.id } });
|
||||
return store;
|
||||
});
|
||||
// Compte Dirigeant : l'e-mail a pu être pris entre-temps (cas rarissime) ; le magasin existe quand même.
|
||||
try {
|
||||
await this.prisma.staffUser.create({
|
||||
data: { storeId: store.id, email: pending.email, displayName: data.contactName, role: 'MANAGER', passwordHash: pending.passwordHash },
|
||||
});
|
||||
} catch (e) {
|
||||
if (!(e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002')) throw e;
|
||||
this.logger.error(`Inscription ${pending.id} : e-mail ${pending.email} déjà utilisé, compte Dirigeant à créer depuis l'admin`);
|
||||
}
|
||||
// Les prochains événements Stripe retrouvent le magasin par ces métadonnées.
|
||||
await stripe.customers.update(customerId, {
|
||||
name: data.name,
|
||||
phone: data.contactPhone,
|
||||
address: { line1: data.addressLine, postal_code: data.postalCode, city: data.city, country: 'FR' },
|
||||
metadata: { storeId: store.id, siret: data.siret },
|
||||
});
|
||||
if (session.subscription) await stripe.subscriptions.update(String(session.subscription), { metadata: { storeId: store.id } });
|
||||
|
||||
await this.welcome(store.id).catch((e) => this.logger.error(`E-mail de bienvenue non envoyé : ${(e as Error).message}`));
|
||||
this.logger.log(`Inscription en ligne : magasin ${store.id} (${data.name}) créé, formule ${pending.plan}`);
|
||||
return store.id;
|
||||
}
|
||||
|
||||
private async welcome(storeId: string) {
|
||||
const store = await this.prisma.store.findUniqueOrThrow({ where: { id: storeId }, include: { subscription: true } });
|
||||
const espace = `${this.config.get('adminUrl')}/espace`;
|
||||
const def = PLANS[store.subscription?.plan ?? 'ESSENTIEL'];
|
||||
const text = `Bonjour ${store.contactName},\n\nBienvenue sur MonEspacePro ! Votre abonnement ${def.name} pour ${store.name} est actif.\n\nDernière étape : concevez votre carte de fidélité (logo, couleurs, récompenses) sur ${espace}, avec l'e-mail ${store.contactEmail} et le mot de passe choisi à l'inscription. Votre programme s'ouvre à vos clients dès la carte enregistrée.\n\nEn caisse, installez l'app MonEspacePro Pro sur votre téléphone et connectez-vous avec les mêmes identifiants.\n\nMonEspacePro`;
|
||||
const html = emailLayout({
|
||||
webUrl: this.config.get('webUrl')!,
|
||||
preheader: `Concevez votre carte de fidélité pour ouvrir ${store.name} à vos clients.`,
|
||||
eyebrow: `Formule ${def.name}`,
|
||||
title: 'Bienvenue sur MonEspacePro',
|
||||
paragraphs: [
|
||||
`Bonjour ${esc(store.contactName)},`,
|
||||
`Votre abonnement <strong>${esc(def.name)}</strong> pour <strong>${esc(store.name)}</strong> est actif. Dernière étape : concevez votre carte de fidélité (logo, couleurs, récompenses). Votre programme s'ouvre à vos clients dès la carte enregistrée.`,
|
||||
],
|
||||
cta: { label: 'Concevoir ma carte', url: espace },
|
||||
details: [
|
||||
['Identifiant', esc(store.contactEmail)],
|
||||
['Mot de passe', 'Celui choisi à l’inscription'],
|
||||
['En caisse', 'App MonEspacePro Pro, mêmes identifiants'],
|
||||
],
|
||||
note: 'Depuis l’app Pro, vous créez aussi les comptes de vos employés et réglez vos modules.',
|
||||
});
|
||||
await this.mail.send(store.contactEmail, `Bienvenue sur MonEspacePro, ${store.name}`, text, html);
|
||||
}
|
||||
}
|
||||
150
backend/src/staff/staff-space.controller.ts
Normal file
150
backend/src/staff/staff-space.controller.ts
Normal file
|
|
@ -0,0 +1,150 @@
|
|||
import {
|
||||
BadRequestException,
|
||||
Body,
|
||||
Controller,
|
||||
ForbiddenException,
|
||||
Get,
|
||||
HttpCode,
|
||||
Param,
|
||||
ParseEnumPipe,
|
||||
Patch,
|
||||
Post,
|
||||
Put,
|
||||
UploadedFile,
|
||||
UseGuards,
|
||||
UseInterceptors,
|
||||
} from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { FileInterceptor } from '@nestjs/platform-express';
|
||||
import { Throttle } from '@nestjs/throttler';
|
||||
import * as argon2 from 'argon2';
|
||||
import { IsString, Length } from 'class-validator';
|
||||
import { JwtPayload } from '../common/auth.types';
|
||||
import { CurrentUser, JwtAuthGuard, StaffGuard, StaffRoles } from '../common/guards';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { CardDesignService, ImageKind } from '../card-design/card-design.service';
|
||||
import { SaveCardDesignDto } from '../card-design/dto/card-design.dto';
|
||||
import { BillingService } from '../billing/billing.service';
|
||||
import { CreateStaffDto, UpdateStaffDto } from './dto/staff.dto';
|
||||
import { StaffService } from './staff.service';
|
||||
|
||||
enum ImageKindParam {
|
||||
logo = 'logo',
|
||||
strip = 'strip',
|
||||
}
|
||||
|
||||
function staffOf(user: JwtPayload) {
|
||||
if (user.kind !== 'staff') throw new Error('StaffGuard manquant');
|
||||
return user;
|
||||
}
|
||||
|
||||
class ChangePasswordDto {
|
||||
@IsString()
|
||||
current!: string;
|
||||
|
||||
@IsString() @Length(10, 128, { message: 'Nouveau mot de passe : 10 caractères minimum' })
|
||||
next!: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Espace du Dirigeant (app Pro et espace web) : fiche du magasin, conception
|
||||
* de la carte, comptes des employés. Les employés n'y ont pas accès.
|
||||
*/
|
||||
@Controller('staff')
|
||||
@UseGuards(JwtAuthGuard, StaffGuard)
|
||||
@StaffRoles('MANAGER')
|
||||
export class StaffSpaceController {
|
||||
constructor(
|
||||
private prisma: PrismaService,
|
||||
private config: ConfigService,
|
||||
private designs: CardDesignService,
|
||||
private staff: StaffService,
|
||||
private billing: BillingService,
|
||||
) {}
|
||||
|
||||
@Get('store')
|
||||
async store(@CurrentUser() user: JwtPayload) {
|
||||
const { storeId } = staffOf(user);
|
||||
const store = await this.prisma.store.findUniqueOrThrow({ where: { id: storeId }, include: { subscription: true } });
|
||||
const sub = store.subscription;
|
||||
const subscribed = !!sub?.stripeSubscriptionId && sub.status !== 'CANCELED';
|
||||
return {
|
||||
id: store.id,
|
||||
name: store.name,
|
||||
status: store.status,
|
||||
enrollUrl: `${this.config.get('webUrl')}/c/${store.slug}`,
|
||||
subscription: sub && { status: sub.status, plan: sub.plan, interval: sub.interval },
|
||||
// Pas encore payé : le Dirigeant peut finaliser lui-même l'abonnement.
|
||||
subscribeUrl: subscribed ? null : this.billing.subscribeUrl(store.id),
|
||||
};
|
||||
}
|
||||
|
||||
// ── Carte de fidélité ──
|
||||
@Get('card-design')
|
||||
getDesign(@CurrentUser() user: JwtPayload) {
|
||||
return this.designs.get(staffOf(user).storeId);
|
||||
}
|
||||
|
||||
@Put('card-design')
|
||||
saveDesign(@CurrentUser() user: JwtPayload, @Body() dto: SaveCardDesignDto) {
|
||||
return this.designs.save(staffOf(user).storeId, dto);
|
||||
}
|
||||
|
||||
@Post('card-design/images/:kind')
|
||||
@UseInterceptors(FileInterceptor('file', { limits: { fileSize: 2 * 1024 * 1024 } }))
|
||||
upload(
|
||||
@CurrentUser() user: JwtPayload,
|
||||
@Param('kind', new ParseEnumPipe(ImageKindParam, { exceptionFactory: () => new BadRequestException('Type d’image inconnu') }))
|
||||
kind: ImageKind,
|
||||
@UploadedFile() file: Express.Multer.File | undefined,
|
||||
) {
|
||||
return this.designs.saveImage(staffOf(user).storeId, kind, file);
|
||||
}
|
||||
|
||||
// ── Employés ──
|
||||
@Get('team')
|
||||
team(@CurrentUser() user: JwtPayload) {
|
||||
return this.staff.list(staffOf(user).storeId);
|
||||
}
|
||||
|
||||
@Post('team')
|
||||
addMember(@CurrentUser() user: JwtPayload, @Body() dto: CreateStaffDto) {
|
||||
return this.staff.create(staffOf(user).storeId, dto);
|
||||
}
|
||||
|
||||
@Patch('team/:id')
|
||||
updateMember(@CurrentUser() user: JwtPayload, @Param('id') id: string, @Body() dto: UpdateStaffDto) {
|
||||
const me = staffOf(user);
|
||||
// Évite de se retirer soi-même l'accès (plus aucun Dirigeant).
|
||||
if (id === me.sub && (dto.active === false || (dto.role && dto.role !== 'MANAGER'))) {
|
||||
throw new ForbiddenException('Vous ne pouvez pas désactiver votre propre compte ni retirer votre rôle de Dirigeant.');
|
||||
}
|
||||
return this.staff.update(me.storeId, id, dto);
|
||||
}
|
||||
|
||||
@Post('team/:id/reset-password')
|
||||
@HttpCode(200)
|
||||
resetMember(@CurrentUser() user: JwtPayload, @Param('id') id: string) {
|
||||
const me = staffOf(user);
|
||||
if (id === me.sub) throw new ForbiddenException('Changez votre propre mot de passe depuis « Mon compte ».');
|
||||
return this.staff.resetPassword(me.storeId, id);
|
||||
}
|
||||
}
|
||||
|
||||
/** Mot de passe personnel : tous les rôles. */
|
||||
@Controller('staff/password')
|
||||
@UseGuards(JwtAuthGuard, StaffGuard)
|
||||
export class StaffPasswordController {
|
||||
constructor(private prisma: PrismaService) {}
|
||||
|
||||
@Post()
|
||||
@HttpCode(200)
|
||||
@Throttle({ default: { limit: 5, ttl: 10 * 60_000 } })
|
||||
async change(@CurrentUser() user: JwtPayload, @Body() dto: ChangePasswordDto) {
|
||||
const me = staffOf(user);
|
||||
const staff = await this.prisma.staffUser.findUniqueOrThrow({ where: { id: me.sub } });
|
||||
if (!(await argon2.verify(staff.passwordHash, dto.current))) throw new BadRequestException('Mot de passe actuel incorrect');
|
||||
await this.prisma.staffUser.update({ where: { id: me.sub }, data: { passwordHash: await argon2.hash(dto.next) } });
|
||||
return { ok: true };
|
||||
}
|
||||
}
|
||||
|
|
@ -53,7 +53,7 @@ export class AdminStatsController {
|
|||
}
|
||||
}
|
||||
|
||||
/** App Pro : statistiques et exports pour les gérants (formule Pro). */
|
||||
/** App Pro : statistiques et exports pour les dirigeants (formule Pro). */
|
||||
@Controller('staff')
|
||||
@UseGuards(JwtAuthGuard, StaffGuard)
|
||||
@StaffRoles('MANAGER')
|
||||
|
|
@ -74,7 +74,7 @@ export class StaffStatsController {
|
|||
return this.stats.compute(user.storeId, period(days));
|
||||
}
|
||||
|
||||
/** Le fichier part par e-mail au gérant : rien à stocker sur le téléphone. */
|
||||
/** Le fichier part par e-mail au dirigeant : rien à stocker sur le téléphone. */
|
||||
@Post('export')
|
||||
@HttpCode(200)
|
||||
@Throttle({ default: { limit: 5, ttl: 10 * 60_000 } })
|
||||
|
|
|
|||
17
backend/src/stores/activation.ts
Normal file
17
backend/src/stores/activation.ts
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
import { Logger } from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
const logger = new Logger('Activation');
|
||||
|
||||
/**
|
||||
* Ouverture automatique d'un magasin en brouillon dès que tout est prêt :
|
||||
* abonnement payé ET carte de fidélité conçue (appelé après chacun des deux).
|
||||
*/
|
||||
export async function activateIfReady(prisma: PrismaService, storeId: string) {
|
||||
const { count } = await prisma.store.updateMany({
|
||||
where: { id: storeId, status: 'DRAFT', cardDesign: { isNot: null }, subscription: { is: { status: 'ACTIVE' } } },
|
||||
data: { status: 'ACTIVE' },
|
||||
});
|
||||
if (count) logger.log(`Magasin ${storeId} ouvert automatiquement (abonnement payé, carte conçue)`);
|
||||
return count > 0;
|
||||
}
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
import { PartialType } from '@nestjs/mapped-types';
|
||||
import { StoreStatus } from '@prisma/client';
|
||||
import { BillingInterval, Plan, StoreStatus } from '@prisma/client';
|
||||
import { Transform } from 'class-transformer';
|
||||
import {
|
||||
IsEmail,
|
||||
|
|
@ -67,6 +67,15 @@ export class CreateStoreDto {
|
|||
minScanIntervalMin!: number;
|
||||
}
|
||||
|
||||
/** Création depuis l'admin : la formule choisie part avec le lien de paiement. */
|
||||
export class AdminCreateStoreDto extends CreateStoreDto {
|
||||
@IsEnum(Plan)
|
||||
plan!: Plan;
|
||||
|
||||
@IsEnum(BillingInterval)
|
||||
interval!: BillingInterval;
|
||||
}
|
||||
|
||||
export class UpdateStoreDto extends PartialType(CreateStoreDto) {}
|
||||
|
||||
export class SetStoreStatusDto {
|
||||
|
|
|
|||
18
backend/src/stores/slug.ts
Normal file
18
backend/src/stores/slug.ts
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
import { randomBytes } from 'crypto';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
/** « Boulangerie Le Fournil » → « boulangerie-le-fournil-k3f9 » (suffixe : non devinable, sans collision). */
|
||||
export async function uniqueSlug(prisma: PrismaService, name: string) {
|
||||
const base =
|
||||
name
|
||||
.normalize('NFD')
|
||||
.replace(/[̀-ͯ]/g, '')
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-|-$/g, '')
|
||||
.slice(0, 40) || 'magasin';
|
||||
for (;;) {
|
||||
const slug = `${base}-${randomBytes(3).toString('hex').slice(0, 4)}`;
|
||||
if (!(await prisma.store.findUnique({ where: { slug }, select: { id: true } }))) return slug;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,12 +1,18 @@
|
|||
import { Body, Controller, Get, Param, Patch, Post, Query, UseGuards } from '@nestjs/common';
|
||||
import { AdminGuard, JwtAuthGuard } from '../common/guards';
|
||||
import { CreateStoreDto, ListStoresQuery, SetStoreStatusDto, UpdateStoreDto } from './dto/store.dto';
|
||||
import { AdminCreateStoreDto, ListStoresQuery, SetStoreStatusDto, UpdateStoreDto } from './dto/store.dto';
|
||||
import { StoresService } from './stores.service';
|
||||
import { BillingService } from '../billing/billing.service';
|
||||
import { StaffService } from '../staff/staff.service';
|
||||
|
||||
@Controller('admin/stores')
|
||||
@UseGuards(JwtAuthGuard, AdminGuard)
|
||||
export class StoresController {
|
||||
constructor(private stores: StoresService) {}
|
||||
constructor(
|
||||
private stores: StoresService,
|
||||
private billing: BillingService,
|
||||
private staff: StaffService,
|
||||
) {}
|
||||
|
||||
@Get()
|
||||
list(@Query() query: ListStoresQuery) {
|
||||
|
|
@ -14,8 +20,25 @@ export class StoresController {
|
|||
}
|
||||
|
||||
@Post()
|
||||
create(@Body() dto: CreateStoreDto) {
|
||||
return this.stores.create(dto);
|
||||
async create(@Body() dto: AdminCreateStoreDto) {
|
||||
const { plan, interval, ...fields } = dto;
|
||||
const store = await this.stores.create(fields);
|
||||
// Tout part automatiquement : compte Dirigeant du contact + lien de paiement par e-mail.
|
||||
const manager = await this.staff
|
||||
.create(store.id, { displayName: store.contactName, email: store.contactEmail, role: 'MANAGER' })
|
||||
.catch(() => null); // e-mail déjà utilisé par un autre compte : à créer à la main
|
||||
const link = await this.billing
|
||||
.checkoutLink(store.id, {
|
||||
plan,
|
||||
interval,
|
||||
sendEmail: true,
|
||||
credentials: manager ? { email: manager.email, password: manager.provisionalPassword } : undefined,
|
||||
})
|
||||
.catch(async (e: Error) => {
|
||||
await this.billing.choosePlan(store.id, plan, interval);
|
||||
return { url: null, emailedTo: null, error: e.message };
|
||||
});
|
||||
return { ...store, manager, link };
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { Prisma, Store, StoreStatus } from '@prisma/client';
|
||||
import { randomBytes } from 'crypto';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { uniqueSlug } from './slug';
|
||||
import { CreateStoreDto, ListStoresQuery, UpdateStoreDto } from './dto/store.dto';
|
||||
|
||||
/** Transitions autorisées depuis l'admin (la suspension pour impayé viendra de Stripe). */
|
||||
|
|
@ -64,7 +64,7 @@ export class StoresService {
|
|||
|
||||
async create(dto: CreateStoreDto) {
|
||||
const store = await this.prisma.store.create({
|
||||
data: { ...this.toData(dto), slug: await this.uniqueSlug(dto.name) } as Prisma.StoreCreateInput,
|
||||
data: { ...this.toData(dto), slug: await uniqueSlug(this.prisma, dto.name) } as Prisma.StoreCreateInput,
|
||||
});
|
||||
return this.present(store);
|
||||
}
|
||||
|
|
@ -110,20 +110,4 @@ export class StoresService {
|
|||
const { maxAmountCents, minScanIntervalSec, ...rest } = s;
|
||||
return { ...rest, maxAmountEuros: maxAmountCents / 100, minScanIntervalMin: Math.round(minScanIntervalSec / 60) };
|
||||
}
|
||||
|
||||
/** « Boulangerie Le Fournil » → « boulangerie-le-fournil-k3f9 » (suffixe : non devinable, sans collision). */
|
||||
private async uniqueSlug(name: string) {
|
||||
const base =
|
||||
name
|
||||
.normalize('NFD')
|
||||
.replace(/[̀-ͯ]/g, '')
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-|-$/g, '')
|
||||
.slice(0, 40) || 'magasin';
|
||||
for (;;) {
|
||||
const slug = `${base}-${randomBytes(3).toString('hex').slice(0, 4)}`;
|
||||
if (!(await this.prisma.store.findUnique({ where: { slug }, select: { id: true } }))) return slug;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { Prisma } from '@prisma/client';
|
||||
import { fill, ModuleId, moduleActive, moduleConfig, quantity } from '../modules/catalog';
|
||||
import { fill, ModuleId, moduleActive, moduleConfig, quantity, rewardVars } from '../modules/catalog';
|
||||
|
||||
/** Tout ce qu'il faut pour dessiner une carte, chargé en une requête. */
|
||||
export const CARD_WITH_CONTEXT = {
|
||||
|
|
@ -67,11 +67,11 @@ export function reminderText(card: CardWithContext) {
|
|||
return fill(String(moduleConfig(card.store, 'reminders').message), messageVars(card));
|
||||
}
|
||||
|
||||
/** Annonce du cadeau d'anniversaire (« 3 tampons offerts sur votre carte. »), vide si message seulement. */
|
||||
/** Annonce du cadeau d'anniversaire (« Pour vous : 3 tampons offerts. »), vide si message seulement. */
|
||||
export function birthdayGiftText(store: CardWithContext['store']) {
|
||||
const c = moduleConfig(store, 'birthday');
|
||||
const n = Number(c.points);
|
||||
return n > 0 ? fill(String(c.giftText), { quantite: quantity(n, stampMode(store)) }) : '';
|
||||
const vars = rewardVars(Number(c.points), c.gift, stampMode(store));
|
||||
return vars.recompense ? fill(String(c.giftText), vars) : '';
|
||||
}
|
||||
|
||||
export function birthdayText(card: CardWithContext) {
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
||||
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
|
||||
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.
|
||||
|
|
|
|||
|
|
@ -52,6 +52,8 @@ function Navigator() {
|
|||
<Stack.Screen name="stats" options={{ title: 'Statistiques' }} />
|
||||
<Stack.Screen name="loyalty" options={{ title: 'Modules' }} />
|
||||
<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>
|
||||
);
|
||||
|
|
|
|||
51
pro/app/account.tsx
Normal file
51
pro/app/account.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
|
|
@ -8,23 +8,25 @@ import { Banner, Button, Card, T } from '../src/ui';
|
|||
import { font, useColors } from '../src/theme';
|
||||
|
||||
interface Overview {
|
||||
defaultTitle: string;
|
||||
allowed: boolean;
|
||||
maxLength: number;
|
||||
minIntervalHours: number;
|
||||
audience: { cards: number; appleDevices: number };
|
||||
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) =>
|
||||
new Date(d).toLocaleString('fr-FR', { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' });
|
||||
|
||||
/** Campagnes (gérants, formule Pro) : un message envoyé en notification à toutes les cartes du magasin. */
|
||||
/** Campagnes (dirigeants, formule Pro) : un message envoyé en notification à toutes les cartes du magasin. */
|
||||
export default function Campaigns() {
|
||||
const c = useColors();
|
||||
const store = useStore();
|
||||
const [data, setData] = useState<Overview | null>(null);
|
||||
const [message, setMessage] = useState('');
|
||||
const [title, setTitle] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [sent, setSent] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
|
@ -46,7 +48,7 @@ export default function Campaigns() {
|
|||
const blocked = !data || !data.allowed || !!data.nextAllowedAt;
|
||||
|
||||
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: 'Envoyer',
|
||||
|
|
@ -54,7 +56,7 @@ export default function Campaigns() {
|
|||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await api.post('/api/staff/campaigns', { message: text });
|
||||
await api.post('/api/staff/campaigns', { message: text, title: (title ?? data!.defaultTitle).trim() });
|
||||
setMessage('');
|
||||
setSent(true);
|
||||
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.
|
||||
{data ? ` ${data.audience.cards} cartes au total.` : ''}
|
||||
</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
|
||||
value={message}
|
||||
onChangeText={setMessage}
|
||||
|
|
@ -109,6 +124,7 @@ export default function Campaigns() {
|
|||
<T v="h2">Campagnes envoyées</T>
|
||||
{data.items.map((i) => (
|
||||
<Card key={i.id} style={{ padding: 14, gap: 4 }}>
|
||||
{!!i.title && <T v="label">{i.title}</T>}
|
||||
<T>{i.message}</T>
|
||||
<T v="muted" style={{ fontSize: 13 }}>
|
||||
{when(i.createdAt)} · {i.sentByName} · {i.cards} cartes
|
||||
|
|
|
|||
|
|
@ -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 { useStore } from '../../../src/session';
|
||||
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 { font, useColors } from '../../../src/theme';
|
||||
|
||||
|
|
@ -19,7 +21,8 @@ function ago(iso: string) {
|
|||
export default function ClientCard() {
|
||||
const c = useColors();
|
||||
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 (!card) return <Screen style={{ justifyContent: 'center' }}><ActivityIndicator /></Screen>;
|
||||
|
|
@ -27,6 +30,25 @@ export default function ClientCard() {
|
|||
const mode = store.design.pointsMode;
|
||||
const cheapest = store.design.rewards[0];
|
||||
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 (
|
||||
<Screen scroll>
|
||||
|
|
@ -52,6 +74,18 @@ export default function ClientCard() {
|
|||
</T>
|
||||
) : 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 && (
|
||||
<Banner tone="warn">
|
||||
Déjà créditée récemment : nouveau crédit possible à{' '}
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ const REASON: Record<string, string> = {
|
|||
INSUFFICIENT_BALANCE: 'Refusé : solde insuffisant',
|
||||
};
|
||||
|
||||
/** Historique (maquettes 9a/9b) : le gérant voit tout, l'employé ses opérations. */
|
||||
/** Historique (maquettes 9a/9b) : le dirigeant voit tout, l'employé ses opérations. */
|
||||
export default function History() {
|
||||
const c = useColors();
|
||||
const { me } = useSession();
|
||||
|
|
|
|||
|
|
@ -1,11 +1,11 @@
|
|||
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 { SafeAreaView } from 'react-native-safe-area-context';
|
||||
import Svg, { Path } from 'react-native-svg';
|
||||
import { api, Summary } from '../src/api';
|
||||
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';
|
||||
|
||||
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() {
|
||||
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 { me, logout } = useSession();
|
||||
const store = useStore();
|
||||
|
|
@ -59,7 +96,7 @@ export default function Home() {
|
|||
<View style={{ flex: 1 }}>
|
||||
<T v="label" numberOfLines={1}>{store.name}</T>
|
||||
<T v="muted" numberOfLines={1}>
|
||||
{me?.displayName} · {isManager ? 'Gérant' : 'Employé'}
|
||||
{me?.displayName} · {isManager ? 'Dirigeant' : 'Employé'}
|
||||
</T>
|
||||
</View>
|
||||
<Pressable
|
||||
|
|
@ -113,8 +150,11 @@ export default function Home() {
|
|||
|
||||
<View style={{ flex: 1 }} />
|
||||
{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')} />}
|
||||
<Button label="Historique des opérations" variant="secondary" onPress={() => router.push('/history')} />
|
||||
<Button label="Mon compte" variant="secondary" onPress={() => router.push('/account')} />
|
||||
</ScrollView>
|
||||
</SafeAreaView>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -77,7 +77,7 @@ export default function Login() {
|
|||
/>
|
||||
</View>
|
||||
<Button label="Se connecter" onPress={submit} loading={busy} disabled={!email || password.length < 8} />
|
||||
<T v="muted" style={{ textAlign: 'center' }}>Identifiants fournis par votre gérant.</T>
|
||||
<T v="muted" style={{ textAlign: 'center' }}>Identifiants fournis par votre dirigeant.</T>
|
||||
</KeyboardAvoidingView>
|
||||
</SafeAreaView>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ import { Banner, Card, T } from '../src/ui';
|
|||
import { font, useColors } from '../src/theme';
|
||||
import type { ModuleInfo } from '../src/modules';
|
||||
|
||||
/** Modules complémentaires du magasin (gérants) : état et accès aux réglages. */
|
||||
/** Modules complémentaires du magasin (dirigeants) : état et accès aux réglages. */
|
||||
export default function Modules() {
|
||||
const c = useColors();
|
||||
const [list, setList] = useState<ModuleInfo[] | null>(null);
|
||||
|
|
|
|||
|
|
@ -84,7 +84,7 @@ function Field({ f, value, onChange }: { f: FieldDef; value: Value; onChange: (v
|
|||
);
|
||||
}
|
||||
|
||||
/** Réglages complets d'un module (gérants). */
|
||||
/** Réglages complets d'un module (dirigeants). */
|
||||
export default function ModuleScreen() {
|
||||
const { id } = useLocalSearchParams<{ id: string }>();
|
||||
const [m, setM] = useState<ModuleInfo | null>(null);
|
||||
|
|
|
|||
|
|
@ -30,7 +30,7 @@ const PERIODS: [number, string][] = [[30, '30 j'], [90, '3 mois'], [365, '12 moi
|
|||
const euros = (c: number) => (c / 100).toLocaleString('fr-FR', { style: 'currency', currency: 'EUR', maximumFractionDigits: 0 });
|
||||
const pctText = (n: number | null) => (n === null ? '' : `${n >= 0 ? '▲' : '▼'} ${Math.abs(n)} %`);
|
||||
|
||||
/** Statistiques (gérants, formule Pro) et exports CSV envoyés par e-mail. */
|
||||
/** Statistiques (dirigeants, formule Pro) et exports CSV envoyés par e-mail. */
|
||||
export default function StatsScreen() {
|
||||
const c = useColors();
|
||||
const [days, setDays] = useState(30);
|
||||
|
|
|
|||
158
pro/app/team.tsx
Normal file
158
pro/app/team.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
|
|
@ -101,6 +101,7 @@ export const api = {
|
|||
get: <T>(path: string) => request<T>('GET', path),
|
||||
post: <T>(path: string, body: unknown = {}) => request<T>('POST', 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 ─────────────────────────────────────────────
|
||||
|
|
@ -142,6 +143,8 @@ export interface CardInfo {
|
|||
memberSince: string;
|
||||
lastCreditAt: 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 {
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ export function describe(e: unknown): { title: string; detail: string } {
|
|||
case 'AMOUNT_OVER_LIMIT':
|
||||
return {
|
||||
title: `Montant supérieur au plafond (${euros(d.maxAmountCents)})`,
|
||||
detail: "Vérifiez le montant saisi. Pour une commande exceptionnelle, contactez votre gérant. La tentative a été enregistrée.",
|
||||
detail: "Vérifiez le montant saisi. Pour une commande exceptionnelle, contactez votre dirigeant. La tentative a été enregistrée.",
|
||||
};
|
||||
case 'TOO_SOON':
|
||||
return {
|
||||
|
|
|
|||
|
|
@ -21,5 +21,5 @@ export function useCard() {
|
|||
load();
|
||||
}, [load]);
|
||||
|
||||
return { serial, card, error, reload: load };
|
||||
return { serial, card, setCard, error, reload: load };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ const path = require('path');
|
|||
|
||||
const backend = path.join(__dirname, '..', 'backend');
|
||||
require(path.join(backend, 'node_modules', 'ts-node')).register({ transpileOnly: true, compilerOptions: { module: 'commonjs' } });
|
||||
const { PLANS, TRIAL_DAYS } = require(path.join(backend, 'src', 'billing', 'plans.ts'));
|
||||
const { PLANS } = require(path.join(backend, 'src', 'billing', 'plans.ts'));
|
||||
const { MODULES } = require(path.join(backend, 'src', 'modules', 'catalog.ts'));
|
||||
|
||||
/** Fonctions de base de chaque formule (les modules sont listés à part, depuis le catalogue) ; `soon: true` = affichée « Bientôt ». */
|
||||
|
|
@ -40,6 +40,8 @@ const euros = (cents) =>
|
|||
(cents / 100).toLocaleString('fr-FR', { minimumFractionDigits: cents % 100 ? 2 : 0, maximumFractionDigits: 2 }).replace(/ /g, ' ');
|
||||
const plans = Object.values(PLANS);
|
||||
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)} €`;
|
||||
|
||||
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="plan-price"><span data-price data-month="${euros(def.priceCents.MONTH)}" data-year="${euros(def.priceCents.YEAR)}">${euros(def.priceCents.MONTH)}</span> €<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} € par mois — 2 mois offerts">Sans engagement, résiliable à tout moment</p>
|
||||
<a href="/contact/" class="${pro ? 'btn' : 'btn2'}" style="width:100%;margin:20px 0 4px">Essayer ${TRIAL_DAYS} jours gratuits</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>` : ''}
|
||||
<ul class="fl" style="margin-top:${m.intro ? '12px' : '20px'}">
|
||||
${m.items
|
||||
|
|
@ -106,7 +108,7 @@ const TARIF_HERO = `<section class="sec" style="padding-bottom:40px">
|
|||
<div class="w">
|
||||
<p class="eb">Tarif</p>
|
||||
<h1 style="max-width:18ch">Trois formules, aucun engagement.</h1>
|
||||
<p class="lead" style="margin:24px 0 32px">Commencez simple, passez en Pro quand vous voulez faire revenir vos clients plus souvent. ${TRIAL_DAYS} jours d’essai gratuit, sans frais d’installation.</p>
|
||||
<p class="lead" style="margin:24px 0 32px">Commencez simple, passez en Pro quand vous voulez faire revenir vos clients plus souvent. Sans engagement, sans frais d’installation.</p>
|
||||
<div class="seg" role="group" aria-label="Périodicité de paiement" style="margin-bottom:32px">
|
||||
<button type="button" class="on" aria-pressed="true" data-interval="month">Mensuel</button>
|
||||
<button type="button" aria-pressed="false" data-interval="year">Annuel · 2 mois offerts</button>
|
||||
|
|
@ -142,20 +144,20 @@ const EDITS = {
|
|||
['<span data-total>10</span> €', `<span data-total>${euros(PLANS.PRO.priceCents.MONTH)}</span> €`],
|
||||
['<p class="mu" style="font-size:15px">par mois, sans engagement</p>', '<p class="mu" style="font-size:15px" data-sim-hint>par mois, sans engagement</p>'],
|
||||
['<h3>Prélèvement mensuel</h3><p class="mu">10 € par magasin, prélevés chaque mois.</p>', '<h3>Mensuel ou annuel</h3><p class="mu">Prélevé chaque mois, ou une fois par an avec 2 mois offerts. Carte bancaire ou prélèvement SEPA.</p>'],
|
||||
['<p>Non. Le tarif est de 10 € par mois et par magasin, sans frais d’installation et sans commission.</p>', `<p>Non. Vous payez seulement votre formule, à partir de ${FROM} par mois et par magasin, sans frais d’installation et sans commission. Et les ${TRIAL_DAYS} premiers jours sont gratuits.</p>`],
|
||||
['<p>Non. Le tarif est de 10 € par mois et par magasin, sans frais d’installation et sans commission.</p>', `<p>Non. Vous payez seulement votre formule, à partir de ${FROM} par mois et par magasin, sans frais d’installation et sans commission.</p>`],
|
||||
['<p>Automatiquement, au format PDF, après chaque prélèvement mensuel. La TVA n’est pas applicable (art. 293 B du CGI).</p>', '<p>Automatiquement, au format PDF, après chaque prélèvement (mensuel ou annuel). La TVA n’est pas applicable (art. 293 B du CGI).</p>'],
|
||||
['<p>10 € par mois et par magasin. Le simulateur ci-dessus calcule le total.</p>', `<p>Chaque magasin a sa formule. À partir de 3 magasins, la formule Réseau revient à ${euros(PLANS.RESEAU.priceCents.MONTH)} € par mois et par magasin, avec toutes les fonctions Pro. Le simulateur ci-dessus calcule le total.</p>`],
|
||||
],
|
||||
'Main.dc.html': [
|
||||
['<svg class="ico l"><use href="#i-coin"/></svg>10 €/mois</div>', `<svg class="ico l"><use href="#i-coin"/></svg>Dès ${euros(min)} €/mois</div>`],
|
||||
[/<div class="big">10 €<\/div>\s*<p style="font-size:20px;font-weight:600;margin-top:8px">par mois et par magasin<\/p>/, `<p style="font-size:18px;font-weight:600;margin:0 0 4px;opacity:.9">À partir de</p>\n<div class="big">${FROM}</div>\n<p style="font-size:20px;font-weight:600;margin-top:8px">par mois et par magasin</p>`],
|
||||
['<li><svg class="ico t"><use href="#i-check"/></svg>Sans engagement, prélèvement mensuel</li>', `<li><svg class="ico t"><use href="#i-check"/></svg>3 formules, ${TRIAL_DAYS} jours d’essai gratuit</li>\n<li><svg class="ico t"><use href="#i-check"/></svg>Sans engagement, mensuel ou annuel</li>`],
|
||||
['<li><svg class="ico t"><use href="#i-check"/></svg>Sans engagement, prélèvement mensuel</li>', `<li><svg class="ico t"><use href="#i-check"/></svg>3 formules au choix</li>\n<li><svg class="ico t"><use href="#i-check"/></svg>Sans engagement, mensuel ou annuel</li>`],
|
||||
['<a href="/tarif/" style="text-decoration:underline">Voir le détail du tarif</a>', '<a href="/tarif/" style="text-decoration:underline">Comparer les formules</a>'],
|
||||
['<p>10 € par mois et par magasin, sans engagement. Le prélèvement est mensuel et les factures sont automatiques.</p>', `<p>À partir de ${FROM} par mois et par magasin, sans engagement, avec ${TRIAL_DAYS} jours d’essai gratuit. Paiement mensuel ou annuel, factures automatiques.</p>`],
|
||||
['<p>10 € par mois et par magasin, sans engagement. Le prélèvement est mensuel et les factures sont automatiques.</p>', `<p>À partir de ${FROM} par mois et par magasin, sans engagement. Paiement mensuel ou annuel, factures automatiques.</p>`],
|
||||
],
|
||||
'Faq.dc.html': [
|
||||
['<p>Le tarif est de 10 € par mois et par magasin.</p>', `<p>Chaque magasin a sa formule. À partir de 3 magasins, la formule Réseau revient à ${euros(PLANS.RESEAU.priceCents.MONTH)} € par mois et par magasin. <a href="/tarif/">Voir les formules</a>.</p>`],
|
||||
['<p>10 € par mois et par magasin, sans frais d’installation et sans commission. TVA non applicable, art. 293 B du CGI.</p>', `<p>Trois formules : Essentiel à ${euros(PLANS.ESSENTIEL.priceCents.MONTH)} €, Pro à ${euros(PLANS.PRO.priceCents.MONTH)} € et Réseau à ${euros(PLANS.RESEAU.priceCents.MONTH)} € par magasin, par mois. Sans frais d’installation, sans commission, ${TRIAL_DAYS} jours d’essai gratuit. TVA non applicable, art. 293 B du CGI. <a href="/tarif/">Comparer les formules</a>.</p>`],
|
||||
['<p>10 € par mois et par magasin, sans frais d’installation et sans commission. TVA non applicable, art. 293 B du CGI.</p>', `<p>Trois formules : Essentiel à ${euros(PLANS.ESSENTIEL.priceCents.MONTH)} €, Pro à ${euros(PLANS.PRO.priceCents.MONTH)} € et Réseau à ${euros(PLANS.RESEAU.priceCents.MONTH)} € par magasin, par mois. Sans frais d’installation, sans commission. TVA non applicable, art. 293 B du CGI. <a href="/tarif/">Comparer les formules</a>.</p>`],
|
||||
],
|
||||
'Cgv.dc.html': [
|
||||
['<p>Le service est proposé au prix de 10 € par mois et par magasin. TVA non applicable, art. 293 B du CGI.</p>', '<p>Le prix dépend de la formule choisie (Essentiel, Pro ou Réseau) et de sa périodicité (mensuelle ou annuelle). Il est indiqué sur la page <a href="/tarif/">Tarif</a> et rappelé lors de la souscription. TVA non applicable, art. 293 B du CGI.</p>'],
|
||||
|
|
@ -173,7 +175,7 @@ function applyPricing(file, body) {
|
|||
|
||||
const DESCRIPTIONS = {
|
||||
'Main.dc.html': `La carte de fidélité dématérialisée pour les commerces indépendants : vos clients l'ajoutent à Apple Wallet ou Google Wallet, sans application. Dès ${euros(min)} € par mois, sans engagement.`,
|
||||
'Tarif.dc.html': `Trois formules sans engagement : Essentiel ${euros(PLANS.ESSENTIEL.priceCents.MONTH)} €, Pro ${euros(PLANS.PRO.priceCents.MONTH)} €, Réseau ${euros(PLANS.RESEAU.priceCents.MONTH)} € par magasin et par mois. ${TRIAL_DAYS} jours d’essai gratuit, sans frais d’installation. Modules inclus selon la formule.`,
|
||||
'Tarif.dc.html': `Trois formules sans engagement : Essentiel ${euros(PLANS.ESSENTIEL.priceCents.MONTH)} €, Pro ${euros(PLANS.PRO.priceCents.MONTH)} €, Réseau ${euros(PLANS.RESEAU.priceCents.MONTH)} € par magasin et par mois, sans frais d’installation. Modules inclus selon la formule.`,
|
||||
};
|
||||
|
||||
const CSS = [
|
||||
|
|
|
|||
|
|
@ -43,6 +43,10 @@
|
|||
document.querySelectorAll('[data-price],[data-per],[data-note]').forEach(function (el) {
|
||||
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();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -108,7 +108,7 @@
|
|||
<div class="cd row">
|
||||
<div class="num">3</div>
|
||||
<div><p class="dur"><svg class="ico s"><use href="#i-clock"/></svg>Durée estimée : [durée]</p><h3>Comptes employés et app Pro</h3><p class="mu">Vous créez les comptes de votre équipe. Chacun installe l’app MonEspacePro Pro sur son téléphone.</p><div class="who"><span>Vous : inviter l’équipe</span><span>Employés : installer l’app</span></div></div>
|
||||
<div class="win" style="box-shadow:none"><div class="win-b"><div class="ph-r" style="border:0;color:var(--ink)"><span>[Employé 1]</span><span class="pill" style="min-height:28px;font-size:13px">Gérant</span></div><div class="ph-r" style="color:var(--ink);border-color:var(--bd)"><span>[Employé 2]</span><span class="pill" style="min-height:28px;font-size:13px">Employé</span></div></div></div>
|
||||
<div class="win" style="box-shadow:none"><div class="win-b"><div class="ph-r" style="border:0;color:var(--ink)"><span>[Employé 1]</span><span class="pill" style="min-height:28px;font-size:13px">Dirigeant</span></div><div class="ph-r" style="color:var(--ink);border-color:var(--bd)"><span>[Employé 2]</span><span class="pill" style="min-height:28px;font-size:13px">Employé</span></div></div></div>
|
||||
</div>
|
||||
|
||||
<div class="cd row">
|
||||
|
|
|
|||
|
|
@ -128,7 +128,7 @@
|
|||
|
||||
<div id="paiement"><h2 style="font-size:30px">Paiement et résiliation</h2>
|
||||
<div class="faq">
|
||||
<details><summary>Combien ça coûte ?<svg class="ico"><use href="#i-chev"/></svg></summary><p>Trois formules : Essentiel à 19 €, Pro à 39 € et Réseau à 29 € par magasin, par mois. Sans frais d’installation, sans commission, 30 jours d’essai gratuit. TVA non applicable, art. 293 B du CGI. <a href="/tarif/">Comparer les formules</a>.</p></details>
|
||||
<details><summary>Combien ça coûte ?<svg class="ico"><use href="#i-chev"/></svg></summary><p>Trois formules : Essentiel à 19 €, Pro à 39 € et Réseau à 29 € par magasin, par mois. Sans frais d’installation, sans commission. TVA non applicable, art. 293 B du CGI. <a href="/tarif/">Comparer les formules</a>.</p></details>
|
||||
<details><summary>Comment se passe le paiement ?<svg class="ico"><use href="#i-chev"/></svg></summary><p>Vous recevez un lien d’abonnement par e-mail. Le prélèvement est mensuel et la facture PDF est émise automatiquement.</p></details>
|
||||
<details><summary>Puis-je résilier quand je veux ?<svg class="ico"><use href="#i-chev"/></svg></summary><p>Oui, à tout moment. Il n’y a pas d’engagement.</p></details>
|
||||
</div></div>
|
||||
|
|
|
|||
|
|
@ -146,13 +146,13 @@
|
|||
<div>
|
||||
<p class="eb">L’app Pro pour vos employés</p>
|
||||
<h2>Scan, montant, récompenses, historique.</h2>
|
||||
<p class="lead">L’app mobile MonEspacePro Pro tient dans la poche de l’équipe. Deux rôles : gérant et employé.</p>
|
||||
<p class="lead">L’app mobile MonEspacePro Pro tient dans la poche de l’équipe. Deux rôles : dirigeant et employé.</p>
|
||||
<ul class="fl"><li><svg class="ico"><use href="#i-check"/></svg>Scanner la carte du client</li><li><svg class="ico"><use href="#i-check"/></svg>Saisir le montant, valider une récompense</li><li><svg class="ico"><use href="#i-check"/></svg>Retrouver chaque opération dans l’historique</li></ul>
|
||||
</div>
|
||||
<div style="display:flex;flex-wrap:wrap;gap:20px;justify-content:center">
|
||||
<div class="iph sm" style="margin:0"><div class="scr">
|
||||
<div class="ph-t"><svg class="lg" width="24" height="24" aria-hidden="true"><use href="#logo"/></svg>MonEspacePro Pro</div>
|
||||
<div class="seg" style="background:#DADAE2"><span class="on" style="background:#fff;color:#1C1C19">Employé</span><span style="color:#5A5A53">Gérant</span></div>
|
||||
<div class="seg" style="background:#DADAE2"><span class="on" style="background:#fff;color:#1C1C19">Employé</span><span style="color:#5A5A53">Dirigeant</span></div>
|
||||
<div style="display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px">
|
||||
<div class="tile"><svg class="ico"><use href="#i-scan"/></svg>Scanner</div>
|
||||
<div class="tile"><svg class="ico"><use href="#i-coin"/></svg>Montant</div>
|
||||
|
|
|
|||
|
|
@ -245,7 +245,7 @@
|
|||
<li><svg class="ico t"><use href="#i-check"/></svg>La carte à vos couleurs, dans le Wallet</li>
|
||||
<li><svg class="ico t"><use href="#i-check"/></svg>L’app MonEspacePro Pro pour vos employés</li>
|
||||
<li><svg class="ico t"><use href="#i-check"/></svg>L’affichette de comptoir A5 / A6</li>
|
||||
<li><svg class="ico t"><use href="#i-check"/></svg>3 formules, 30 jours d’essai gratuit</li>
|
||||
<li><svg class="ico t"><use href="#i-check"/></svg>3 formules au choix</li>
|
||||
<li><svg class="ico t"><use href="#i-check"/></svg>Sans engagement, mensuel ou annuel</li>
|
||||
<li><svg class="ico t"><use href="#i-check"/></svg>Factures automatiques</li>
|
||||
</ul>
|
||||
|
|
@ -267,7 +267,7 @@
|
|||
<div class="faq">
|
||||
<details open><summary>Mes clients doivent-ils installer une application ?<svg class="ico"><use href="#i-chev"/></svg></summary><p>Non. Ils scannent le QR du comptoir, saisissent leur prénom et leur e-mail, puis ajoutent la carte à Apple Wallet ou Google Wallet.</p></details>
|
||||
<details><summary>Que contient la carte ?<svg class="ico"><use href="#i-chev"/></svg></summary><p>Votre logo, vos couleurs, le solde du client et un QR code personnel. Le solde se met à jour tout seul dans le Wallet.</p></details>
|
||||
<details><summary>Combien ça coûte, et suis-je engagé ?<svg class="ico"><use href="#i-chev"/></svg></summary><p>À partir de 19 € par mois et par magasin, sans engagement, avec 30 jours d’essai gratuit. Paiement mensuel ou annuel, factures automatiques.</p></details>
|
||||
<details><summary>Combien ça coûte, et suis-je engagé ?<svg class="ico"><use href="#i-chev"/></svg></summary><p>À partir de 19 € par mois et par magasin, sans engagement. Paiement mensuel ou annuel, factures automatiques.</p></details>
|
||||
<details><summary>Où sont hébergées les données ?<svg class="ico"><use href="#i-chev"/></svg></summary><p>Dans l’Union européenne. Le client donne son consentement et peut demander la suppression de ses données à tout moment.</p></details>
|
||||
<details><summary>Comment éviter les abus ?<svg class="ico"><use href="#i-chev"/></svg></summary><p>Un plafond par opération, un délai entre deux crédits, et chaque opération est tracée avec l’employé qui l’a faite.</p></details>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -4,12 +4,12 @@
|
|||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Tarif — MonEspacePro</title>
|
||||
<meta name="description" content="Trois formules sans engagement : Essentiel 19 €, Pro 39 €, Réseau 29 € par magasin et par mois. 30 jours d’essai gratuit, sans frais d’installation. Modules inclus selon la formule.">
|
||||
<meta name="description" content="Trois formules sans engagement : Essentiel 19 €, Pro 39 €, Réseau 29 € par magasin et par mois, sans frais d’installation. Modules inclus selon la formule.">
|
||||
<link rel="canonical" href="https://monespacepro.eu/tarif/">
|
||||
<meta name="theme-color" content="#0E7A66">
|
||||
<meta property="og:type" content="website">
|
||||
<meta property="og:title" content="Tarif — MonEspacePro">
|
||||
<meta property="og:description" content="Trois formules sans engagement : Essentiel 19 €, Pro 39 €, Réseau 29 € par magasin et par mois. 30 jours d’essai gratuit, sans frais d’installation. Modules inclus selon la formule.">
|
||||
<meta property="og:description" content="Trois formules sans engagement : Essentiel 19 €, Pro 39 €, Réseau 29 € par magasin et par mois, sans frais d’installation. Modules inclus selon la formule.">
|
||||
<meta property="og:url" content="https://monespacepro.eu/tarif/">
|
||||
<meta property="og:image" content="https://monespacepro.eu/assets/og.png">
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
|
||||
|
|
@ -83,7 +83,7 @@
|
|||
<div class="w">
|
||||
<p class="eb">Tarif</p>
|
||||
<h1 style="max-width:18ch">Trois formules, aucun engagement.</h1>
|
||||
<p class="lead" style="margin:24px 0 32px">Commencez simple, passez en Pro quand vous voulez faire revenir vos clients plus souvent. 30 jours d’essai gratuit, sans frais d’installation.</p>
|
||||
<p class="lead" style="margin:24px 0 32px">Commencez simple, passez en Pro quand vous voulez faire revenir vos clients plus souvent. Sans engagement, sans frais d’installation.</p>
|
||||
<div class="seg" role="group" aria-label="Périodicité de paiement" style="margin-bottom:32px">
|
||||
<button type="button" class="on" aria-pressed="true" data-interval="month">Mensuel</button>
|
||||
<button type="button" aria-pressed="false" data-interval="year">Annuel · 2 mois offerts</button>
|
||||
|
|
@ -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="plan-price"><span data-price data-month="19" data-year="190">19</span> €<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 € par mois — 2 mois offerts">Sans engagement, résiliable à tout moment</p>
|
||||
<a href="/contact/" class="btn2" style="width:100%;margin:20px 0 4px">Essayer 30 jours gratuits</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">
|
||||
<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="plan-price"><span data-price data-month="39" data-year="390">39</span> €<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 € par mois — 2 mois offerts">Sans engagement, résiliable à tout moment</p>
|
||||
<a href="/contact/" class="btn" style="width:100%;margin:20px 0 4px">Essayer 30 jours gratuits</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>
|
||||
<ul class="fl" style="margin-top:12px">
|
||||
<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="plan-price"><span data-price data-month="29" data-year="290">29</span> €<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 € par mois — 2 mois offerts">Sans engagement, résiliable à tout moment</p>
|
||||
<a href="/contact/" class="btn2" style="width:100%;margin:20px 0 4px">Essayer 30 jours gratuits</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>
|
||||
<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>
|
||||
|
|
@ -258,7 +258,7 @@
|
|||
<div class="btnrow" style="margin-top:28px"><a href="/faq/" class="btn2">Toute la FAQ</a></div>
|
||||
</div>
|
||||
<div class="faq">
|
||||
<details open><summary>Y a-t-il des frais d’installation ?<svg class="ico"><use href="#i-chev"/></svg></summary><p>Non. Vous payez seulement votre formule, à partir de 19 € par mois et par magasin, sans frais d’installation et sans commission. Et les 30 premiers jours sont gratuits.</p></details>
|
||||
<details open><summary>Y a-t-il des frais d’installation ?<svg class="ico"><use href="#i-chev"/></svg></summary><p>Non. Vous payez seulement votre formule, à partir de 19 € par mois et par magasin, sans frais d’installation et sans commission.</p></details>
|
||||
<details><summary>Puis-je arrêter quand je veux ?<svg class="ico"><use href="#i-chev"/></svg></summary><p>Oui. Il n’y a pas d’engagement : vous pouvez résilier à tout moment.</p></details>
|
||||
<details><summary>Comment sont émises les factures ?<svg class="ico"><use href="#i-chev"/></svg></summary><p>Automatiquement, au format PDF, après chaque prélèvement (mensuel ou annuel). La TVA n’est pas applicable (art. 293 B du CGI).</p></details>
|
||||
<details><summary>J’ai plusieurs magasins : que paie-je ?<svg class="ico"><use href="#i-chev"/></svg></summary><p>Chaque magasin a sa formule. À partir de 3 magasins, la formule Réseau revient à 29 € par mois et par magasin, avec toutes les fonctions Pro. Le simulateur ci-dessus calcule le total.</p></details>
|
||||
|
|
|
|||
Loading…
Reference in a new issue