Modules complémentaires personnalisables à 100 %

- Catalogue des modules (src/modules/catalog.ts) : Campagnes, Relance des inactifs,
  Offre d'anniversaire, Avis Google, Parrainage, Statistiques & export, Marque blanche
- Chaque formule liste ses modules ; l'admin peut ajouter ou retirer un module sur mesure
- Tous les textes (messages, titres de notification, libellés des cartes et des pages)
  et tous les réglages (délais, heures d'envoi, plafonds, points) sont modifiables
- Réglages stockés en JSON par magasin (Store.modules / moduleOverrides),
  migration 2026-10-08-modules.sql (reprise des réglages existants)
- API générique admin et gérant : /modules, /modules/:id, /modules/:id/override
- Admin : onglet Modules (formulaires générés), formules avec modules inclus
- App Pro : liste des modules et écran de réglages générique
- Site : modules inclus sur chaque formule et tableau comparatif sur la page Tarif

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Tony AVERTY 2026-10-07 11:04:25 +02:00
parent 9096e799f4
commit 5064421c48
45 changed files with 1377 additions and 1581 deletions

View file

@ -6,6 +6,7 @@ interface CatalogEntry {
name: string; name: string;
tagline: string; tagline: string;
priceCents: Record<BillingInterval, number>; priceCents: Record<BillingInterval, number>;
modules: { id: string; name: string; tagline: string }[];
features: string[]; features: string[];
limits: { maxStaff: number | null }; limits: { maxStaff: number | null };
} }
@ -36,18 +37,8 @@ const STATUS: Record<SubscriptionStatus, [string, string]> = {
CANCELED: ['Résilié', 'CLOSED'], CANCELED: ['Résilié', 'CLOSED'],
}; };
/** Libellés lisibles des fonctions du catalogue (src/billing/plans.ts côté API). */ /** Fonctions propres à une formule (hors modules). */
const FEATURE_LABEL: Record<string, string> = { const FEATURE_LABEL: Record<string, string> = { multiStore: 'Carte commune à plusieurs magasins' };
campaigns: 'Notifications push et campagnes',
inactiveReminders: 'Relance des clients inactifs',
birthday: "Offre d'anniversaire",
googleReview: "Collecte d'avis Google",
referral: 'Parrainage',
advancedStats: 'Statistiques avancées',
csvExport: 'Export CSV',
whiteLabel: 'Sans « Propulsé par MonEspacePro »',
multiStore: 'Carte commune à plusieurs magasins',
};
const euros = (c: number) => (c / 100).toLocaleString('fr-FR', { style: 'currency', currency: 'EUR', minimumFractionDigits: c % 100 ? 2 : 0 }); const euros = (c: number) => (c / 100).toLocaleString('fr-FR', { style: 'currency', currency: 'EUR', minimumFractionDigits: c % 100 ? 2 : 0 });
const day = (d: string) => new Date(d).toLocaleDateString('fr-FR', { day: 'numeric', month: 'short', year: 'numeric' }); const day = (d: string) => new Date(d).toLocaleDateString('fr-FR', { day: 'numeric', month: 'short', year: 'numeric' });
@ -151,9 +142,15 @@ export function BillingTab({ storeId, contactEmail, onChange }: { storeId: strin
<span className="muted" style={{ fontSize: 14 }}>{c.tagline}</span> <span className="muted" style={{ fontSize: 14 }}>{c.tagline}</span>
<ul style={{ margin: 0, paddingLeft: 18, fontSize: 14, lineHeight: 1.6 }}> <ul style={{ margin: 0, paddingLeft: 18, fontSize: 14, lineHeight: 1.6 }}>
<li>{c.limits.maxStaff ? `${c.limits.maxStaff} employés` : 'Employés illimités'}</li> <li>{c.limits.maxStaff ? `${c.limits.maxStaff} employés` : 'Employés illimités'}</li>
{c.features.length === 0 && <li>Carte Wallet, points ou tampons, récompenses, mises à jour en direct</li>} <li>Carte Wallet, points ou tampons, récompenses, mises à jour en direct</li>
{c.features.map((f) => <li key={f}>{FEATURE_LABEL[f] ?? f}</li>)} {c.features.map((f) => <li key={f}>{FEATURE_LABEL[f] ?? f}</li>)}
</ul> </ul>
<span style={{ fontSize: 14, fontWeight: 700 }}>{c.modules.length ? `Modules inclus (${c.modules.length})` : 'Aucun module inclus'}</span>
{c.modules.length > 0 && (
<ul style={{ margin: 0, paddingLeft: 18, fontSize: 14, lineHeight: 1.6 }}>
{c.modules.map((m) => <li key={m.id} title={m.tagline}>{m.name}</li>)}
</ul>
)}
</label> </label>
))} ))}
</div> </div>

View file

@ -1,106 +0,0 @@
import { useCallback, useEffect, useState } from 'react';
import { api } from '../api';
interface Birthday {
allowed: boolean;
settings: { enabled: boolean; points: number; message: string | null };
defaultMessage: string;
maxPoints: number;
stats: { cards: number; known: number; giftedThisYear: number };
}
/** Offre d'anniversaire (formule Pro). */
export function BirthdayCard({ storeId }: { storeId: string }) {
const [data, setData] = useState<Birthday | null>(null);
const [enabled, setEnabled] = useState(false);
const [points, setPoints] = useState(0);
const [message, setMessage] = useState('');
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const apply = (d: Birthday) => {
setData(d);
setEnabled(d.settings.enabled);
setPoints(d.settings.points);
setMessage(d.settings.message ?? '');
};
const load = useCallback(() => {
api.get<Birthday>(`/api/admin/stores/${storeId}/birthday`).then(apply).catch((e) => setError(e.message));
}, [storeId]);
useEffect(load, [load]);
if (!data) return error ? <div className="alert error">{error}</div> : null;
async function save() {
setBusy(true);
setError(null);
setNotice(null);
try {
apply(await api.put<Birthday>(`/api/admin/stores/${storeId}/birthday`, { enabled, points, message: message.trim() || null }));
setNotice("Offre d'anniversaire enregistrée.");
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(false);
}
}
const s = data.stats;
return (
<section className="card" style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
<div>
<h2>Offre d'anniversaire</h2>
<p className="muted" style={{ margin: 0 }}>
Les clients peuvent indiquer leur anniversaire (jour et mois) à l'inscription ou sur la page de leur carte.
Le jour J, ils reçoivent une notification et, si vous le souhaitez, des points ou tampons offerts. Un cadeau par an.
</p>
</div>
{error && <div className="alert error" role="alert">{error}</div>}
{notice && <div className="alert ok" role="status">{notice}</div>}
{!data.allowed && <div className="alert warn">L'offre d'anniversaire est réservée aux formules Pro et Réseau (abonnement actif).</div>}
<label style={{ display: 'flex', alignItems: 'center', gap: 10, fontWeight: 600 }}>
<input type="checkbox" checked={enabled} disabled={!data.allowed && !enabled} onChange={(e) => setEnabled(e.target.checked)} />
Offre d'anniversaire activée
</label>
<div style={{ maxWidth: 260 }}>
<label htmlFor="birthday-points" style={{ fontWeight: 600 }}>Points ou tampons offerts</label>
<input
id="birthday-points"
className="input"
type="number"
min={0}
max={data.maxPoints}
value={points}
onChange={(e) => setPoints(Math.max(0, Math.min(data.maxPoints, Math.floor(Number(e.target.value) || 0))))}
/>
<span className="muted" style={{ fontSize: 14 }}>0 = message seulement.</span>
</div>
<div>
<label htmlFor="birthday-msg" style={{ fontWeight: 600 }}>Message</label>
<textarea
id="birthday-msg"
className="input"
rows={2}
maxLength={160}
placeholder={data.defaultMessage}
value={message}
onChange={(e) => setMessage(e.target.value)}
/>
<span className="muted" style={{ fontSize: 14 }}>
Laissez vide pour le texte par défaut. <code>{'{prenom}'}</code> = prénom du client, <code>{'{cadeau}'}</code> = « 3 tampons offerts sur votre carte. »
</span>
</div>
<div className="row between">
<span className="muted" style={{ fontSize: 14 }}>
{s.known} / {s.cards} client(s) ont indiqué leur anniversaire · {s.giftedThisYear} cadeau(x) sur 12 mois
</span>
<button className="btn" disabled={busy} onClick={save}>{busy ? 'Enregistrement…' : 'Enregistrer'}</button>
</div>
</section>
);
}

View file

@ -1,9 +1,5 @@
import { useCallback, useEffect, useState } from 'react'; import { useCallback, useEffect, useState } from 'react';
import { api } from '../api'; import { api } from '../api';
import { RemindersCard } from './RemindersCard';
import { BirthdayCard } from './BirthdayCard';
import { ReviewsCard } from './ReviewsCard';
import { ReferralCard } from './ReferralCard';
interface Campaign { interface Campaign {
id: string; id: string;
@ -16,16 +12,18 @@ interface Campaign {
interface Overview { interface Overview {
allowed: boolean; allowed: boolean;
maxLength: number;
minIntervalHours: number;
audience: { cards: number; appleDevices: number }; audience: { cards: number; appleDevices: number };
nextAllowedAt: string | null; nextAllowedAt: string | null;
items: Campaign[]; items: Campaign[];
} }
const MAX = 160;
const when = (d: string) => const when = (d: string) =>
new Date(d).toLocaleString('fr-FR', { day: 'numeric', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' }); new Date(d).toLocaleString('fr-FR', { day: 'numeric', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' });
export function CampaignsTab({ storeId, storeName }: { storeId: string; storeName: string }) { /** Envoi d'une campagne et historique (dans le module Campagnes). */
export function CampaignSender({ storeId, storeName }: { storeId: string; storeName: string }) {
const [data, setData] = useState<Overview | null>(null); const [data, setData] = useState<Overview | null>(null);
const [message, setMessage] = useState(''); const [message, setMessage] = useState('');
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
@ -62,7 +60,6 @@ export function CampaignsTab({ storeId, storeName }: { storeId: string; storeNam
<> <>
{error && <div className="alert error" role="alert">{error}</div>} {error && <div className="alert error" role="alert">{error}</div>}
{notice && <div className="alert ok" role="status">{notice}</div>} {notice && <div className="alert ok" role="status">{notice}</div>}
{!data.allowed && <div className="alert warn">Les campagnes sont réservées aux formules Pro et Réseau (abonnement actif).</div>}
<section className="card" style={{ display: 'flex', flexDirection: 'column', gap: 16 }}> <section className="card" style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
<div> <div>
@ -77,14 +74,14 @@ export function CampaignsTab({ storeId, storeName }: { storeId: string; storeNam
id="campaign-msg" id="campaign-msg"
className="input" className="input"
rows={3} rows={3}
maxLength={MAX} maxLength={data.maxLength}
placeholder="Ex. : -20 % sur les viennoiseries ce samedi, sur présentation de votre carte !" placeholder="Ex. : -20 % sur les viennoiseries ce samedi, sur présentation de votre carte !"
value={message} value={message}
onChange={(e) => setMessage(e.target.value)} onChange={(e) => setMessage(e.target.value)}
disabled={blocked || busy} disabled={blocked || busy}
/> />
<div className="row between"> <div className="row between">
<span className="muted" style={{ fontSize: 14 }}>{text.length} / {MAX} caractères · 1 campagne par jour maximum</span> <span className="muted" style={{ fontSize: 14 }}>{text.length} / {data.maxLength} caractères · 1 campagne par jour maximum</span>
<button className="btn" disabled={blocked || busy || text.length < 5} onClick={send}> <button className="btn" disabled={blocked || busy || text.length < 5} onClick={send}>
{busy ? 'Envoi…' : 'Envoyer la campagne'} {busy ? 'Envoi…' : 'Envoyer la campagne'}
</button> </button>
@ -92,11 +89,6 @@ export function CampaignsTab({ storeId, storeName }: { storeId: string; storeNam
{data.nextAllowedAt && <div className="alert warn">Prochain envoi possible le {when(data.nextAllowedAt)}.</div>} {data.nextAllowedAt && <div className="alert warn">Prochain envoi possible le {when(data.nextAllowedAt)}.</div>}
</section> </section>
<RemindersCard storeId={storeId} />
<BirthdayCard storeId={storeId} />
<ReviewsCard storeId={storeId} />
<ReferralCard storeId={storeId} />
<section className="card"> <section className="card">
<h2>Historique</h2> <h2>Historique</h2>
{data.items.length === 0 ? ( {data.items.length === 0 ? (

View file

@ -0,0 +1,224 @@
import { useCallback, useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { api } from '../api';
import { CampaignSender } from './CampaignSender';
type Value = string | number | boolean;
export type FieldDef =
| { key: string; type: 'boolean'; label: string; help?: string; default: boolean }
| { key: string; type: 'int' | 'hour'; label: string; help?: string; default: number; min: number; max: number; unit?: string }
| { key: string; type: 'text' | 'textarea' | 'url'; label: string; help?: string; default: string; maxLength: number; variables?: string[] };
export interface ModuleInfo {
id: string;
name: string;
tagline: string;
description: string;
fields: FieldDef[];
inPlan: boolean;
override: boolean | null;
available: boolean;
config: Record<string, Value> & { enabled: boolean };
stats?: Record<string, number | string | null> | null;
}
/** Origine du module pour ce magasin. */
function Origin({ m }: { m: ModuleInfo }) {
const [label, tone] =
m.override === true ? ['Ajouté sur mesure', 'ACTIVE'] : m.override === false ? ['Retiré', 'CLOSED'] : m.inPlan ? ['Inclus dans la formule', 'ACTIVE'] : ['Non inclus', 'DRAFT'];
return <span className={`badge ${tone}`}>{label}</span>;
}
/** Champ de réglage générique, construit depuis la définition du module (API). */
function Field({ f, value, onChange }: { f: FieldDef; value: Value; onChange: (v: Value) => void }) {
const id = `f-${f.key}`;
const help = (
<>
{f.help && <span className="muted" style={{ fontSize: 14 }}>{f.help} </span>}
{'variables' in f && f.variables?.length ? (
<span className="muted" style={{ fontSize: 14 }}>
Variables : {f.variables.map((v) => <code key={v} style={{ marginRight: 6 }}>{v}</code>)}
</span>
) : null}
</>
);
if (f.type === 'boolean') {
return (
<label style={{ display: 'flex', alignItems: 'center', gap: 10, fontWeight: 600 }}>
<input type="checkbox" checked={!!value} onChange={(e) => onChange(e.target.checked)} />
{f.label}
{f.help && <span className="muted" style={{ fontWeight: 400, fontSize: 14 }}>— {f.help}</span>}
</label>
);
}
if (f.type === 'int' || f.type === 'hour') {
return (
<div>
<label htmlFor={id} style={{ fontWeight: 600 }}>{f.label}</label>
<div className="row" style={{ gap: 8, alignItems: 'center' }}>
<input
id={id}
className="input"
type="number"
style={{ width: 120 }}
min={f.min}
max={f.max}
value={Number(value)}
onChange={(e) => onChange(Math.floor(Number(e.target.value) || 0))}
/>
<span className="muted">{f.type === 'hour' ? 'h' : f.unit}</span>
</div>
{help}
</div>
);
}
const t = f as Extract<FieldDef, { maxLength: number }>;
const text = String(value ?? '');
return (
<div>
<label htmlFor={id} style={{ fontWeight: 600 }}>{f.label}</label>
{t.type === 'textarea' ? (
<textarea id={id} className="input" rows={2} maxLength={t.maxLength} value={text} onChange={(e) => onChange(e.target.value)} />
) : (
<input id={id} className="input" type={t.type === 'url' ? 'url' : 'text'} maxLength={t.maxLength} value={text} onChange={(e) => onChange(e.target.value)} />
)}
<div className="row between" style={{ gap: 8 }}>
<span>{help}</span>
<span className="muted" style={{ fontSize: 13 }}>{text.length} / {t.maxLength}</span>
</div>
{t.type !== 'url' && text !== t.default && (
<button type="button" className="link" style={{ fontSize: 14 }} onClick={() => onChange(t.default)}>Remettre le texte par défaut</button>
)}
</div>
);
}
function ModulePanel({ storeId, storeName, initial, onChanged }: { storeId: string; storeName: string; initial: ModuleInfo; onChanged: () => void }) {
const [m, setM] = useState<ModuleInfo>(initial);
const [values, setValues] = useState<Record<string, Value>>(initial.config);
const [open, setOpen] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const base = `/api/admin/stores/${storeId}/modules/${m.id}`;
const apply = (next: ModuleInfo) => {
setM(next);
setValues(next.config);
};
useEffect(() => {
if (open) api.get<ModuleInfo>(base).then(apply).catch((e) => setError(e.message));
}, [open, base]);
async function run(fn: () => Promise<ModuleInfo>, done: string) {
setBusy(true);
setError(null);
setNotice(null);
try {
apply(await fn());
setNotice(done);
onChanged();
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(false);
}
}
const dirty = JSON.stringify(values) !== JSON.stringify(m.config);
return (
<section className="card" style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
<div className="row between" style={{ alignItems: 'flex-start', gap: 12 }}>
<div style={{ flex: '1 1 320px' }}>
<div className="row" style={{ gap: 10, alignItems: 'center' }}>
<h2 style={{ margin: 0 }}>{m.name}</h2>
<Origin m={m} />
{m.available && <span className={`badge ${m.config.enabled ? 'ACTIVE' : 'DRAFT'}`}>{m.config.enabled ? 'Activé' : 'Désactivé'}</span>}
</div>
<p className="muted" style={{ margin: '6px 0 0' }}>{m.description}</p>
</div>
<div className="row" style={{ gap: 8 }}>
<label className="sr-only" htmlFor={`ov-${m.id}`}>Disponibilité du module</label>
<select
id={`ov-${m.id}`}
className="input"
style={{ width: 'auto' }}
disabled={busy}
value={m.override === null ? 'plan' : m.override ? 'add' : 'remove'}
onChange={(e) => {
const v = e.target.value === 'plan' ? null : e.target.value === 'add';
run(() => api.put<ModuleInfo>(`${base}/override`, { value: v }), v === null ? 'Module remis selon la formule.' : v ? 'Module ajouté sur mesure.' : 'Module retiré.');
}}
>
<option value="plan">Selon la formule{m.inPlan ? ' (inclus)' : ' (non inclus)'}</option>
<option value="add">Ajouter sur mesure</option>
<option value="remove">Retirer</option>
</select>
<button type="button" className="btn secondary" onClick={() => setOpen(!open)} aria-expanded={open}>
{open ? 'Fermer' : 'Personnaliser'}
</button>
</div>
</div>
{error && <div className="alert error" role="alert">{error}</div>}
{notice && <div className="alert ok" role="status">{notice}</div>}
{open && (
<>
{!m.available && <div className="alert warn">Module non disponible pour ce magasin : ajoutez-le sur mesure ou changez de formule pour l'activer. Vous pouvez déjà préparer ses réglages.</div>}
<label style={{ display: 'flex', alignItems: 'center', gap: 10, fontWeight: 700 }}>
<input type="checkbox" checked={!!values.enabled} onChange={(e) => setValues({ ...values, enabled: e.target.checked })} />
Module activé
</label>
{m.fields.map((f) => (
<Field key={f.key} f={f} value={values[f.key]} onChange={(v) => setValues({ ...values, [f.key]: v })} />
))}
{m.stats && (
<div className="row" style={{ gap: 24 }}>
{Object.entries(m.stats).map(([k, v]) => (
<div key={k}>
<div style={{ fontSize: 22, fontWeight: 800 }}>{v ?? '—'}</div>
<div className="muted" style={{ fontSize: 14 }}>{k}</div>
</div>
))}
</div>
)}
{m.id === 'stats' && <Link to="../statistiques">Voir les statistiques du magasin →</Link>}
<div className="row" style={{ gap: 8, justifyContent: 'flex-end' }}>
{dirty && <button type="button" className="btn secondary" disabled={busy} onClick={() => setValues(m.config)}>Annuler</button>}
<button type="button" className="btn" disabled={busy || !dirty} onClick={() => run(() => api.put<ModuleInfo>(base, values), 'Réglages enregistrés.')}>
{busy ? 'Enregistrement…' : 'Enregistrer'}
</button>
</div>
{m.id === 'campaigns' && m.available && m.config.enabled && <CampaignSender storeId={storeId} storeName={storeName} />}
</>
)}
</section>
);
}
/** Onglet « Modules » : modules complémentaires du magasin, disponibilité sur mesure et réglages complets. */
export function ModulesTab({ storeId, storeName }: { storeId: string; storeName: string }) {
const [list, setList] = useState<ModuleInfo[] | null>(null);
const [error, setError] = useState<string | null>(null);
const load = useCallback(() => {
api.get<ModuleInfo[]>(`/api/admin/stores/${storeId}/modules`).then(setList).catch((e) => setError(e.message));
}, [storeId]);
useEffect(load, [load]);
if (!list) return error ? <div className="alert error">{error}</div> : <p className="muted">Chargement…</p>;
const active = list.filter((m) => m.available && m.config.enabled).length;
return (
<>
<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.
</p>
{list.map((m) => (
<ModulePanel key={m.id} storeId={storeId} storeName={storeName} initial={m} onChanged={load} />
))}
</>
);
}

View file

@ -1,87 +0,0 @@
import { useCallback, useEffect, useState } from 'react';
import { api } from '../api';
interface Referral {
allowed: boolean;
settings: { enabled: boolean; points: number; friendPoints: number };
maxPoints: number;
maxRewardsPer30Days: number;
stats: { referred: number; rewarded: number };
}
/** Parrainage (formule Pro). */
export function ReferralCard({ storeId }: { storeId: string }) {
const [data, setData] = useState<Referral | null>(null);
const [enabled, setEnabled] = useState(false);
const [points, setPoints] = useState(5);
const [friendPoints, setFriendPoints] = useState(0);
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const apply = (d: Referral) => {
setData(d);
setEnabled(d.settings.enabled);
setPoints(d.settings.points);
setFriendPoints(d.settings.friendPoints);
};
const load = useCallback(() => {
api.get<Referral>(`/api/admin/stores/${storeId}/referral`).then(apply).catch((e) => setError(e.message));
}, [storeId]);
useEffect(load, [load]);
if (!data) return error ? <div className="alert error">{error}</div> : null;
const clamp = (v: string) => Math.max(0, Math.min(data.maxPoints, Math.floor(Number(v) || 0)));
async function save() {
setBusy(true);
setError(null);
setNotice(null);
try {
apply(await api.put<Referral>(`/api/admin/stores/${storeId}/referral`, { enabled, points, friendPoints }));
setNotice('Parrainage enregistré.');
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(false);
}
}
return (
<section className="card" style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
<div>
<h2>Parrainage</h2>
<p className="muted" style={{ margin: 0 }}>
Chaque client a un lien personnel (sur la page et au dos de sa carte). Quand un ami s'inscrit avec ce lien puis fait son premier passage,
le parrain est récompensé, et l'ami aussi si vous le souhaitez. Au plus {data.maxRewardsPer30Days} récompenses par parrain sur 30 jours.
</p>
</div>
{error && <div className="alert error" role="alert">{error}</div>}
{notice && <div className="alert ok" role="status">{notice}</div>}
{!data.allowed && <div className="alert warn">Le parrainage est réservé aux formules Pro et Réseau (abonnement actif).</div>}
<label style={{ display: 'flex', alignItems: 'center', gap: 10, fontWeight: 600 }}>
<input type="checkbox" checked={enabled} disabled={!data.allowed && !enabled} onChange={(e) => setEnabled(e.target.checked)} />
Parrainage activé
</label>
<div className="row" style={{ gap: 16 }}>
<div style={{ width: 220 }}>
<label htmlFor="ref-points" style={{ fontWeight: 600 }}>Offerts au parrain</label>
<input id="ref-points" className="input" type="number" min={0} max={data.maxPoints} value={points} onChange={(e) => setPoints(clamp(e.target.value))} />
</div>
<div style={{ width: 220 }}>
<label htmlFor="ref-friend" style={{ fontWeight: 600 }}>Offerts au filleul</label>
<input id="ref-friend" className="input" type="number" min={0} max={data.maxPoints} value={friendPoints} onChange={(e) => setFriendPoints(clamp(e.target.value))} />
</div>
</div>
<div className="row between">
<span className="muted" style={{ fontSize: 14 }}>
{data.stats.referred} filleul(s) inscrit(s) · {data.stats.rewarded} venu(s) en magasin
</span>
<button className="btn" disabled={busy} onClick={save}>{busy ? 'Enregistrement…' : 'Enregistrer'}</button>
</div>
</section>
);
}

View file

@ -1,101 +0,0 @@
import { useCallback, useEffect, useState } from 'react';
import { api } from '../api';
interface Reminders {
allowed: boolean;
settings: { enabled: boolean; days: number; message: string | null };
defaultMessage: string;
dayChoices: number[];
stats: { pending: number; sentLast30Days: number; cameBack: number; totalReminded: number };
}
/** Relance automatique des clients inactifs (formule Pro). */
export function RemindersCard({ storeId }: { storeId: string }) {
const [data, setData] = useState<Reminders | null>(null);
const [enabled, setEnabled] = useState(false);
const [days, setDays] = useState(45);
const [message, setMessage] = useState('');
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const apply = (d: Reminders) => {
setData(d);
setEnabled(d.settings.enabled);
setDays(d.settings.days);
setMessage(d.settings.message ?? '');
};
const load = useCallback(() => {
api.get<Reminders>(`/api/admin/stores/${storeId}/reminders`).then(apply).catch((e) => setError(e.message));
}, [storeId]);
useEffect(load, [load]);
if (!data) return error ? <div className="alert error">{error}</div> : null;
async function save() {
setBusy(true);
setError(null);
setNotice(null);
try {
apply(await api.put<Reminders>(`/api/admin/stores/${storeId}/reminders`, { enabled, days, message: message.trim() || null }));
setNotice('Réglages de relance enregistrés.');
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(false);
}
}
const s = data.stats;
return (
<section className="card" style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
<div>
<h2>Relance des clients inactifs</h2>
<p className="muted" style={{ margin: 0 }}>
Un client qui n'est pas revenu depuis le délai choisi reçoit automatiquement une notification sur sa carte (entre 10 h et 19 h).
Une seule relance par absence : il doit revenir pour pouvoir être relancé à nouveau.
</p>
</div>
{error && <div className="alert error" role="alert">{error}</div>}
{notice && <div className="alert ok" role="status">{notice}</div>}
{!data.allowed && <div className="alert warn">La relance automatique est réservée aux formules Pro et Réseau (abonnement actif).</div>}
<label style={{ display: 'flex', alignItems: 'center', gap: 10, fontWeight: 600 }}>
<input type="checkbox" checked={enabled} disabled={!data.allowed && !enabled} onChange={(e) => setEnabled(e.target.checked)} />
Relance automatique activée
</label>
<div role="group" aria-label="Délai d'inactivité" className="row" style={{ gap: 8, alignItems: 'center' }}>
<span>Relancer après</span>
{data.dayChoices.map((d) => (
<button key={d} type="button" className="chip" aria-pressed={days === d} onClick={() => setDays(d)}>
{d} jours
</button>
))}
</div>
<div>
<label htmlFor="reminder-msg" style={{ fontWeight: 600 }}>Message</label>
<textarea
id="reminder-msg"
className="input"
rows={2}
maxLength={160}
placeholder={data.defaultMessage}
value={message}
onChange={(e) => setMessage(e.target.value)}
/>
<span className="muted" style={{ fontSize: 14 }}>
Laissez vide pour le texte par défaut. <code>{'{prenom}'}</code> et <code>{'{solde}'}</code> sont remplacés par le prénom et le solde du client.
</span>
</div>
<div className="row between">
<span className="muted" style={{ fontSize: 14 }}>
{s.pending} client(s) inactif(s) à relancer · {s.sentLast30Days} relance(s) sur 30 jours · {s.cameBack} / {s.totalReminded} client(s) relancé(s) revenu(s)
</span>
<button className="btn" disabled={busy} onClick={save}>{busy ? 'Enregistrement…' : 'Enregistrer'}</button>
</div>
</section>
);
}

View file

@ -1,100 +0,0 @@
import { useCallback, useEffect, useState } from 'react';
import { api } from '../api';
interface Reviews {
allowed: boolean;
settings: { enabled: boolean; url: string | null; afterVisits: number; message: string | null };
defaultMessage: string;
visitChoices: number[];
stats: { asked: number; clicked: number };
}
/** Collecte d'avis Google (formule Pro). */
export function ReviewsCard({ storeId }: { storeId: string }) {
const [data, setData] = useState<Reviews | null>(null);
const [enabled, setEnabled] = useState(false);
const [url, setUrl] = useState('');
const [afterVisits, setAfterVisits] = useState(2);
const [message, setMessage] = useState('');
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const apply = (d: Reviews) => {
setData(d);
setEnabled(d.settings.enabled);
setUrl(d.settings.url ?? '');
setAfterVisits(d.settings.afterVisits);
setMessage(d.settings.message ?? '');
};
const load = useCallback(() => {
api.get<Reviews>(`/api/admin/stores/${storeId}/reviews`).then(apply).catch((e) => setError(e.message));
}, [storeId]);
useEffect(load, [load]);
if (!data) return error ? <div className="alert error">{error}</div> : null;
async function save() {
setBusy(true);
setError(null);
setNotice(null);
try {
apply(await api.put<Reviews>(`/api/admin/stores/${storeId}/reviews`, { enabled, url: url.trim() || null, afterVisits, message: message.trim() || null }));
setNotice("Collecte d'avis enregistrée.");
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(false);
}
}
return (
<section className="card" style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
<div>
<h2>Avis Google</h2>
<p className="muted" style={{ margin: 0 }}>
Après le nombre de passages choisi, le client reçoit une seule fois une notification qui l'invite à laisser un avis (2 h après son passage).
Le lien est aussi au dos de sa carte et sur sa page. Règle Google : aucune récompense en échange d'un avis.
</p>
</div>
{error && <div className="alert error" role="alert">{error}</div>}
{notice && <div className="alert ok" role="status">{notice}</div>}
{!data.allowed && <div className="alert warn">La collecte d'avis est réservée aux formules Pro et Réseau (abonnement actif).</div>}
<label style={{ display: 'flex', alignItems: 'center', gap: 10, fontWeight: 600 }}>
<input type="checkbox" checked={enabled} disabled={!data.allowed && !enabled} onChange={(e) => setEnabled(e.target.checked)} />
Collecte d'avis activée
</label>
<div>
<label htmlFor="review-url" style={{ fontWeight: 600 }}>Lien de la fiche Google</label>
<input id="review-url" className="input" type="url" placeholder="https://g.page/r/…/review" value={url} onChange={(e) => setUrl(e.target.value)} />
<span className="muted" style={{ fontSize: 14 }}>
Dans Google Business Profile : « Demander des avis » → copier le lien.
</span>
</div>
<div role="group" aria-label="Nombre de passages" className="row" style={{ gap: 8, alignItems: 'center' }}>
<span>Demander après</span>
{data.visitChoices.map((n) => (
<button key={n} type="button" className="chip" aria-pressed={afterVisits === n} onClick={() => setAfterVisits(n)}>
{n} passage{n > 1 ? 's' : ''}
</button>
))}
</div>
<div>
<label htmlFor="review-msg" style={{ fontWeight: 600 }}>Message</label>
<textarea id="review-msg" className="input" rows={2} maxLength={160} placeholder={data.defaultMessage} value={message} onChange={(e) => setMessage(e.target.value)} />
<span className="muted" style={{ fontSize: 14 }}>Laissez vide pour le texte par défaut. <code>{'{prenom}'}</code> = prénom du client.</span>
</div>
<div className="row between">
<span className="muted" style={{ fontSize: 14 }}>
{data.stats.asked} demande(s) envoyée(s) · {data.stats.clicked} clic(s) vers Google
</span>
<button className="btn" disabled={busy} onClick={save}>{busy ? 'Enregistrement…' : 'Enregistrer'}</button>
</div>
</section>
);
}

View file

@ -6,14 +6,14 @@ import { StoreForm } from '../components/StoreForm';
import { CardWizard } from './CardWizard'; import { CardWizard } from './CardWizard';
import { StaffTab } from './StaffTab'; import { StaffTab } from './StaffTab';
import { BillingTab } from './BillingTab'; import { BillingTab } from './BillingTab';
import { CampaignsTab } from './CampaignsTab'; import { ModulesTab } from './ModulesTab';
import { StatsTab } from './StatsTab'; import { StatsTab } from './StatsTab';
const TABS = [ const TABS = [
['infos', 'Infos'], ['infos', 'Infos'],
['carte', 'Carte de fidélité'], ['carte', 'Carte de fidélité'],
['employes', 'Employés'], ['employes', 'Employés'],
['campagnes', 'Fidélisation'], ['modules', 'Modules'],
['statistiques', 'Statistiques'], ['statistiques', 'Statistiques'],
['facturation', 'Facturation'], ['facturation', 'Facturation'],
] as const; ] as const;
@ -113,7 +113,7 @@ export function StorePage() {
/> />
<Route path="carte" element={<CardWizard store={store} onSaved={reload} />} /> <Route path="carte" element={<CardWizard store={store} onSaved={reload} />} />
<Route path="employes" element={<StaffTab storeId={store.id} />} /> <Route path="employes" element={<StaffTab storeId={store.id} />} />
<Route path="campagnes" element={<CampaignsTab storeId={store.id} storeName={store.name} />} /> <Route path="modules" element={<ModulesTab storeId={store.id} storeName={store.name} />} />
<Route path="statistiques" element={<StatsTab storeId={store.id} storeSlug={store.slug} />} /> <Route path="statistiques" element={<StatsTab storeId={store.id} storeSlug={store.slug} />} />
<Route path="facturation" element={<BillingTab storeId={store.id} contactEmail={store.contactEmail} onChange={reload} />} /> <Route path="facturation" element={<BillingTab storeId={store.id} contactEmail={store.contactEmail} onChange={reload} />} />
</Routes> </Routes>

View file

@ -175,3 +175,6 @@ dialog::backdrop { background: rgb(0 0 0 / 0.45); }
.mode-card:has(input:checked) { border-color: var(--primary); background: var(--primary-soft); } .mode-card:has(input:checked) { border-color: var(--primary); background: var(--primary-soft); }
.upload-drop { border: 2px dashed var(--border-strong); border-radius: 14px; padding: 20px; display: flex; align-items: center; gap: 16px; } .upload-drop { border: 2px dashed var(--border-strong); border-radius: 14px; padding: 20px; display: flex; align-items: center; gap: 16px; }
.upload-drop img { max-height: 72px; max-width: 200px; border-radius: 6px; } .upload-drop img { max-height: 72px; max-width: 200px; border-radius: 6px; }
/* Bouton d’apparence lien (actions secondaires). */
.link { background: none; border: 0; padding: 0; color: var(--primary); font: inherit; text-decoration: underline; cursor: pointer; }

View file

@ -0,0 +1,21 @@
-- Modules complémentaires : les réglages passent dans une colonne JSON par magasin.
-- À exécuter APRÈS les migrations du 2026-10-07 (campagnes, relance-inactifs, anniversaire, avis-google, parrainage).
ALTER TABLE `Store`
ADD COLUMN `modules` JSON NULL,
ADD COLUMN `moduleOverrides` JSON NULL;
-- Reprise des réglages déjà saisis (oui/non stockés en 0/1 : l'API les lit comme tels).
UPDATE `Store` SET `modules` = JSON_OBJECT(
'reminders', JSON_OBJECT('enabled', `reminderEnabled` = 1, 'days', `reminderDays`),
'birthday', JSON_OBJECT('enabled', `birthdayEnabled` = 1, 'points', `birthdayPoints`),
'reviews', JSON_OBJECT('enabled', `reviewEnabled` = 1, 'url', COALESCE(`googleReviewUrl`, ''), 'afterVisits', `reviewAfterVisits`),
'referral', JSON_OBJECT('enabled', `referralEnabled` = 1, 'points', `referralPoints`, 'friendPoints', `referralFriendPoints`)
);
UPDATE `Store` SET `modules` = JSON_SET(`modules`, '$.reminders.message', `reminderMessage`) WHERE `reminderMessage` IS NOT NULL;
UPDATE `Store` SET `modules` = JSON_SET(`modules`, '$.reviews.message', `reviewMessage`) WHERE `reviewMessage` IS NOT NULL;
ALTER TABLE `Store`
DROP COLUMN `reminderEnabled`, DROP COLUMN `reminderDays`, DROP COLUMN `reminderMessage`,
DROP COLUMN `birthdayEnabled`, DROP COLUMN `birthdayPoints`, DROP COLUMN `birthdayMessage`,
DROP COLUMN `reviewEnabled`, DROP COLUMN `googleReviewUrl`, DROP COLUMN `reviewAfterVisits`, DROP COLUMN `reviewMessage`,
DROP COLUMN `referralEnabled`, DROP COLUMN `referralPoints`, DROP COLUMN `referralFriendPoints`;

View file

@ -48,34 +48,10 @@ model Store {
maxAmountCents Int @default(50000) /// plafond d'un montant saisi maxAmountCents Int @default(50000) /// plafond d'un montant saisi
minScanIntervalSec Int @default(300) /// délai minimum entre deux crédits d'un même client minScanIntervalSec Int @default(300) /// délai minimum entre deux crédits d'un même client
// Relance automatique des clients inactifs (formule Pro) /// Réglages des modules complémentaires : { campaigns: { enabled, … }, reminders: {…}, … } (voir src/modules/catalog.ts).
reminderEnabled Boolean @default(false) modules Json?
reminderDays Int @default(45) /// Modules ajoutés (true) ou retirés (false) sur mesure par l'admin, en plus de la formule.
/// Texte de la relance ; {prenom} et {solde} sont remplacés. Vide = texte par défaut. moduleOverrides Json?
reminderMessage String? @db.VarChar(160)
// Offre d'anniversaire (formule Pro)
birthdayEnabled Boolean @default(false)
/// Points ou tampons offerts le jour de l'anniversaire (0 = message seulement).
birthdayPoints Int @default(0)
/// Texte du message ; {prenom} et {cadeau} sont remplacés. Vide = texte par défaut.
birthdayMessage String? @db.VarChar(160)
// Collecte d'avis Google (formule Pro)
reviewEnabled Boolean @default(false)
/// Lien « Demander des avis » de la fiche Google du magasin.
googleReviewUrl String? @db.VarChar(500)
/// Demande envoyée après ce nombre de passages (crédits).
reviewAfterVisits Int @default(2)
/// Texte de la demande ; {prenom} est remplacé. Vide = texte par défaut.
reviewMessage String? @db.VarChar(160)
// Parrainage (formule Pro)
referralEnabled Boolean @default(false)
/// Offerts au parrain quand son filleul fait son premier passage.
referralPoints Int @default(5)
/// Offerts au filleul à son premier passage (0 = rien).
referralFriendPoints Int @default(0)
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt

View file

@ -14,12 +14,13 @@ import { BillingModule } from './billing/billing.controller';
import { EntitlementsModule } from './billing/entitlements.service'; import { EntitlementsModule } from './billing/entitlements.service';
import { WalletModule } from './wallet/wallet.module'; import { WalletModule } from './wallet/wallet.module';
import { CampaignsModule } from './campaigns/campaigns.controller'; import { CampaignsModule } from './campaigns/campaigns.controller';
import { RemindersModule } from './reminders/reminders.controller'; import { RemindersModule } from './reminders/reminders.service';
import { BirthdaysModule } from './birthdays/birthdays.controller'; import { BirthdaysModule } from './birthdays/birthdays.controller';
import { ReviewsModule } from './reviews/reviews.controller'; import { ReviewsModule } from './reviews/reviews.controller';
import { ReferralsModule } from './referrals/referrals.controller';
import { ReferralsCoreModule } from './referrals/referrals.service'; import { ReferralsCoreModule } from './referrals/referrals.service';
import { StatsModule } from './stats/stats.controller'; import { StatsModule } from './stats/stats.controller';
import { ModulesCoreModule } from './modules/modules.service';
import { ModulesModule } from './modules/modules.controller';
import { HealthController } from './health.controller'; import { HealthController } from './health.controller';
@Module({ @Module({
@ -36,12 +37,13 @@ import { HealthController } from './health.controller';
ContactModule, ContactModule,
BillingModule, BillingModule,
EntitlementsModule, EntitlementsModule,
ModulesCoreModule,
ModulesModule,
CampaignsModule, CampaignsModule,
RemindersModule, RemindersModule,
BirthdaysModule, BirthdaysModule,
ReviewsModule, ReviewsModule,
ReferralsCoreModule, ReferralsCoreModule,
ReferralsModule,
StatsModule, StatsModule,
], ],
controllers: [HealthController], controllers: [HealthController],

View file

@ -1,12 +1,12 @@
import { ForbiddenException, Global, Injectable, Module } from '@nestjs/common'; import { ForbiddenException, Global, Injectable, Module } from '@nestjs/common';
import { Plan } from '@prisma/client'; import { Plan } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service'; import { PrismaService } from '../prisma/prisma.service';
import { Feature, hasFeature, PLANS } from './plans'; import { PLANS } from './plans';
/** /**
* Droits d'un magasin selon sa formule. Un magasin sans abonnement actif * Droits d'un magasin selon sa formule. Un magasin sans abonnement actif
* (brouillon, essai expiré, impayé) a les droits de la formule Essentiel : * (brouillon, essai expiré, impayé) a les droits de la formule Essentiel.
* on ne casse jamais ce qui fonctionne, on bloque seulement les fonctions Pro. * Les modules complémentaires sont gérés par ModulesService.
*/ */
@Injectable() @Injectable()
export class EntitlementsService { export class EntitlementsService {
@ -17,24 +17,6 @@ export class EntitlementsService {
return sub && sub.status === 'ACTIVE' ? sub.plan : 'ESSENTIEL'; return sub && sub.status === 'ACTIVE' ? sub.plan : 'ESSENTIEL';
} }
async can(storeId: string, feature: Feature) {
return hasFeature(await this.planOf(storeId), feature);
}
/** Erreur « 403 PLAN_REQUIRED » que l'admin et l'app Pro savent afficher. */
async require(storeId: string, feature: Feature) {
const plan = await this.planOf(storeId);
if (!hasFeature(plan, feature)) {
const needed = (['PRO', 'RESEAU'] as const).find((p) => hasFeature(p, feature))!;
throw new ForbiddenException({
statusCode: 403,
code: 'PLAN_REQUIRED',
requiredPlan: needed,
message: `Fonction disponible avec la formule ${PLANS[needed].name}.`,
});
}
}
/** Nombre d'employés actifs autorisé ; `adding` = 1 pour une création ou une réactivation. */ /** Nombre d'employés actifs autorisé ; `adding` = 1 pour une création ou une réactivation. */
async requireStaffSlot(storeId: string) { async requireStaffSlot(storeId: string) {
const plan = await this.planOf(storeId); const plan = await this.planOf(storeId);

View file

@ -1,4 +1,6 @@
import { BillingInterval, Plan } from '@prisma/client'; import { BillingInterval, Plan } from '@prisma/client';
import { moduleDef } from '../modules/catalog';
import type { ModuleId } from '../modules/catalog';
/** /**
* Catalogue des formules : la seule source de vérité sur ce que chaque * Catalogue des formules : la seule source de vérité sur ce que chaque
@ -6,16 +8,8 @@ import { BillingInterval, Plan } from '@prisma/client';
* `scripts/stripe-setup.ts` avec les mêmes clés (lookup_key). * `scripts/stripe-setup.ts` avec les mêmes clés (lookup_key).
*/ */
export type Feature = /** Fonctions propres à une formule (hors modules complémentaires). */
| 'campaigns' // notifications push de campagne export type Feature = 'multiStore'; // carte commune à plusieurs magasins
| 'inactiveReminders' // relance automatique des clients inactifs
| 'birthday' // offre d'anniversaire
| 'googleReview' // collecte d'avis Google
| 'referral' // parrainage
| 'advancedStats' // statistiques avancées
| 'csvExport' // export CSV clients / opérations
| 'whiteLabel' // retrait de « Propulsé par MonEspacePro »
| 'multiStore'; // carte commune à plusieurs magasins
export interface PlanDefinition { export interface PlanDefinition {
plan: Plan; plan: Plan;
@ -24,20 +18,13 @@ export interface PlanDefinition {
/** Prix TTC = HT (franchise de TVA), en centimes. */ /** Prix TTC = HT (franchise de TVA), en centimes. */
priceCents: Record<BillingInterval, number>; priceCents: Record<BillingInterval, number>;
lookupKey: Record<BillingInterval, string>; lookupKey: Record<BillingInterval, string>;
/** Modules complémentaires inclus (voir src/modules/catalog.ts). */
modules: ModuleId[];
features: Feature[]; features: Feature[];
limits: { maxStaff: number | null }; limits: { maxStaff: number | null };
} }
const PRO_FEATURES: Feature[] = [ const PRO_MODULES: ModuleId[] = ['campaigns', 'reminders', 'birthday', 'reviews', 'referral', 'stats', 'whiteLabel'];
'campaigns',
'inactiveReminders',
'birthday',
'googleReview',
'referral',
'advancedStats',
'csvExport',
'whiteLabel',
];
export const PLANS: Record<Plan, PlanDefinition> = { export const PLANS: Record<Plan, PlanDefinition> = {
ESSENTIEL: { ESSENTIEL: {
@ -46,6 +33,7 @@ export const PLANS: Record<Plan, PlanDefinition> = {
tagline: 'La carte de fidélité dans le Wallet de vos clients', tagline: 'La carte de fidélité dans le Wallet de vos clients',
priceCents: { MONTH: 1900, YEAR: 19000 }, priceCents: { MONTH: 1900, YEAR: 19000 },
lookupKey: { MONTH: 'mep_essentiel_mensuel', YEAR: 'mep_essentiel_annuel' }, lookupKey: { MONTH: 'mep_essentiel_mensuel', YEAR: 'mep_essentiel_annuel' },
modules: [],
features: [], features: [],
limits: { maxStaff: 3 }, limits: { maxStaff: 3 },
}, },
@ -55,7 +43,8 @@ export const PLANS: Record<Plan, PlanDefinition> = {
tagline: 'Faites revenir vos clients', tagline: 'Faites revenir vos clients',
priceCents: { MONTH: 3900, YEAR: 39000 }, priceCents: { MONTH: 3900, YEAR: 39000 },
lookupKey: { MONTH: 'mep_pro_mensuel', YEAR: 'mep_pro_annuel' }, lookupKey: { MONTH: 'mep_pro_mensuel', YEAR: 'mep_pro_annuel' },
features: PRO_FEATURES, modules: PRO_MODULES,
features: [],
limits: { maxStaff: null }, limits: { maxStaff: null },
}, },
RESEAU: { RESEAU: {
@ -64,7 +53,8 @@ export const PLANS: Record<Plan, PlanDefinition> = {
tagline: 'Plusieurs magasins, une seule carte', tagline: 'Plusieurs magasins, une seule carte',
priceCents: { MONTH: 2900, YEAR: 29000 }, priceCents: { MONTH: 2900, YEAR: 29000 },
lookupKey: { MONTH: 'mep_reseau_mensuel', YEAR: 'mep_reseau_annuel' }, lookupKey: { MONTH: 'mep_reseau_mensuel', YEAR: 'mep_reseau_annuel' },
features: [...PRO_FEATURES, 'multiStore'], modules: PRO_MODULES,
features: ['multiStore'],
limits: { maxStaff: null }, limits: { maxStaff: null },
}, },
}; };
@ -96,6 +86,8 @@ export function publicCatalog() {
name: p.name, name: p.name,
tagline: p.tagline, tagline: p.tagline,
priceCents: p.priceCents, priceCents: p.priceCents,
/** Modules inclus, avec leur nom (affichés sur les cartes des formules). */
modules: p.modules.map((id) => ({ id, name: moduleDef(id).name, tagline: moduleDef(id).tagline })),
features: p.features, features: p.features,
limits: p.limits, limits: p.limits,
})); }));

View file

@ -1,22 +1,9 @@
import { Body, Controller, Get, HttpCode, Module, NotFoundException, Param, Post, Put, Query, UseGuards } from '@nestjs/common'; import { Body, Controller, HttpCode, Module, NotFoundException, Param, Post, Query } from '@nestjs/common';
import { Throttle } from '@nestjs/throttler'; import { Throttle } from '@nestjs/throttler';
import { IsBoolean, IsInt, IsOptional, IsString, Max, MaxLength, Min } from 'class-validator'; import { IsInt, Max, Min } from 'class-validator';
import { JwtPayload } from '../common/auth.types';
import { AdminGuard, CurrentUser, JwtAuthGuard, StaffGuard, StaffRoles } from '../common/guards';
import { EnrollmentModule } from '../enrollment/enrollment.module'; import { EnrollmentModule } from '../enrollment/enrollment.module';
import { EnrollmentService } from '../enrollment/enrollment.service'; import { EnrollmentService } from '../enrollment/enrollment.service';
import { BirthdaysService, MAX_BIRTHDAY_POINTS } from './birthdays.service'; import { BirthdaysService } from './birthdays.service';
class BirthdaySettingsDto {
@IsBoolean()
enabled!: boolean;
@IsInt() @Min(0) @Max(MAX_BIRTHDAY_POINTS)
points!: number;
@IsOptional() @IsString() @MaxLength(160)
message?: string | null;
}
class CustomerBirthdayDto { class CustomerBirthdayDto {
@IsInt() @Min(1) @Max(12) @IsInt() @Min(1) @Max(12)
@ -26,42 +13,6 @@ class CustomerBirthdayDto {
day!: number; day!: number;
} }
@Controller('admin/stores/:id/birthday')
@UseGuards(JwtAuthGuard, AdminGuard)
export class AdminBirthdaysController {
constructor(private birthdays: BirthdaysService) {}
@Get()
get(@Param('id') id: string) {
return this.birthdays.overview(id);
}
@Put()
update(@Param('id') id: string, @Body() dto: BirthdaySettingsDto) {
return this.birthdays.update(id, { enabled: dto.enabled, points: dto.points, message: dto.message ?? null });
}
}
/** App Pro : réservé aux gérants. */
@Controller('staff/birthday')
@UseGuards(JwtAuthGuard, StaffGuard)
@StaffRoles('MANAGER')
export class StaffBirthdaysController {
constructor(private birthdays: BirthdaysService) {}
@Get()
get(@CurrentUser() user: JwtPayload) {
if (user.kind !== 'staff') throw new Error('StaffGuard manquant');
return this.birthdays.overview(user.storeId);
}
@Put()
update(@CurrentUser() user: JwtPayload, @Body() dto: BirthdaySettingsDto) {
if (user.kind !== 'staff') throw new Error('StaffGuard manquant');
return this.birthdays.update(user.storeId, { enabled: dto.enabled, points: dto.points, message: dto.message ?? null });
}
}
/** Le client renseigne son anniversaire depuis la page de sa carte (lien secret). */ /** Le client renseigne son anniversaire depuis la page de sa carte (lien secret). */
@Controller('public/cards/:serial/birthday') @Controller('public/cards/:serial/birthday')
export class PublicBirthdayController { export class PublicBirthdayController {
@ -80,8 +31,7 @@ export class PublicBirthdayController {
@Module({ @Module({
imports: [EnrollmentModule], imports: [EnrollmentModule],
controllers: [AdminBirthdaysController, StaffBirthdaysController, PublicBirthdayController], controllers: [PublicBirthdayController],
providers: [BirthdaysService], providers: [BirthdaysService],
exports: [BirthdaysService],
}) })
export class BirthdaysModule {} export class BirthdaysModule {}

View file

@ -1,26 +1,18 @@
import { BadRequestException, Injectable, Logger, NotFoundException, OnApplicationBootstrap, OnApplicationShutdown } from '@nestjs/common'; import { BadRequestException, Injectable, Logger, OnApplicationBootstrap, OnApplicationShutdown, OnModuleInit } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service'; import { PrismaService } from '../prisma/prisma.service';
import { EntitlementsService } from '../billing/entitlements.service'; import { moduleActive, moduleConfig } from '../modules/catalog';
import { ModulesService } from '../modules/modules.service';
import { CardUpdatesService } from '../wallet/card-updates.service'; import { CardUpdatesService } from '../wallet/card-updates.service';
import { birthdayText, CARD_WITH_CONTEXT, DEFAULT_BIRTHDAY } from '../wallet/wallet.types'; import { birthdayText, CARD_WITH_CONTEXT, notificationTitle } from '../wallet/wallet.types';
/** Envois seulement entre 9 h et 19 h (heure de Paris). */
const SEND_HOURS = { from: 9, to: 19 };
/** Un cadeau par an : un cadeau de moins de 300 jours bloque le suivant. */ /** Un cadeau par an : un cadeau de moins de 300 jours bloque le suivant. */
const MIN_GAP_MS = 300 * 24 * 3600_000; const MIN_GAP_MS = 300 * 24 * 3600_000;
export const MAX_BIRTHDAY_POINTS = 100;
export interface BirthdaySettings { /** Jour, mois, heure à Paris. */
enabled: boolean;
points: number;
message: string | null;
}
/** Jour et mois à Paris. */
export function parisDate(now: Date) { export function parisDate(now: Date) {
const parts = new Intl.DateTimeFormat('fr-FR', { timeZone: 'Europe/Paris', year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', hour12: false }).formatToParts(now); const parts = new Intl.DateTimeFormat('fr-FR', { timeZone: 'Europe/Paris', year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', hour12: false }).formatToParts(now);
const get = (t: string) => Number(parts.find((p) => p.type === t)!.value); const get = (t: string) => Number(parts.find((p) => p.type === t)!.value);
return { year: get('year'), month: get('month'), day: get('day'), hour: get('hour') }; return { year: get('year'), month: get('month'), day: get('day'), hour: get('hour') % 24 };
} }
/** Anniversaires fêtés aujourd'hui ; le 29 février est fêté le 28 les années non bissextiles. */ /** Anniversaires fêtés aujourd'hui ; le 29 février est fêté le 28 les années non bissextiles. */
@ -37,21 +29,33 @@ export function isValidBirthday(month: number, day: number) {
} }
/** /**
* Offre d'anniversaire : le jour J, le client reçoit une notification sur sa carte * Module « Offre d'anniversaire » : le jour J, le client reçoit une notification
* et, si le magasin le souhaite, des points ou tampons offerts. * et, si le magasin le souhaite, des points ou tampons offerts.
*/ */
@Injectable() @Injectable()
export class BirthdaysService implements OnApplicationBootstrap, OnApplicationShutdown { export class BirthdaysService implements OnModuleInit, OnApplicationBootstrap, OnApplicationShutdown {
private readonly logger = new Logger(BirthdaysService.name); private readonly logger = new Logger(BirthdaysService.name);
private timer?: NodeJS.Timeout; private timer?: NodeJS.Timeout;
private running = false; private running = false;
constructor( constructor(
private prisma: PrismaService, private prisma: PrismaService,
private entitlements: EntitlementsService, private modules: ModulesService,
private cardUpdates: CardUpdatesService, private cardUpdates: CardUpdatesService,
) {} ) {}
onModuleInit() {
this.modules.registerStats('birthday', async (storeId) => {
const yearAgo = new Date(Date.now() - 365 * 24 * 3600_000);
const [cards, known, gifted] = await Promise.all([
this.prisma.loyaltyCard.count({ where: { storeId } }),
this.prisma.loyaltyCard.count({ where: { storeId, customer: { birthMonth: { not: null } } } }),
this.prisma.loyaltyCard.count({ where: { storeId, birthdayGiftAt: { gte: yearAgo } } }),
]);
return { 'Anniversaires connus': `${known} / ${cards}`, 'Cadeaux (12 mois)': gifted };
});
}
onApplicationBootstrap() { onApplicationBootstrap() {
this.timer = setInterval(() => void this.tick(), 3600_000); this.timer = setInterval(() => void this.tick(), 3600_000);
setTimeout(() => void this.tick(), 90_000); setTimeout(() => void this.tick(), 90_000);
@ -61,58 +65,27 @@ export class BirthdaysService implements OnApplicationBootstrap, OnApplicationSh
clearInterval(this.timer); clearInterval(this.timer);
} }
async overview(storeId: string) {
const store = await this.prisma.store.findUnique({ where: { id: storeId } });
if (!store) throw new NotFoundException('Magasin introuvable');
const yearAgo = new Date(Date.now() - 365 * 24 * 3600_000);
const [allowed, cards, known, giftedThisYear] = await Promise.all([
this.entitlements.can(storeId, 'birthday'),
this.prisma.loyaltyCard.count({ where: { storeId } }),
this.prisma.loyaltyCard.count({ where: { storeId, customer: { birthMonth: { not: null } } } }),
this.prisma.loyaltyCard.count({ where: { storeId, birthdayGiftAt: { gte: yearAgo } } }),
]);
return {
allowed,
settings: { enabled: store.birthdayEnabled, points: store.birthdayPoints, message: store.birthdayMessage } as BirthdaySettings,
defaultMessage: DEFAULT_BIRTHDAY,
maxPoints: MAX_BIRTHDAY_POINTS,
stats: { cards, known, giftedThisYear },
};
}
async update(storeId: string, settings: BirthdaySettings) {
if (settings.enabled) await this.entitlements.require(storeId, 'birthday');
await this.prisma.store.update({
where: { id: storeId },
data: {
birthdayEnabled: settings.enabled,
birthdayPoints: settings.points,
birthdayMessage: settings.message?.replace(/\s+/g, ' ').trim() || null,
},
});
return this.overview(storeId);
}
/** Le client renseigne son anniversaire (inscription ou page de sa carte). */ /** Le client renseigne son anniversaire (inscription ou page de sa carte). */
async setCustomerBirthday(customerId: string, month: number, day: number) { async setCustomerBirthday(customerId: string, month: number, day: number) {
if (!isValidBirthday(month, day)) throw new BadRequestException('Date invalide'); if (!isValidBirthday(month, day)) throw new BadRequestException('Date invalide');
await this.prisma.customer.update({ where: { id: customerId }, data: { birthMonth: month, birthDay: day } }); await this.prisma.customer.update({ where: { id: customerId }, data: { birthMonth: month, birthDay: day } });
} }
/** Passage horaire. */ /** Passage horaire : chaque magasin selon sa propre plage d'envoi. */
async tick(now = new Date()) { async tick(now = new Date()) {
if (this.running) return; if (this.running) return;
const today = parisDate(now);
if (today.hour < SEND_HOURS.from || today.hour >= SEND_HOURS.to) return;
this.running = true; this.running = true;
try { try {
const today = parisDate(now);
const stores = await this.prisma.store.findMany({ const stores = await this.prisma.store.findMany({
where: { birthdayEnabled: true, status: 'ACTIVE', billingSuspended: false }, where: { status: 'ACTIVE', billingSuspended: false },
select: { id: true, name: true, birthdayPoints: true }, select: { id: true, name: true, modules: true, moduleOverrides: true, subscription: { select: { plan: true, status: true } } },
}); });
for (const store of stores) { for (const store of stores) {
if (!(await this.entitlements.can(store.id, 'birthday'))) continue; if (!moduleActive(store, 'birthday')) continue;
const sent = await this.runStore(store, today, now); 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);
if (sent) this.logger.log(`Anniversaire : ${sent} client(s) de ${store.name}`); if (sent) this.logger.log(`Anniversaire : ${sent} client(s) de ${store.name}`);
} }
} catch (e) { } catch (e) {
@ -122,11 +95,11 @@ export class BirthdaysService implements OnApplicationBootstrap, OnApplicationSh
} }
} }
private async runStore(store: { id: string; name: string; birthdayPoints: number }, today: ReturnType<typeof parisDate>, now: Date) { private async runStore(storeId: string, points: number, today: ReturnType<typeof parisDate>, now: Date) {
const notBefore = new Date(now.getTime() - MIN_GAP_MS); const notBefore = new Date(now.getTime() - MIN_GAP_MS);
const cards = await this.prisma.loyaltyCard.findMany({ const cards = await this.prisma.loyaltyCard.findMany({
where: { where: {
storeId: store.id, storeId,
customer: { OR: birthdaysOn(today.year, today.month, today.day) }, customer: { OR: birthdaysOn(today.year, today.month, today.day) },
OR: [{ birthdayGiftAt: null }, { birthdayGiftAt: { lt: notBefore } }], OR: [{ birthdayGiftAt: null }, { birthdayGiftAt: { lt: notBefore } }],
}, },
@ -137,12 +110,12 @@ export class BirthdaysService implements OnApplicationBootstrap, OnApplicationSh
// Mise à jour conditionnelle : jamais deux cadeaux, même si deux passages se chevauchent. // Mise à jour conditionnelle : jamais deux cadeaux, même si deux passages se chevauchent.
const { count } = await this.prisma.loyaltyCard.updateMany({ const { count } = await this.prisma.loyaltyCard.updateMany({
where: { id, OR: [{ birthdayGiftAt: null }, { birthdayGiftAt: { lt: notBefore } }] }, where: { id, OR: [{ birthdayGiftAt: null }, { birthdayGiftAt: { lt: notBefore } }] },
data: { birthdayGiftAt: now, passUpdatedAt: now, ...(store.birthdayPoints > 0 && { balance: { increment: store.birthdayPoints } }) }, data: { birthdayGiftAt: now, passUpdatedAt: now, ...(points > 0 && { balance: { increment: points } }) },
}); });
if (!count) continue; if (!count) continue;
const card = await this.prisma.loyaltyCard.findUniqueOrThrow({ where: { id }, include: CARD_WITH_CONTEXT }); const card = await this.prisma.loyaltyCard.findUniqueOrThrow({ where: { id }, include: CARD_WITH_CONTEXT });
try { try {
await this.cardUpdates.remind(card.id, birthdayText(card), store.name); await this.cardUpdates.remind(card.id, birthdayText(card), notificationTitle(card.store, 'birthday'));
sent++; sent++;
} catch (e) { } catch (e) {
this.logger.warn(`Anniversaire carte ${card.serial} : ${(e as Error).message}`); this.logger.warn(`Anniversaire carte ${card.serial} : ${(e as Error).message}`);

View file

@ -1,39 +1,40 @@
import { BadRequestException, ConflictException, Injectable, NotFoundException } from '@nestjs/common'; import { BadRequestException, ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service'; import { PrismaService } from '../prisma/prisma.service';
import { EntitlementsService } from '../billing/entitlements.service'; import { fill, moduleAvailable, moduleConfig } from '../modules/catalog';
import { ModulesService } from '../modules/modules.service';
import { CardUpdatesService } from '../wallet/card-updates.service'; import { CardUpdatesService } from '../wallet/card-updates.service';
/** Une campagne par jour : Google limite à 3 notifications par carte et par 24 h, et les clients n'aiment pas être harcelés. */
export const CAMPAIGN_INTERVAL_MS = 24 * 3600_000;
@Injectable() @Injectable()
export class CampaignsService { export class CampaignsService {
constructor( constructor(
private prisma: PrismaService, private prisma: PrismaService,
private entitlements: EntitlementsService, private modules: ModulesService,
private cardUpdates: CardUpdatesService, private cardUpdates: CardUpdatesService,
) {} ) {}
/** État de l'écran Campagnes : droits, audience, prochain envoi possible, historique. */ /** État de l'écran Campagnes : droits, audience, prochain envoi possible, historique. */
async overview(storeId: string) { async overview(storeId: string) {
const store = await this.prisma.store.findUnique({ where: { id: storeId }, select: { id: true } }); const store = await this.modules.store(storeId);
if (!store) throw new NotFoundException('Magasin introuvable'); const config = moduleConfig(store, 'campaigns');
const [allowed, cards, appleDevices, items] = await Promise.all([ const interval = Number(config.minIntervalHours) * 3600_000;
this.entitlements.can(storeId, 'campaigns'), const allowed = moduleAvailable(store, 'campaigns') && config.enabled;
const [cards, appleDevices, items] = await Promise.all([
this.prisma.loyaltyCard.count({ where: { storeId } }), this.prisma.loyaltyCard.count({ where: { storeId } }),
this.prisma.appleDevice.count({ where: { registrations: { some: { card: { storeId } } } } }), this.prisma.appleDevice.count({ where: { registrations: { some: { card: { storeId } } } } }),
this.prisma.campaign.findMany({ where: { storeId }, orderBy: { createdAt: 'desc' }, take: 50 }), this.prisma.campaign.findMany({ where: { storeId }, orderBy: { createdAt: 'desc' }, take: 50 }),
]); ]);
const last = items[0]; const last = items[0];
const nextAllowedAt = const nextAllowedAt =
last && last.createdAt.getTime() + CAMPAIGN_INTERVAL_MS > Date.now() last && last.createdAt.getTime() + interval > Date.now()
? new Date(last.createdAt.getTime() + CAMPAIGN_INTERVAL_MS) ? new Date(last.createdAt.getTime() + interval)
: null; : null;
return { allowed, audience: { cards, appleDevices }, nextAllowedAt, items }; return { allowed, 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) {
await this.entitlements.require(storeId, 'campaigns'); 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 } }); const store = await this.prisma.store.findUnique({ where: { id: storeId } });
if (!store) throw new NotFoundException('Magasin introuvable'); if (!store) throw new NotFoundException('Magasin introuvable');
if (store.status !== 'ACTIVE' || store.billingSuspended) { if (store.status !== 'ACTIVE' || store.billingSuspended) {
@ -41,15 +42,16 @@ export class CampaignsService {
} }
const message = rawMessage.replace(/\s+/g, ' ').trim(); const message = rawMessage.replace(/\s+/g, ' ').trim();
if (message.length < 5) throw new BadRequestException('Le message est trop court.'); 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 last = await this.prisma.campaign.findFirst({ where: { storeId }, orderBy: { createdAt: 'desc' } }); const last = await this.prisma.campaign.findFirst({ where: { storeId }, orderBy: { createdAt: 'desc' } });
if (last && last.createdAt.getTime() + CAMPAIGN_INTERVAL_MS > Date.now()) { if (last && last.createdAt.getTime() + interval > Date.now()) {
const at = new Date(last.createdAt.getTime() + CAMPAIGN_INTERVAL_MS); const at = new Date(last.createdAt.getTime() + interval);
throw new ConflictException({ throw new ConflictException({
statusCode: 409, statusCode: 409,
code: 'CAMPAIGN_TOO_SOON', code: 'CAMPAIGN_TOO_SOON',
nextAllowedAt: at, nextAllowedAt: at,
message: `Une campagne par jour au maximum. Prochain envoi possible le ${at.toLocaleString('fr-FR', { timeZone: 'Europe/Paris', dateStyle: 'short', timeStyle: 'short' })}.`, message: `Délai minimum entre deux campagnes : ${config.minIntervalHours} h. Prochain envoi possible le ${at.toLocaleString('fr-FR', { timeZone: 'Europe/Paris', dateStyle: 'short', timeStyle: 'short' })}.`,
}); });
} }
// L'iPhone ne notifie que si le texte change. // L'iPhone ne notifie que si le texte change.
@ -62,7 +64,7 @@ export class CampaignsService {
const campaign = await this.prisma.campaign.create({ const campaign = await this.prisma.campaign.create({
data: { storeId, message, sentByName, cards, appleDevices }, data: { storeId, message, sentByName, cards, appleDevices },
}); });
this.cardUpdates.broadcast(storeId, campaign, store.name); this.cardUpdates.broadcast(storeId, campaign, fill(String(config.title), { magasin: store.name }) || store.name);
return campaign; return campaign;
} }
} }

View file

@ -1,5 +1,5 @@
import type { CardDesign, Plan, Reward, Store, SubscriptionStatus } from '@prisma/client'; import type { CardDesign, Plan, Reward, Store, SubscriptionStatus } from '@prisma/client';
import { hasFeature } from '../billing/plans'; import { fill, moduleActive, moduleConfig, quantity } from '../modules/catalog';
import { nextRewardText, reviewOffered, type CardWithContext } from '../wallet/wallet.types'; import { nextRewardText, reviewOffered, type CardWithContext } from '../wallet/wallet.types';
/** Pages publiques (clients finaux), rendues côté serveur aux couleurs du magasin. */ /** Pages publiques (clients finaux), rendues côté serveur aux couleurs du magasin. */
@ -10,12 +10,12 @@ export type StoreWithDesign = Store & {
}; };
/** Formule Pro et plus : la mention « Propulsé par MonEspacePro » disparaît. */ /** Formule Pro et plus : la mention « Propulsé par MonEspacePro » disparaît. */
const whiteLabel = (s: StoreWithDesign) => s.subscription?.status === 'ACTIVE' && hasFeature(s.subscription.plan, 'whiteLabel'); const whiteLabel = (s: StoreWithDesign) => moduleActive(s, 'whiteLabel');
export type Platform = 'apple' | 'google' | 'other'; export type Platform = 'apple' | 'google' | 'other';
/** Offre d'anniversaire active (formule Pro) : on propose alors au client d'indiquer son anniversaire. */ /** Offre d'anniversaire active (formule Pro) : on propose alors au client d'indiquer son anniversaire. */
export const birthdayOffered = (s: StoreWithDesign) => export const birthdayOffered = (s: StoreWithDesign) =>
s.birthdayEnabled && s.subscription?.status === 'ACTIVE' && hasFeature(s.subscription.plan, 'birthday'); moduleActive(s, 'birthday');
const MONTHS = ['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre']; const MONTHS = ['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'];
@ -31,10 +31,13 @@ function birthdaySelects() {
/** Lecture des listes jour / mois côté navigateur : null si vide, false si incomplet ou impossible. */ /** Lecture des listes jour / mois côté navigateur : null si vide, false si incomplet ou impossible. */
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 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}}`;
function birthdayGiftLine(store: StoreWithDesign) { const stamp = (s: StoreWithDesign) => s.cardDesign?.pointsMode === 'STAMP';
const n = store.birthdayPoints; /** Textes du module Anniversaire, avec {cadeau} (« 3 tampons offerts sur votre carte. » ou vide). */
const unit = store.cardDesign?.pointsMode === 'STAMP' ? 'tampon' : 'point'; function birthdayTexts(store: StoreWithDesign) {
return n > 0 ? `${n} ${unit}${n > 1 ? 's' : ''} offert${n > 1 ? 's' : ''} le jour de votre anniversaire.` : 'Une surprise le jour de votre anniversaire.'; const c = moduleConfig(store, 'birthday');
const n = Number(c.points);
const cadeau = n > 0 ? fill(String(c.giftText), { quantite: quantity(n, stamp(store)) }) : '';
return { enrollHint: fill(String(c.enrollHint), { cadeau }), askTitle: String(c.askTitle), askText: fill(String(c.askText), { cadeau }) };
} }
export function escapeHtml(value: unknown) { export function escapeHtml(value: unknown) {
@ -196,11 +199,11 @@ export function enrollPage(store: StoreWithDesign, referrer: { code: string; fir
</div> </div>
${ ${
referrer referrer
? `<div class="notice" style="margin-bottom:16px"><strong>${e(referrer.firstName)} vous invite !</strong> ${ ? `<div class="notice" style="margin-bottom:16px"><strong>${e(fill(String(moduleConfig(store, 'referral').inviteText), { parrain: referrer.firstName }))}</strong> ${e(
store.referralFriendPoints > 0 Number(moduleConfig(store, 'referral').friendPoints) > 0
? `${store.referralFriendPoints} ${unitLower.replace(/s$/, '')}${store.referralFriendPoints > 1 ? 's' : ''} offert${store.referralFriendPoints > 1 ? 's' : ''} à votre premier passage en magasin.` ? fill(String(moduleConfig(store, 'referral').inviteGiftText), { quantite: quantity(Number(moduleConfig(store, 'referral').friendPoints), stamp(store)) })
: 'Créez votre carte et passez en magasin.' : '',
}</div>` )}</div>`
: '' : ''
} }
${promises(store)} ${promises(store)}
@ -220,7 +223,7 @@ export function enrollPage(store: StoreWithDesign, referrer: { code: string; fir
? `<div class="field"> ? `<div class="field">
<label for="bday">Anniversaire <span class="hint">(facultatif)</span></label> <label for="bday">Anniversaire <span class="hint">(facultatif)</span></label>
${birthdaySelects()} ${birthdaySelects()}
<span class="hint">${e(birthdayGiftLine(store))}</span> <span class="hint">${e(birthdayTexts(store).enrollHint)}</span>
<span class="error" id="e-birthday" hidden>Choisissez le jour et le mois, ou laissez les deux vides.</span> <span class="error" id="e-birthday" hidden>Choisissez le jour et le mois, ou laissez les deux vides.</span>
</div>` </div>`
: '' : ''
@ -338,6 +341,7 @@ export function cardPage(
: appleBtn + googleBtn; : appleBtn + googleBtn;
const none = !opts.apple && !opts.google; const none = !opts.apple && !opts.google;
const askBirthday = birthdayOffered(store) && card.customer.birthMonth === null; const askBirthday = birthdayOffered(store) && card.customer.birthMonth === null;
const referral = moduleConfig(store, 'referral');
const body = ` const body = `
<div style="display:flex;flex-direction:column;gap:8px"> <div style="display:flex;flex-direction:column;gap:8px">
@ -354,8 +358,8 @@ export function cardPage(
<p class="hint" style="text-align:center">Présentez ce QR code au comptoir à chaque passage.</p> <p class="hint" style="text-align:center">Présentez ce QR code au comptoir à chaque passage.</p>
${rewardsList(d.rewards, card.balance, d.pointsMode === 'STAMP')} ${rewardsList(d.rewards, card.balance, d.pointsMode === 'STAMP')}
${askBirthday ? `<form id="bform" class="notice" style="display:flex;flex-direction:column;gap:10px" novalidate> ${askBirthday ? `<form id="bform" class="notice" style="display:flex;flex-direction:column;gap:10px" novalidate>
<strong>Un cadeau pour votre anniversaire ?</strong> <strong>${e(birthdayTexts(store).askTitle)}</strong>
<span>${e(birthdayGiftLine(store))} Indiquez le jour et le mois (l’année n’est pas demandée).</span> <span>${e(birthdayTexts(store).askText)}</span>
${birthdaySelects()} ${birthdaySelects()}
<span class="error" id="e-birthday" hidden>Choisissez un jour et un mois valides.</span> <span class="error" id="e-birthday" hidden>Choisissez un jour et un mois valides.</span>
<button class="btn" id="bsave">Enregistrer</button> <button class="btn" id="bsave">Enregistrer</button>
@ -374,17 +378,15 @@ ${askBirthday ? `<form id="bform" class="notice" style="display:flex;flex-direct
: '' : ''
} }
</div> </div>
${reviewOffered(card.store) && !opts.isNew ? `<a class="btn ghost" href="/api/public/cards/${e(card.serial)}/review${e(q)}" rel="noopener">Laisser un avis Google</a>` : ''} ${reviewOffered(card.store) && !opts.isNew ? `<a class="btn ghost" href="/api/public/cards/${e(card.serial)}/review${e(q)}" rel="noopener">${e(String(moduleConfig(store, 'reviews').linkLabel))}</a>` : ''}
${opts.isNew ? '<p class="small">Un e-mail de confirmation vous a été envoyé avec le lien de votre carte.</p>' : ''} ${opts.isNew ? '<p class="small">Un e-mail de confirmation vous a été envoyé avec le lien de votre carte.</p>' : ''}
${ ${
opts.referralUrl opts.referralUrl
? `<section class="notice" style="display:flex;flex-direction:column;gap:10px"> ? `<section class="notice" style="display:flex;flex-direction:column;gap:10px">
<strong>Parrainez vos proches</strong> <strong>${e(String(referral.sectionTitle))}</strong>
<span>${ <span>${e(fill(String(referral.sectionText), { quantite: quantity(Number(referral.points), stamp(store)) }))}${
store.referralPoints > 0 Number(referral.friendPoints) > 0 ? ` ${e(fill(String(referral.sectionFriendText), { quantite: quantity(Number(referral.friendPoints), stamp(store)) }))}` : ''
? `Gagnez ${store.referralPoints} ${unit.toLowerCase().replace(/s$/, '')}${store.referralPoints > 1 ? 's' : ''} pour chaque ami qui s’inscrit avec votre lien et passe en magasin.` }</span>
: 'Partagez votre lien avec vos proches.'
}${store.referralFriendPoints > 0 ? ` Votre ami reçoit ${store.referralFriendPoints} ${unit.toLowerCase().replace(/s$/, '')}${store.referralFriendPoints > 1 ? 's' : ''} lui aussi.` : ''}</span>
<input type="text" id="reflink" readonly value="${e(opts.referralUrl)}" aria-label="Votre lien de parrainage" onclick="this.select()"> <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> <button class="btn" id="share" type="button">Partager mon lien</button>
${opts.referred ? `<span class="small">${opts.referred} ami${opts.referred > 1 ? 's' : ''} inscrit${opts.referred > 1 ? 's' : ''} grâce à vous.</span>` : ''} ${opts.referred ? `<span class="small">${opts.referred} ami${opts.referred > 1 ? 's' : ''} inscrit${opts.referred > 1 ? 's' : ''} grâce à vous.</span>` : ''}
@ -404,7 +406,7 @@ ${
opts.referralUrl opts.referralUrl
? `document.getElementById('share').addEventListener('click',async function(){ ? `document.getElementById('share').addEventListener('click',async function(){
var url=document.getElementById('reflink').value; var url=document.getElementById('reflink').value;
var text=${JSON.stringify(`Rejoignez le programme de fidélité ${d.programName} de ${store.name} :`)}; var text=${JSON.stringify(fill(String(referral.shareText), { magasin: store.name, programme: d.programName })).replace(/</g, '\\u003c')};
if(navigator.share){try{await navigator.share({title:${JSON.stringify(store.name)},text:text,url:url});return}catch(e){if(e.name==='AbortError')return}} if(navigator.share){try{await navigator.share({title:${JSON.stringify(store.name)},text:text,url:url});return}catch(e){if(e.name==='AbortError')return}}
try{await navigator.clipboard.writeText(url);this.textContent='Lien copié !'}catch(e){document.getElementById('reflink').select()} try{await navigator.clipboard.writeText(url);this.textContent='Lien copié !'}catch(e){document.getElementById('reflink').select()}
});` });`

View file

@ -0,0 +1,248 @@
import type { Plan, SubscriptionStatus } from '@prisma/client';
import { PLANS } from '../billing/plans';
/**
* Modules complémentaires : chaque fonction de fidélisation est un module
* autonome, inclus dans certaines formules et activable sur mesure par
* l'admin. Tous ses textes et réglages sont décrits ici ; l'admin et l'app Pro
* construisent leurs formulaires à partir de ces définitions.
*/
export type ModuleId = 'campaigns' | 'reminders' | 'birthday' | 'reviews' | 'referral' | 'stats' | 'whiteLabel';
export type FieldDef =
| { key: string; type: 'boolean'; label: string; help?: string; default: boolean }
| { key: string; type: 'int'; label: string; help?: string; default: number; min: number; max: number; unit?: string }
| { key: string; type: 'hour'; label: string; help?: string; default: number; min: number; max: number }
| { key: string; type: 'text' | 'textarea'; label: string; help?: string; default: string; maxLength: number; variables?: string[] }
| { key: string; type: 'url'; label: string; help?: string; default: string; maxLength: number };
export interface ModuleDef {
id: ModuleId;
name: string;
/** Une ligne, pour les cartes des formules. */
tagline: string;
description: string;
/** Activé dès que le module est disponible (sinon le commerçant l'active). */
enabledByDefault: boolean;
fields: FieldDef[];
}
const V_CLIENT = ['{prenom}', '{magasin}'];
const title = (def = '{magasin}'): FieldDef => ({
key: 'title',
type: 'text',
label: 'Titre de la notification',
help: 'Affiché en titre du message sur Google Wallet (sur iPhone, le nom du magasin apparaît toujours).',
default: def,
maxLength: 40,
variables: ['{magasin}'],
});
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).' },
];
export const MODULES: ModuleDef[] = [
{
id: 'campaigns',
name: 'Campagnes',
tagline: 'Notifications push à tous vos clients',
description: 'Un message envoyé en notification sur le téléphone de tous les clients, visible ensuite sur leur carte.',
enabledByDefault: true,
fields: [
{ key: 'minIntervalHours', type: 'int', label: 'Délai minimum entre deux campagnes', unit: 'heures', default: 24, min: 8, max: 720, help: 'Google limite à 3 notifications par carte et par jour.' },
{ key: 'maxLength', type: 'int', label: 'Longueur maximale du message', unit: 'caractères', default: 160, min: 20, max: 160 },
title(),
{ key: 'newsLabel', type: 'text', label: 'Titre de la rubrique au dos de la carte Apple', default: 'Actualité', maxLength: 30, help: 'Rubrique partagée par tous les messages (campagnes, relances, anniversaires…).' },
{ key: 'emptyNews', type: 'text', label: 'Texte de la rubrique sans message', default: 'Aucune actualité pour le moment.', maxLength: 80 },
],
},
{
id: 'reminders',
name: 'Relance des inactifs',
tagline: 'Relance automatique des clients absents',
description: "Un client qui n'est pas revenu depuis le délai choisi reçoit automatiquement une notification. Une seule relance par absence.",
enabledByDefault: false,
fields: [
{ key: 'days', type: 'int', label: 'Relancer après', unit: 'jours sans passage', default: 45, min: 7, max: 365 },
{ key: 'message', type: 'textarea', label: 'Message', default: 'Vous nous manquez, {prenom} ! Votre solde de {solde} vous attend en magasin.', maxLength: 160, variables: [...V_CLIENT, '{solde}'] },
title(),
...hours(10, 19),
],
},
{
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.',
enabledByDefault: false,
fields: [
{ key: 'points', type: 'int', label: 'Points ou tampons offerts', unit: '(0 = message seulement)', default: 0, min: 0, max: 1000 },
{ 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.' },
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}'] },
{ key: 'enrollHint', type: 'text', label: "Texte sous le champ à l'inscription", default: 'Une surprise le jour de votre anniversaire ! {cadeau}', maxLength: 120, variables: ['{cadeau}'] },
...hours(9, 19),
],
},
{
id: 'reviews',
name: 'Avis Google',
tagline: 'Invitation à laisser un avis Google',
description: "Après quelques passages, le client reçoit une seule fois une invitation à laisser un avis. Règle Google : aucune récompense en échange d'un avis.",
enabledByDefault: false,
fields: [
{ key: 'url', type: 'url', label: 'Lien de la fiche Google', default: '', maxLength: 500, help: 'Google Business Profile → « Demander des avis » → copier le lien.' },
{ key: 'afterVisits', type: 'int', label: 'Demander après', unit: 'passages', default: 2, min: 1, max: 50 },
{ key: 'delayHours', type: 'int', label: 'Délai après le passage', unit: 'heures', default: 2, min: 0, max: 72 },
{ key: 'message', type: 'textarea', label: 'Message', default: 'Merci pour vos visites, {prenom} ! Votre avis compte beaucoup pour nous : laissez-nous un avis Google en une minute.', maxLength: 160, variables: V_CLIENT },
title(),
{ key: 'linkLabel', type: 'text', label: 'Texte du lien (carte et page)', default: 'Laisser un avis Google', maxLength: 40 },
...hours(10, 20),
],
},
{
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é.',
enabledByDefault: false,
fields: [
{ key: 'points', type: 'int', label: 'Offerts au parrain', unit: 'points / tampons', default: 5, min: 0, max: 1000 },
{ key: 'friendPoints', type: 'int', label: 'Offerts au filleul', unit: 'points / tampons', default: 0, min: 0, max: 1000 },
{ 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}'] },
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: '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: '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 },
],
},
{
id: 'stats',
name: 'Statistiques & export',
tagline: 'Statistiques avancées et export CSV',
description: 'Fréquentation, clients fidèles, heures d’affluence, meilleurs clients, et export CSV des clients et des opérations.',
enabledByDefault: true,
fields: [{ key: 'csvExport', type: 'boolean', label: 'Autoriser l’export CSV', default: true, help: 'Les exports contiennent des données personnelles de vos clients.' }],
},
{
id: 'whiteLabel',
name: 'Marque blanche',
tagline: 'Sans « Propulsé par MonEspacePro »',
description: 'La mention « Propulsé par MonEspacePro » disparaît des pages de vos clients.',
enabledByDefault: true,
fields: [],
},
];
export const MODULE_IDS = MODULES.map((m) => m.id);
export const moduleDef = (id: ModuleId) => MODULES.find((m) => m.id === id)!;
export const isModuleId = (id: string): id is ModuleId => (MODULE_IDS as string[]).includes(id);
/** Ce qu'il faut d'un magasin pour savoir si un module est actif (champs scalaires du Store). */
export interface StoreModules {
modules: unknown;
moduleOverrides: unknown;
subscription?: { plan: Plan; status: SubscriptionStatus } | null;
}
type Values = Record<string, string | number | boolean>;
/** Oui/non tolérant : true/false, 1/0 (reprise SQL), "true"/"false". */
const asBool = (v: unknown): boolean | undefined =>
typeof v === 'boolean' ? v : v === 1 || v === '1' || v === 'true' ? true : v === 0 || v === '0' || v === 'false' ? false : undefined;
const record = (v: unknown): Record<string, unknown> => (v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : {});
/** Le module fait-il partie de la formule active du magasin ? */
export function includedInPlan(store: StoreModules, id: ModuleId) {
return store.subscription?.status === 'ACTIVE' && PLANS[store.subscription.plan].modules.includes(id);
}
/** Ajout ou retrait sur mesure par l'admin : true, false, ou null (formule). */
export function overrideOf(store: StoreModules, id: ModuleId): boolean | null {
const v = record(store.moduleOverrides)[id];
return typeof v === 'boolean' ? v : null;
}
/** Disponible = inclus dans la formule, sauf ajout ou retrait sur mesure. */
export function moduleAvailable(store: StoreModules, id: ModuleId) {
return overrideOf(store, id) ?? includedInPlan(store, id);
}
/** Réglages du module : valeurs enregistrées, complétées par les valeurs par défaut. */
export function moduleConfig(store: StoreModules, id: ModuleId): Values & { enabled: boolean } {
const def = moduleDef(id);
const saved = record(record(store.modules)[id]);
const out: Values = { enabled: asBool(saved.enabled) ?? def.enabledByDefault };
for (const f of def.fields) {
const v = saved[f.key];
out[f.key] = typeof f.default === 'boolean' ? (asBool(v) ?? f.default) : typeof v === typeof f.default ? (v as string | number) : f.default;
}
return out as Values & { enabled: boolean };
}
/** Disponible ET activé par le commerçant. */
export function moduleActive(store: StoreModules, id: ModuleId) {
return moduleAvailable(store, id) && moduleConfig(store, id).enabled;
}
/** Remplace {variables} ; les textes vides retombent sur la valeur par défaut. */
export function fill(template: string, vars: Record<string, string | number>) {
return template
.replace(/\{(\w+)\}/g, (m, k: string) => (k in vars ? String(vars[k]) : m))
.replace(/\s+/g, ' ')
.trim();
}
/** « 3 tampons », « 1 point ». */
export function quantity(n: number, stamp: boolean) {
return `${n} ${stamp ? 'tampon' : 'point'}${n > 1 ? 's' : ''}`;
}
/** 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);
const values: Values = {};
const errors: string[] = [];
if ('enabled' in input) {
if (typeof input.enabled !== 'boolean') errors.push('« Activé » invalide');
else values.enabled = input.enabled;
}
for (const f of def.fields) {
if (!(f.key in input)) continue;
const v = input[f.key];
switch (f.type) {
case 'boolean':
if (typeof v !== 'boolean') errors.push(`${f.label} : valeur invalide`);
else values[f.key] = v;
break;
case 'int':
case 'hour':
if (typeof v !== 'number' || !Number.isInteger(v) || v < f.min || v > f.max) errors.push(`${f.label} : entre ${f.min} et ${f.max}`);
else values[f.key] = v;
break;
default: {
if (typeof v !== 'string') {
errors.push(`${f.label} : texte attendu`);
break;
}
const s = v.replace(/[ \t]+/g, ' ').trim();
if (s.length > f.maxLength) errors.push(`${f.label} : ${f.maxLength} caractères maximum`);
// Texte vide = retour au texte par défaut (sauf le lien, qui peut être vide).
else values[f.key] = s || (f.type === 'url' ? '' : f.default);
}
}
}
const from = values.hourFrom ?? undefined;
const to = values.hourTo ?? undefined;
if (typeof from === 'number' && typeof to === 'number' && from >= to) errors.push("L'heure de début doit précéder l'heure de fin");
return { values, errors };
}

View file

@ -0,0 +1,69 @@
import { Body, Controller, Get, Module, Param, Put, UseGuards } from '@nestjs/common';
import { IsBoolean, IsOptional, ValidateIf } from 'class-validator';
import { JwtPayload } from '../common/auth.types';
import { AdminGuard, CurrentUser, JwtAuthGuard, StaffGuard, StaffRoles } from '../common/guards';
import { ModulesService } from './modules.service';
class OverrideDto {
/** true = ajouté, false = retiré, null = selon la formule. */
@IsOptional() @ValidateIf((_, v) => v !== null) @IsBoolean()
value!: boolean | null;
}
const staffStore = (user: JwtPayload) => {
if (user.kind !== 'staff') throw new Error('StaffGuard manquant');
return user.storeId;
};
@Controller('admin/stores/:id/modules')
@UseGuards(JwtAuthGuard, AdminGuard)
export class AdminModulesController {
constructor(private modules: ModulesService) {}
@Get()
list(@Param('id') id: string) {
return this.modules.list(id);
}
@Get(':module')
get(@Param('id') id: string, @Param('module') module: string) {
return this.modules.get(id, module);
}
/** Réglages : corps libre, validé par la définition du module (catalog.ts). */
@Put(':module')
update(@Param('id') id: string, @Param('module') module: string, @Body() body: Record<string, unknown>) {
return this.modules.update(id, module, body);
}
@Put(':module/override')
override(@Param('id') id: string, @Param('module') module: string, @Body() dto: OverrideDto) {
return this.modules.setOverride(id, module, dto.value ?? null);
}
}
/** App Pro : les gérants règlent eux-mêmes leurs modules. */
@Controller('staff/modules')
@UseGuards(JwtAuthGuard, StaffGuard)
@StaffRoles('MANAGER')
export class StaffModulesController {
constructor(private modules: ModulesService) {}
@Get()
list(@CurrentUser() user: JwtPayload) {
return this.modules.list(staffStore(user));
}
@Get(':module')
get(@CurrentUser() user: JwtPayload, @Param('module') module: string) {
return this.modules.get(staffStore(user), module);
}
@Put(':module')
update(@CurrentUser() user: JwtPayload, @Param('module') module: string, @Body() body: Record<string, unknown>) {
return this.modules.update(staffStore(user), module, body);
}
}
@Module({ controllers: [AdminModulesController, StaffModulesController] })
export class ModulesModule {}

View file

@ -0,0 +1,150 @@
import { BadRequestException, ForbiddenException, Global, Injectable, Module, NotFoundException } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PLANS } from '../billing/plans';
import { PrismaService } from '../prisma/prisma.service';
import { CardUpdatesService } from '../wallet/card-updates.service';
import {
includedInPlan,
isModuleId,
ModuleId,
moduleActive,
moduleAvailable,
moduleConfig,
moduleDef,
MODULES,
overrideOf,
StoreModules,
validateConfig,
} from './catalog';
const WALLET_MODULES: ModuleId[] = ['campaigns', 'reviews', 'referral', 'reminders', 'birthday'];
type StatsProvider = (storeId: string) => Promise<Record<string, number | string | null>>;
type ConfigHook = (storeId: string, values: Record<string, unknown>) => Promise<Record<string, unknown> | void>;
/** Magasin + abonnement : de quoi évaluer les modules. */
const STORE_SELECT = { id: true, name: true, modules: true, moduleOverrides: true, subscription: { select: { plan: true, status: true } } } as const;
@Injectable()
export class ModulesService {
private stats = new Map<ModuleId, StatsProvider>();
private hooks = new Map<ModuleId, ConfigHook>();
constructor(
private prisma: PrismaService,
private cardUpdates: CardUpdatesService,
) {}
/** Les modules visibles sur les cartes Wallet : un changement redessine toutes les cartes du magasin. */
private refreshCards(storeId: string, id: ModuleId) {
if (WALLET_MODULES.includes(id)) this.cardUpdates.notifyStore(storeId);
}
/** Chaque module fournit ses chiffres clés affichés sous ses réglages. */
registerStats(id: ModuleId, provider: StatsProvider) {
this.stats.set(id, provider);
}
/** Contrôle ou complément lors d'un enregistrement (ex. lien Google, codes de parrainage). */
registerHook(id: ModuleId, hook: ConfigHook) {
this.hooks.set(id, hook);
}
async store(storeId: string) {
const store = await this.prisma.store.findUnique({ where: { id: storeId }, select: STORE_SELECT });
if (!store) throw new NotFoundException('Magasin introuvable');
return store;
}
/** Module disponible et activé ? (pour les traitements automatiques et les pages). */
async active(storeId: string, id: ModuleId) {
return moduleActive(await this.store(storeId), id);
}
/** Réglages effectifs si le module est actif, sinon null. */
async activeConfig(storeId: string, id: ModuleId) {
const store = await this.store(storeId);
return moduleActive(store, id) ? moduleConfig(store, id) : null;
}
/** Erreur 403 MODULE_REQUIRED (module absent de la formule) que l'admin et l'app savent afficher. */
async require(storeId: string, id: ModuleId, { mustBeEnabled = true } = {}) {
const store = await this.store(storeId);
const def = moduleDef(id);
if (!moduleAvailable(store, id)) {
const plan = (['PRO', 'RESEAU'] as const).find((p) => PLANS[p].modules.includes(id));
throw new ForbiddenException({
statusCode: 403,
code: 'PLAN_REQUIRED',
module: id,
requiredPlan: plan,
message: `Le module ${def.name} n'est pas inclus dans votre formule${plan ? ` (disponible avec la formule ${PLANS[plan].name})` : ''}.`,
});
}
const config = moduleConfig(store, id);
if (mustBeEnabled && !config.enabled) {
throw new ForbiddenException({ statusCode: 403, code: 'MODULE_DISABLED', module: id, message: `Le module ${def.name} est désactivé. Activez-le dans ses réglages.` });
}
return config;
}
private describe(store: StoreModules, id: ModuleId) {
const def = moduleDef(id);
return {
id,
name: def.name,
tagline: def.tagline,
description: def.description,
fields: def.fields,
inPlan: includedInPlan(store, id),
override: overrideOf(store, id),
available: moduleAvailable(store, id),
config: moduleConfig(store, id),
};
}
/** Liste des modules d'un magasin (écran « Modules »). */
async list(storeId: string) {
const store = await this.store(storeId);
return MODULES.map((m) => this.describe(store, m.id));
}
async get(storeId: string, id: string) {
if (!isModuleId(id)) throw new NotFoundException('Module inconnu');
const store = await this.store(storeId);
const stats = this.stats.get(id);
return { ...this.describe(store, id), stats: stats ? await stats(storeId) : null };
}
/** Enregistre les réglages (commerçant ou admin). Activer exige que le module soit disponible. */
async update(storeId: string, id: string, input: Record<string, unknown>) {
if (!isModuleId(id)) throw new NotFoundException('Module inconnu');
const store = await this.store(storeId);
const { values, errors } = validateConfig(id, input);
if (errors.length) throw new BadRequestException(errors);
if (values.enabled === true) await this.require(storeId, id, { mustBeEnabled: false });
const merged = { ...moduleConfig(store, id), ...values };
if ('hourFrom' in merged && Number(merged.hourFrom) >= Number(merged.hourTo)) throw new BadRequestException(["L'heure de début doit précéder l'heure de fin"]);
const extra = await this.hooks.get(id)?.(storeId, merged);
const all = { ...((store.modules as Record<string, unknown>) ?? {}), [id]: { ...merged, ...(extra ?? {}) } };
await this.prisma.store.update({ where: { id: storeId }, data: { modules: all as Prisma.InputJsonValue } });
this.refreshCards(storeId, id);
return this.get(storeId, id);
}
/** Admin : ajoute (true) ou retire (false) un module sur mesure, ou revient à la formule (null). */
async setOverride(storeId: string, id: string, value: boolean | null) {
if (!isModuleId(id)) throw new NotFoundException('Module inconnu');
const store = await this.store(storeId);
const overrides = { ...((store.moduleOverrides as Record<string, boolean>) ?? {}) };
if (value === null) delete overrides[id];
else overrides[id] = value;
await this.prisma.store.update({ where: { id: storeId }, data: { moduleOverrides: overrides as Prisma.InputJsonValue } });
this.refreshCards(storeId, id);
return this.get(storeId, id);
}
}
@Global()
@Module({ providers: [ModulesService], exports: [ModulesService] })
export class ModulesCoreModule {}

View file

@ -1,60 +0,0 @@
import { Body, Controller, Get, Module, Param, Put, UseGuards } from '@nestjs/common';
import { IsBoolean, IsInt, Max, Min } from 'class-validator';
import { JwtPayload } from '../common/auth.types';
import { AdminGuard, CurrentUser, JwtAuthGuard, StaffGuard, StaffRoles } from '../common/guards';
import { MAX_REFERRAL_POINTS, ReferralsCoreModule, ReferralsService } from './referrals.service';
class ReferralSettingsDto {
@IsBoolean()
enabled!: boolean;
@IsInt() @Min(0) @Max(MAX_REFERRAL_POINTS)
points!: number;
@IsInt() @Min(0) @Max(MAX_REFERRAL_POINTS)
friendPoints!: number;
}
const settings = (dto: ReferralSettingsDto) => ({ enabled: dto.enabled, points: dto.points, friendPoints: dto.friendPoints });
@Controller('admin/stores/:id/referral')
@UseGuards(JwtAuthGuard, AdminGuard)
export class AdminReferralsController {
constructor(private referrals: ReferralsService) {}
@Get()
get(@Param('id') id: string) {
return this.referrals.overview(id);
}
@Put()
update(@Param('id') id: string, @Body() dto: ReferralSettingsDto) {
return this.referrals.update(id, settings(dto));
}
}
/** App Pro : réservé aux gérants. */
@Controller('staff/referral')
@UseGuards(JwtAuthGuard, StaffGuard)
@StaffRoles('MANAGER')
export class StaffReferralsController {
constructor(private referrals: ReferralsService) {}
@Get()
get(@CurrentUser() user: JwtPayload) {
if (user.kind !== 'staff') throw new Error('StaffGuard manquant');
return this.referrals.overview(user.storeId);
}
@Put()
update(@CurrentUser() user: JwtPayload, @Body() dto: ReferralSettingsDto) {
if (user.kind !== 'staff') throw new Error('StaffGuard manquant');
return this.referrals.update(user.storeId, settings(dto));
}
}
@Module({
imports: [ReferralsCoreModule],
controllers: [AdminReferralsController, StaffReferralsController],
})
export class ReferralsModule {}

View file

@ -1,40 +1,45 @@
import { Global, Injectable, Logger, Module, NotFoundException } from '@nestjs/common'; import { Global, Injectable, Logger, Module, OnModuleInit } from '@nestjs/common';
import { randomInt } from 'crypto'; import { randomInt } from 'crypto';
import { Prisma } from '@prisma/client'; import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service'; import { PrismaService } from '../prisma/prisma.service';
import { EntitlementsService } from '../billing/entitlements.service'; import { fill, moduleActive, moduleConfig, quantity, StoreModules } from '../modules/catalog';
import { ModulesService } from '../modules/modules.service';
import { CardUpdatesService } from '../wallet/card-updates.service'; import { CardUpdatesService } from '../wallet/card-updates.service';
import { referralOffered } from '../wallet/wallet.types';
export const MAX_REFERRAL_POINTS = 100;
/** Au-delà, le parrain n'est plus récompensé pendant 30 jours (le filleul l'est toujours). */
export const MAX_REWARDS_PER_30_DAYS = 10;
const ALPHABET = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789'; const ALPHABET = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789';
export interface ReferralSettings {
enabled: boolean;
points: number;
friendPoints: number;
}
const plural = (n: number, stamp: boolean) => `${n} ${stamp ? 'tampon' : 'point'}${n > 1 ? 's' : ''}`;
/** /**
* Parrainage : chaque client a un lien d'inscription personnel. Quand un ami * Module « Parrainage » : chaque client a un lien d'inscription personnel. Quand
* s'inscrit par ce lien puis fait son premier passage en magasin, le parrain * un ami s'inscrit par ce lien puis fait son premier passage en magasin, le
* (et, si le magasin le souhaite, le filleul) reçoit des points. * parrain (et, si le magasin le souhaite, le filleul) reçoit des points.
* Récompense au premier passage réel : une inscription seule ne rapporte rien. * Récompense au premier passage réel : une inscription seule ne rapporte rien.
*/ */
@Injectable() @Injectable()
export class ReferralsService { export class ReferralsService implements OnModuleInit {
private readonly logger = new Logger(ReferralsService.name); private readonly logger = new Logger(ReferralsService.name);
constructor( constructor(
private prisma: PrismaService, private prisma: PrismaService,
private entitlements: EntitlementsService, private modules: ModulesService,
private cardUpdates: CardUpdatesService, private cardUpdates: CardUpdatesService,
) {} ) {}
onModuleInit() {
this.modules.registerStats('referral', async (storeId) => {
const [referred, rewarded] = await Promise.all([
this.prisma.loyaltyCard.count({ where: { storeId, referredById: { not: null } } }),
this.prisma.loyaltyCard.count({ where: { storeId, referredById: { not: null }, referralRewardedAt: { not: null } } }),
]);
return { 'Filleuls inscrits': referred, 'Venus en magasin': rewarded };
});
// À l'activation, chaque carte reçoit son code : le lien apparaît au dos des cartes existantes.
this.modules.registerHook('referral', async (storeId, values) => {
if (!values.enabled) return;
const cards = await this.prisma.loyaltyCard.findMany({ where: { storeId, referralCode: null }, select: { id: true } });
for (const c of cards) await this.ensureCode(c.id);
});
}
/** Code de parrainage de la carte, créé au besoin. */ /** Code de parrainage de la carte, créé au besoin. */
async ensureCode(cardId: string): Promise<string> { async ensureCode(cardId: string): Promise<string> {
const card = await this.prisma.loyaltyCard.findUniqueOrThrow({ where: { id: cardId }, select: { referralCode: true } }); const card = await this.prisma.loyaltyCard.findUniqueOrThrow({ where: { id: cardId }, select: { referralCode: true } });
@ -52,9 +57,9 @@ export class ReferralsService {
throw new Error('Code de parrainage impossible à générer'); throw new Error('Code de parrainage impossible à générer');
} }
/** Parrain d'une inscription (lien ?parrain=CODE) ; null si code inconnu ou parrainage inactif. */ /** Parrain d'une inscription (lien ?parrain=CODE) ; null si code inconnu ou module inactif. */
async findReferrer(store: Parameters<typeof referralOffered>[0] & { id: string }, code: string | undefined | null) { async findReferrer(store: StoreModules & { id: string }, code: string | undefined | null) {
if (!code || !referralOffered(store)) return null; if (!code || !moduleActive(store, 'referral')) return null;
const card = await this.prisma.loyaltyCard.findUnique({ const card = await this.prisma.loyaltyCard.findUnique({
where: { referralCode: code.toUpperCase().slice(0, 16) }, where: { referralCode: code.toUpperCase().slice(0, 16) },
select: { id: true, storeId: true, customer: { select: { firstName: true } } }, select: { id: true, storeId: true, customer: { select: { firstName: true } } },
@ -62,38 +67,6 @@ export class ReferralsService {
return card && card.storeId === store.id ? { id: card.id, firstName: card.customer.firstName } : null; return card && card.storeId === store.id ? { id: card.id, firstName: card.customer.firstName } : null;
} }
async overview(storeId: string) {
const store = await this.prisma.store.findUnique({ where: { id: storeId } });
if (!store) throw new NotFoundException('Magasin introuvable');
const [allowed, referred, rewarded] = await Promise.all([
this.entitlements.can(storeId, 'referral'),
this.prisma.loyaltyCard.count({ where: { storeId, referredById: { not: null } } }),
this.prisma.loyaltyCard.count({ where: { storeId, referredById: { not: null }, referralRewardedAt: { not: null } } }),
]);
return {
allowed,
settings: { enabled: store.referralEnabled, points: store.referralPoints, friendPoints: store.referralFriendPoints } as ReferralSettings,
maxPoints: MAX_REFERRAL_POINTS,
maxRewardsPer30Days: MAX_REWARDS_PER_30_DAYS,
stats: { referred, rewarded },
};
}
async update(storeId: string, settings: ReferralSettings) {
if (settings.enabled) await this.entitlements.require(storeId, 'referral');
await this.prisma.store.update({
where: { id: storeId },
data: { referralEnabled: settings.enabled, referralPoints: settings.points, referralFriendPoints: settings.friendPoints },
});
if (settings.enabled) {
// Chaque carte reçoit son code : le lien apparaît au dos des cartes existantes.
const cards = await this.prisma.loyaltyCard.findMany({ where: { storeId, referralCode: null }, select: { id: true } });
for (const c of cards) await this.ensureCode(c.id);
}
this.cardUpdates.notifyStore(storeId);
return this.overview(storeId);
}
/** Appelé après chaque crédit réussi au comptoir ; ne fait rien hors premier passage d'un filleul. */ /** Appelé après chaque crédit réussi au comptoir ; ne fait rien hors premier passage d'un filleul. */
onCredit(cardId: string) { onCredit(cardId: string) {
void this.rewardFirstVisit(cardId).catch((e) => this.logger.error(`Parrainage carte ${cardId} : ${(e as Error).message}`)); void this.rewardFirstVisit(cardId).catch((e) => this.logger.error(`Parrainage carte ${cardId} : ${(e as Error).message}`));
@ -106,35 +79,39 @@ export class ReferralsService {
}); });
if (!friend?.referredById || friend.referralRewardedAt) return; if (!friend?.referredById || friend.referralRewardedAt) return;
const store = friend.store; const store = friend.store;
if (!referralOffered(store as never) || store.status !== 'ACTIVE' || store.billingSuspended) return; if (!moduleActive(store, 'referral') || store.status !== 'ACTIVE' || store.billingSuspended) return;
const c = moduleConfig(store, 'referral');
const stamp = store.cardDesign?.pointsMode === 'STAMP'; const stamp = store.cardDesign?.pointsMode === 'STAMP';
const title = fill(String(c.title), { magasin: store.name }) || store.name;
const base = { magasin: store.name };
const friendNews = const friendPoints = Number(c.friendPoints);
store.referralFriendPoints > 0 ? `Bienvenue, ${friend.customer.firstName} ! ${plural(store.referralFriendPoints, stamp)} offert${store.referralFriendPoints > 1 ? 's' : ''} grâce à votre parrainage.` : null; const friendNews = friendPoints > 0 ? fill(String(c.friendMessage), { ...base, prenom: friend.customer.firstName, quantite: quantity(friendPoints, stamp) }) : null;
// Conditionnel : un seul cadeau même si deux crédits arrivent en même temps. // Conditionnel : un seul cadeau même si deux crédits arrivent en même temps.
const { count } = await this.prisma.loyaltyCard.updateMany({ const { count } = await this.prisma.loyaltyCard.updateMany({
where: { id: friend.id, referralRewardedAt: null }, where: { id: friend.id, referralRewardedAt: null },
data: { data: {
referralRewardedAt: now, referralRewardedAt: now,
...(friendNews && { balance: { increment: store.referralFriendPoints }, personalNews: friendNews, personalNewsAt: now, passUpdatedAt: now }), ...(friendNews && { balance: { increment: friendPoints }, personalNews: friendNews, personalNewsAt: now, passUpdatedAt: now }),
}, },
}); });
if (!count) return; if (!count) return;
if (friendNews) await this.cardUpdates.remind(friend.id, friendNews, store.name); if (friendNews) await this.cardUpdates.remind(friend.id, friendNews, title);
const points = Number(c.points);
const since = new Date(now.getTime() - 30 * 24 * 3600_000); const since = new Date(now.getTime() - 30 * 24 * 3600_000);
const recent = await this.prisma.loyaltyCard.count({ const recent = await this.prisma.loyaltyCard.count({
where: { referredById: friend.referredById, referralRewardedAt: { gte: since }, id: { not: friend.id } }, where: { referredById: friend.referredById, referralRewardedAt: { gte: since }, id: { not: friend.id } },
}); });
if (store.referralPoints <= 0 || recent >= MAX_REWARDS_PER_30_DAYS) return; if (points <= 0 || recent >= Number(c.maxRewardsPer30Days)) return;
const referrer = await this.prisma.loyaltyCard.findUnique({ where: { id: friend.referredById }, include: { customer: true } }); const referrer = await this.prisma.loyaltyCard.findUnique({ where: { id: friend.referredById }, include: { customer: true } });
if (!referrer || referrer.storeId !== store.id) return; if (!referrer || referrer.storeId !== store.id) return;
const news = `Merci ${referrer.customer.firstName} ! ${friend.customer.firstName} est venu(e) grâce à vous : ${plural(store.referralPoints, stamp)} offert${store.referralPoints > 1 ? 's' : ''}.`; const news = fill(String(c.referrerMessage), { ...base, prenom: referrer.customer.firstName, filleul: friend.customer.firstName, quantite: quantity(points, stamp) });
await this.prisma.loyaltyCard.update({ await this.prisma.loyaltyCard.update({
where: { id: referrer.id }, where: { id: referrer.id },
data: { balance: { increment: store.referralPoints }, personalNews: news, personalNewsAt: now, passUpdatedAt: now }, data: { balance: { increment: points }, personalNews: news, personalNewsAt: now, passUpdatedAt: now },
}); });
await this.cardUpdates.remind(referrer.id, news, store.name); await this.cardUpdates.remind(referrer.id, news, title);
} }
} }

View file

@ -1,58 +0,0 @@
import { Body, Controller, Get, Module, Param, Put, UseGuards } from '@nestjs/common';
import { IsBoolean, IsIn, IsOptional, IsString, MaxLength } from 'class-validator';
import { JwtPayload } from '../common/auth.types';
import { AdminGuard, CurrentUser, JwtAuthGuard, StaffGuard, StaffRoles } from '../common/guards';
import { REMINDER_DAYS, RemindersService } from './reminders.service';
class ReminderSettingsDto {
@IsBoolean()
enabled!: boolean;
@IsIn(REMINDER_DAYS)
days!: number;
@IsOptional() @IsString() @MaxLength(160)
message?: string | null;
}
@Controller('admin/stores/:id/reminders')
@UseGuards(JwtAuthGuard, AdminGuard)
export class AdminRemindersController {
constructor(private reminders: RemindersService) {}
@Get()
get(@Param('id') id: string) {
return this.reminders.overview(id);
}
@Put()
update(@Param('id') id: string, @Body() dto: ReminderSettingsDto) {
return this.reminders.update(id, { enabled: dto.enabled, days: dto.days, message: dto.message ?? null });
}
}
/** App Pro : réservé aux gérants. */
@Controller('staff/reminders')
@UseGuards(JwtAuthGuard, StaffGuard)
@StaffRoles('MANAGER')
export class StaffRemindersController {
constructor(private reminders: RemindersService) {}
@Get()
get(@CurrentUser() user: JwtPayload) {
if (user.kind !== 'staff') throw new Error('StaffGuard manquant');
return this.reminders.overview(user.storeId);
}
@Put()
update(@CurrentUser() user: JwtPayload, @Body() dto: ReminderSettingsDto) {
if (user.kind !== 'staff') throw new Error('StaffGuard manquant');
return this.reminders.update(user.storeId, { enabled: dto.enabled, days: dto.days, message: dto.message ?? null });
}
}
@Module({
controllers: [AdminRemindersController, StaffRemindersController],
providers: [RemindersService],
})
export class RemindersModule {}

View file

@ -1,40 +1,48 @@
import { Injectable, Logger, NotFoundException, OnApplicationBootstrap, OnApplicationShutdown } from '@nestjs/common'; import { Injectable, Logger, Module, OnApplicationBootstrap, OnApplicationShutdown, OnModuleInit } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service'; import { PrismaService } from '../prisma/prisma.service';
import { parisDate } from '../birthdays/birthdays.service'; import { parisDate } from '../birthdays/birthdays.service';
import { EntitlementsService } from '../billing/entitlements.service'; import { moduleActive, moduleConfig } from '../modules/catalog';
import { ModulesService } from '../modules/modules.service';
import { CardUpdatesService } from '../wallet/card-updates.service'; import { CardUpdatesService } from '../wallet/card-updates.service';
import { CARD_WITH_CONTEXT, DEFAULT_REMINDER, reminderText } from '../wallet/wallet.types'; import { CARD_WITH_CONTEXT, notificationTitle, reminderText } from '../wallet/wallet.types';
export const REMINDER_DAYS = [30, 45, 60, 90];
/** Envois seulement entre 10 h et 19 h (heure de Paris) : pas de notification la nuit. */
const SEND_HOURS = { from: 10, to: 19 };
/** Plafond par magasin et par passage horaire, pour étaler les envois. */ /** Plafond par magasin et par passage horaire, pour étaler les envois. */
const BATCH = 200; const BATCH = 200;
const DAY = 24 * 3600_000; const DAY = 24 * 3600_000;
export interface ReminderSettings { /** Magasins susceptibles d'avoir des modules automatiques actifs. */
enabled: boolean; export const ACTIVE_STORES = {
days: number; where: { status: 'ACTIVE' as const, billingSuspended: false },
message: string | null; select: { id: true, name: true, modules: true, moduleOverrides: true, subscription: { select: { plan: true, status: true } } },
};
/** L'heure de Paris est-elle dans la plage d'envoi du module ? */
export function inSendWindow(config: Record<string, unknown>, now: Date) {
const { hour } = parisDate(now);
return hour >= Number(config.hourFrom) && hour < Number(config.hourTo);
} }
/** /**
* Relance automatique : un client sans crédit depuis N jours reçoit une notification * Module « Relance des inactifs » : un client sans crédit depuis N jours reçoit
* sur sa carte Wallet. Une seule relance par période d'inactivité : il faut qu'il * une notification. Une seule relance par absence : il doit revenir pour pouvoir
* revienne (nouveau crédit) pour pouvoir être relancé à nouveau. * être relancé à nouveau.
*/ */
@Injectable() @Injectable()
export class RemindersService implements OnApplicationBootstrap, OnApplicationShutdown { export class RemindersService implements OnModuleInit, OnApplicationBootstrap, OnApplicationShutdown {
private readonly logger = new Logger(RemindersService.name); private readonly logger = new Logger(RemindersService.name);
private timer?: NodeJS.Timeout; private timer?: NodeJS.Timeout;
private running = false; private running = false;
constructor( constructor(
private prisma: PrismaService, private prisma: PrismaService,
private entitlements: EntitlementsService, private modules: ModulesService,
private cardUpdates: CardUpdatesService, private cardUpdates: CardUpdatesService,
) {} ) {}
onModuleInit() {
this.modules.registerStats('reminders', (storeId) => this.stats(storeId));
}
onApplicationBootstrap() { onApplicationBootstrap() {
this.timer = setInterval(() => void this.tick(), 3600_000); this.timer = setInterval(() => void this.tick(), 3600_000);
setTimeout(() => void this.tick(), 60_000); setTimeout(() => void this.tick(), 60_000);
@ -44,76 +52,43 @@ export class RemindersService implements OnApplicationBootstrap, OnApplicationSh
clearInterval(this.timer); clearInterval(this.timer);
} }
async overview(storeId: string) { async stats(storeId: string) {
const store = await this.prisma.store.findUnique({ where: { id: storeId } }); const store = await this.modules.store(storeId);
if (!store) throw new NotFoundException('Magasin introuvable'); const days = Number(moduleConfig(store, 'reminders').days);
const since = new Date(Date.now() - 30 * DAY); const since = new Date(Date.now() - 30 * DAY);
const [allowed, pending, sentLast30Days, reminded] = await Promise.all([ const [pending, sentLast30Days, reminded] = await Promise.all([
this.entitlements.can(storeId, 'inactiveReminders'), this.candidates(storeId, days, Number.MAX_SAFE_INTEGER),
this.candidates(storeId, store.reminderDays, Number.MAX_SAFE_INTEGER),
this.prisma.loyaltyCard.count({ where: { storeId, reminderSentAt: { gte: since } } }), this.prisma.loyaltyCard.count({ where: { storeId, reminderSentAt: { gte: since } } }),
this.prisma.loyaltyCard.findMany({ this.prisma.loyaltyCard.findMany({ where: { storeId, reminderSentAt: { not: null } }, select: { reminderSentAt: true, lastCreditAt: true } }),
where: { storeId, reminderSentAt: { not: null } },
select: { reminderSentAt: true, lastCreditAt: true },
}),
]); ]);
return { return {
allowed, 'Clients à relancer': pending.length,
settings: { enabled: store.reminderEnabled, days: store.reminderDays, message: store.reminderMessage } as ReminderSettings, 'Relances (30 jours)': sentLast30Days,
defaultMessage: DEFAULT_REMINDER, 'Clients revenus après relance': `${reminded.filter((c) => c.lastCreditAt && c.lastCreditAt > c.reminderSentAt!).length} / ${reminded.length}`,
dayChoices: REMINDER_DAYS,
stats: {
/** Clients actuellement inactifs et pas encore relancés. */
pending: pending.length,
sentLast30Days,
/** Clients relancés revenus depuis (nouveau crédit après la relance). */
cameBack: reminded.filter((c) => c.lastCreditAt && c.lastCreditAt > c.reminderSentAt!).length,
totalReminded: reminded.length,
},
}; };
} }
async update(storeId: string, settings: ReminderSettings) {
if (settings.enabled) await this.entitlements.require(storeId, 'inactiveReminders');
await this.prisma.store.update({
where: { id: storeId },
data: {
reminderEnabled: settings.enabled,
reminderDays: settings.days,
reminderMessage: settings.message?.replace(/\s+/g, ' ').trim() || null,
},
});
return this.overview(storeId);
}
/** Cartes inactives depuis `days` jours et pas encore relancées depuis leur dernière visite. */ /** Cartes inactives depuis `days` jours et pas encore relancées depuis leur dernière visite. */
private async candidates(storeId: string, days: number, take: number) { private async candidates(storeId: string, days: number, take: number) {
const cutoff = new Date(Date.now() - days * DAY); const cutoff = new Date(Date.now() - days * DAY);
const cards = await this.prisma.loyaltyCard.findMany({ const cards = await this.prisma.loyaltyCard.findMany({
where: { where: { storeId, OR: [{ lastCreditAt: { lt: cutoff } }, { lastCreditAt: null, createdAt: { lt: cutoff } }] },
storeId,
OR: [{ lastCreditAt: { lt: cutoff } }, { lastCreditAt: null, createdAt: { lt: cutoff } }],
},
select: { id: true, lastCreditAt: true, createdAt: true, reminderSentAt: true }, select: { id: true, lastCreditAt: true, createdAt: true, reminderSentAt: true },
orderBy: { createdAt: 'asc' }, orderBy: { createdAt: 'asc' },
}); });
return cards.filter((c) => !c.reminderSentAt || c.reminderSentAt < (c.lastCreditAt ?? c.createdAt)).slice(0, take); return cards.filter((c) => !c.reminderSentAt || c.reminderSentAt < (c.lastCreditAt ?? c.createdAt)).slice(0, take);
} }
/** Passage horaire. */ /** Passage horaire : chaque magasin selon sa propre plage d'envoi. */
async tick(now = new Date()) { async tick(now = new Date()) {
if (this.running) return; if (this.running) return;
const { hour } = parisDate(now);
if (hour < SEND_HOURS.from || hour >= SEND_HOURS.to) return;
this.running = true; this.running = true;
try { try {
const stores = await this.prisma.store.findMany({ for (const store of await this.prisma.store.findMany(ACTIVE_STORES)) {
where: { reminderEnabled: true, status: 'ACTIVE', billingSuspended: false }, if (!moduleActive(store, 'reminders')) continue;
select: { id: true, name: true, reminderDays: true }, const config = moduleConfig(store, 'reminders');
}); if (!inSendWindow(config, now)) continue;
for (const store of stores) { const sent = await this.runStore(store.id, Number(config.days));
if (!(await this.entitlements.can(store.id, 'inactiveReminders'))) continue;
const sent = await this.runStore(store);
if (sent) this.logger.log(`Relance : ${sent} client(s) de ${store.name}`); if (sent) this.logger.log(`Relance : ${sent} client(s) de ${store.name}`);
} }
} catch (e) { } catch (e) {
@ -123,9 +98,9 @@ export class RemindersService implements OnApplicationBootstrap, OnApplicationSh
} }
} }
private async runStore(store: { id: string; name: string; reminderDays: number }) { private async runStore(storeId: string, days: number) {
let sent = 0; let sent = 0;
for (const { id } of await this.candidates(store.id, store.reminderDays, BATCH)) { for (const { id } of await this.candidates(storeId, days, BATCH)) {
// reminderSentAt + passUpdatedAt d'abord : l'iPhone qui redemande la carte y trouve le texte de relance. // reminderSentAt + passUpdatedAt d'abord : l'iPhone qui redemande la carte y trouve le texte de relance.
const card = await this.prisma.loyaltyCard.update({ const card = await this.prisma.loyaltyCard.update({
where: { id }, where: { id },
@ -133,7 +108,7 @@ export class RemindersService implements OnApplicationBootstrap, OnApplicationSh
include: CARD_WITH_CONTEXT, include: CARD_WITH_CONTEXT,
}); });
try { try {
await this.cardUpdates.remind(card.id, reminderText(card), store.name); await this.cardUpdates.remind(card.id, reminderText(card), notificationTitle(card.store, 'reminders'));
sent++; sent++;
} catch (e) { } catch (e) {
this.logger.warn(`Relance carte ${card.serial} : ${(e as Error).message}`); this.logger.warn(`Relance carte ${card.serial} : ${(e as Error).message}`);
@ -142,3 +117,6 @@ export class RemindersService implements OnApplicationBootstrap, OnApplicationSh
return sent; return sent;
} }
} }
@Module({ providers: [RemindersService] })
export class RemindersModule {}

View file

@ -1,62 +1,7 @@
import { Body, Controller, Get, Module, Param, Put, Query, Res, UseGuards } from '@nestjs/common'; import { Controller, Get, Module, Param, Query, Res } from '@nestjs/common';
import { Throttle } from '@nestjs/throttler'; import { Throttle } from '@nestjs/throttler';
import { IsBoolean, IsIn, IsOptional, IsString, MaxLength } from 'class-validator';
import type { Response } from 'express'; import type { Response } from 'express';
import { JwtPayload } from '../common/auth.types'; import { ReviewsService } from './reviews.service';
import { AdminGuard, CurrentUser, JwtAuthGuard, StaffGuard, StaffRoles } from '../common/guards';
import { ReviewsService, VISIT_CHOICES } from './reviews.service';
class ReviewSettingsDto {
@IsBoolean()
enabled!: boolean;
@IsOptional() @IsString() @MaxLength(500)
url?: string | null;
@IsIn(VISIT_CHOICES)
afterVisits!: number;
@IsOptional() @IsString() @MaxLength(160)
message?: string | null;
}
const settings = (dto: ReviewSettingsDto) => ({ enabled: dto.enabled, url: dto.url ?? null, afterVisits: dto.afterVisits, message: dto.message ?? null });
@Controller('admin/stores/:id/reviews')
@UseGuards(JwtAuthGuard, AdminGuard)
export class AdminReviewsController {
constructor(private reviews: ReviewsService) {}
@Get()
get(@Param('id') id: string) {
return this.reviews.overview(id);
}
@Put()
update(@Param('id') id: string, @Body() dto: ReviewSettingsDto) {
return this.reviews.update(id, settings(dto));
}
}
/** App Pro : réservé aux gérants. */
@Controller('staff/reviews')
@UseGuards(JwtAuthGuard, StaffGuard)
@StaffRoles('MANAGER')
export class StaffReviewsController {
constructor(private reviews: ReviewsService) {}
@Get()
get(@CurrentUser() user: JwtPayload) {
if (user.kind !== 'staff') throw new Error('StaffGuard manquant');
return this.reviews.overview(user.storeId);
}
@Put()
update(@CurrentUser() user: JwtPayload, @Body() dto: ReviewSettingsDto) {
if (user.kind !== 'staff') throw new Error('StaffGuard manquant');
return this.reviews.update(user.storeId, settings(dto));
}
}
/** Lien au dos de la carte : compte le clic puis redirige vers la fiche Google. */ /** Lien au dos de la carte : compte le clic puis redirige vers la fiche Google. */
@Controller('public/cards/:serial/review') @Controller('public/cards/:serial/review')
@ -72,7 +17,7 @@ export class PublicReviewController {
} }
@Module({ @Module({
controllers: [AdminReviewsController, StaffReviewsController, PublicReviewController], controllers: [PublicReviewController],
providers: [ReviewsService], providers: [ReviewsService],
}) })
export class ReviewsModule {} export class ReviewsModule {}

View file

@ -1,16 +1,13 @@
import { BadRequestException, Injectable, Logger, NotFoundException, OnApplicationBootstrap, OnApplicationShutdown } from '@nestjs/common'; import { BadRequestException, Injectable, Logger, NotFoundException, OnApplicationBootstrap, OnApplicationShutdown, OnModuleInit } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service'; import { PrismaService } from '../prisma/prisma.service';
import { parisDate } from '../birthdays/birthdays.service'; import { moduleActive, moduleConfig } from '../modules/catalog';
import { EntitlementsService } from '../billing/entitlements.service'; import { ModulesService } from '../modules/modules.service';
import { ACTIVE_STORES, inSendWindow } from '../reminders/reminders.service';
import { CardUpdatesService } from '../wallet/card-updates.service'; import { CardUpdatesService } from '../wallet/card-updates.service';
import { CARD_WITH_CONTEXT, DEFAULT_REVIEW, reviewText } from '../wallet/wallet.types'; import { CARD_WITH_CONTEXT, notificationTitle, reviewText } from '../wallet/wallet.types';
/** Envois entre 10 h et 20 h (heure de Paris). */ /** Jamais de demande plus de 3 jours après le passage. */
const SEND_HOURS = { from: 10, to: 20 };
/** La demande part 2 h après le passage (le client est rentré), et jamais plus de 3 jours après. */
const DELAY_MS = 2 * 3600_000;
const MAX_AGE_MS = 3 * 24 * 3600_000; const MAX_AGE_MS = 3 * 24 * 3600_000;
export const VISIT_CHOICES = [1, 2, 3, 5];
/** Liens Google acceptés : « Demander des avis » de la fiche d'établissement, ou lien Maps. */ /** Liens Google acceptés : « Demander des avis » de la fiche d'établissement, ou lien Maps. */
const GOOGLE_HOSTS = ['g.page', 'search.google.com', 'www.google.com', 'google.com', 'maps.app.goo.gl', 'goo.gl', 'www.google.fr', 'google.fr', 'maps.google.com']; const GOOGLE_HOSTS = ['g.page', 'search.google.com', 'www.google.com', 'google.com', 'maps.app.goo.gl', 'goo.gl', 'www.google.fr', 'google.fr', 'maps.google.com'];
@ -30,30 +27,39 @@ export function normalizeReviewUrl(raw: string | null | undefined) {
return url.toString(); return url.toString();
} }
export interface ReviewSettings {
enabled: boolean;
url: string | null;
afterVisits: number;
message: string | null;
}
/** /**
* Collecte d'avis Google : après N passages, le client reçoit (une seule fois) une * Module « Avis Google » : après N passages, le client reçoit (une seule fois)
* notification qui l'invite à laisser un avis ; le lien est au dos de sa carte. * une notification qui l'invite à laisser un avis ; le lien est au dos de sa carte.
* Conforme aux règles Google : pas de récompense contre un avis, pas de tri des clients. * Conforme aux règles Google : pas de récompense contre un avis, pas de tri des clients.
*/ */
@Injectable() @Injectable()
export class ReviewsService implements OnApplicationBootstrap, OnApplicationShutdown { export class ReviewsService implements OnModuleInit, OnApplicationBootstrap, OnApplicationShutdown {
private readonly logger = new Logger(ReviewsService.name); private readonly logger = new Logger(ReviewsService.name);
private timer?: NodeJS.Timeout; private timer?: NodeJS.Timeout;
private running = false; private running = false;
constructor( constructor(
private prisma: PrismaService, private prisma: PrismaService,
private entitlements: EntitlementsService, private modules: ModulesService,
private cardUpdates: CardUpdatesService, private cardUpdates: CardUpdatesService,
) {} ) {}
onModuleInit() {
this.modules.registerStats('reviews', async (storeId) => {
const [asked, clicked] = await Promise.all([
this.prisma.loyaltyCard.count({ where: { storeId, reviewAskedAt: { not: null } } }),
this.prisma.loyaltyCard.count({ where: { storeId, reviewClickedAt: { not: null } } }),
]);
return { 'Demandes envoyées': asked, 'Clics vers Google': clicked };
});
// Lien vérifié à l'enregistrement, et obligatoire pour activer le module.
this.modules.registerHook('reviews', async (_storeId, values) => {
const url = normalizeReviewUrl(String(values.url ?? ''));
if (values.enabled && !url) throw new BadRequestException('Renseignez le lien de votre fiche Google pour activer le module Avis Google.');
return { url: url ?? '' };
});
}
onApplicationBootstrap() { onApplicationBootstrap() {
this.timer = setInterval(() => void this.tick(), 3600_000); this.timer = setInterval(() => void this.tick(), 3600_000);
setTimeout(() => void this.tick(), 120_000); setTimeout(() => void this.tick(), 120_000);
@ -63,65 +69,28 @@ export class ReviewsService implements OnApplicationBootstrap, OnApplicationShut
clearInterval(this.timer); clearInterval(this.timer);
} }
async overview(storeId: string) {
const store = await this.prisma.store.findUnique({ where: { id: storeId } });
if (!store) throw new NotFoundException('Magasin introuvable');
const [allowed, asked, clicked] = await Promise.all([
this.entitlements.can(storeId, 'googleReview'),
this.prisma.loyaltyCard.count({ where: { storeId, reviewAskedAt: { not: null } } }),
this.prisma.loyaltyCard.count({ where: { storeId, reviewClickedAt: { not: null } } }),
]);
return {
allowed,
settings: { enabled: store.reviewEnabled, url: store.googleReviewUrl, afterVisits: store.reviewAfterVisits, message: store.reviewMessage } as ReviewSettings,
defaultMessage: DEFAULT_REVIEW,
visitChoices: VISIT_CHOICES,
stats: { asked, clicked },
};
}
async update(storeId: string, settings: ReviewSettings) {
const url = normalizeReviewUrl(settings.url);
if (settings.enabled) {
await this.entitlements.require(storeId, 'googleReview');
if (!url) throw new BadRequestException('Renseignez le lien de votre fiche Google pour activer la collecte d’avis.');
}
await this.prisma.store.update({
where: { id: storeId },
data: {
reviewEnabled: settings.enabled,
googleReviewUrl: url,
reviewAfterVisits: settings.afterVisits,
reviewMessage: settings.message?.replace(/\s+/g, ' ').trim() || null,
},
});
// Le lien apparaît ou disparaît au dos des cartes.
this.cardUpdates.notifyStore(storeId);
return this.overview(storeId);
}
/** Clic du client : on le note, puis direction la fiche Google. */ /** Clic du client : on le note, puis direction la fiche Google. */
async click(serial: string, key: string | undefined) { async click(serial: string, key: string | undefined) {
const card = await this.prisma.loyaltyCard.findUnique({ where: { serial }, include: { store: true } }); const card = await this.prisma.loyaltyCard.findUnique({
if (!card || !key || card.accessKey !== key || !card.store.googleReviewUrl) throw new NotFoundException(); where: { serial },
include: { store: { select: { modules: true, moduleOverrides: true, subscription: { select: { plan: true, status: true } } } } },
});
const url = card ? String(moduleConfig(card.store, 'reviews').url) : '';
if (!card || !key || card.accessKey !== key || !url) throw new NotFoundException();
if (!card.reviewClickedAt) await this.prisma.loyaltyCard.update({ where: { id: card.id }, data: { reviewClickedAt: new Date() } }); if (!card.reviewClickedAt) await this.prisma.loyaltyCard.update({ where: { id: card.id }, data: { reviewClickedAt: new Date() } });
return card.store.googleReviewUrl; return url;
} }
/** Passage horaire. */ /** Passage horaire : chaque magasin selon sa propre plage d'envoi. */
async tick(now = new Date()) { async tick(now = new Date()) {
if (this.running) return; if (this.running) return;
const { hour } = parisDate(now);
if (hour < SEND_HOURS.from || hour >= SEND_HOURS.to) return;
this.running = true; this.running = true;
try { try {
const stores = await this.prisma.store.findMany({ for (const store of await this.prisma.store.findMany(ACTIVE_STORES)) {
where: { reviewEnabled: true, googleReviewUrl: { not: null }, status: 'ACTIVE', billingSuspended: false }, if (!moduleActive(store, 'reviews')) continue;
select: { id: true, name: true, reviewAfterVisits: true }, const config = moduleConfig(store, 'reviews');
}); if (!config.url || !inSendWindow(config, now)) continue;
for (const store of stores) { const sent = await this.runStore(store.id, Number(config.afterVisits), Number(config.delayHours), now);
if (!(await this.entitlements.can(store.id, 'googleReview'))) continue;
const sent = await this.runStore(store, now);
if (sent) this.logger.log(`Avis Google : ${sent} demande(s) pour ${store.name}`); if (sent) this.logger.log(`Avis Google : ${sent} demande(s) pour ${store.name}`);
} }
} catch (e) { } catch (e) {
@ -131,12 +100,12 @@ export class ReviewsService implements OnApplicationBootstrap, OnApplicationShut
} }
} }
private async runStore(store: { id: string; name: string; reviewAfterVisits: number }, now: Date) { private async runStore(storeId: string, afterVisits: number, delayHours: number, now: Date) {
const recent = await this.prisma.loyaltyCard.findMany({ const recent = await this.prisma.loyaltyCard.findMany({
where: { where: {
storeId: store.id, storeId,
reviewAskedAt: null, reviewAskedAt: null,
lastCreditAt: { lte: new Date(now.getTime() - DELAY_MS), gte: new Date(now.getTime() - MAX_AGE_MS) }, lastCreditAt: { lte: new Date(now.getTime() - delayHours * 3600_000), gte: new Date(now.getTime() - MAX_AGE_MS) },
}, },
select: { id: true }, select: { id: true },
}); });
@ -147,7 +116,7 @@ export class ReviewsService implements OnApplicationBootstrap, OnApplicationShut
_count: { _all: true }, _count: { _all: true },
}); });
let sent = 0; let sent = 0;
for (const v of visits.filter((x) => x._count._all >= store.reviewAfterVisits)) { for (const v of visits.filter((x) => x._count._all >= afterVisits)) {
const { count } = await this.prisma.loyaltyCard.updateMany({ const { count } = await this.prisma.loyaltyCard.updateMany({
where: { id: v.cardId, reviewAskedAt: null }, where: { id: v.cardId, reviewAskedAt: null },
data: { reviewAskedAt: now, passUpdatedAt: now }, data: { reviewAskedAt: now, passUpdatedAt: now },
@ -155,7 +124,7 @@ export class ReviewsService implements OnApplicationBootstrap, OnApplicationShut
if (!count) continue; if (!count) continue;
const card = await this.prisma.loyaltyCard.findUniqueOrThrow({ where: { id: v.cardId }, include: CARD_WITH_CONTEXT }); const card = await this.prisma.loyaltyCard.findUniqueOrThrow({ where: { id: v.cardId }, include: CARD_WITH_CONTEXT });
try { try {
await this.cardUpdates.remind(card.id, reviewText(card), store.name); await this.cardUpdates.remind(card.id, reviewText(card), notificationTitle(card.store, 'reviews'));
sent++; sent++;
} catch (e) { } catch (e) {
this.logger.warn(`Avis carte ${card.serial} : ${(e as Error).message}`); this.logger.warn(`Avis carte ${card.serial} : ${(e as Error).message}`);

View file

@ -1,9 +1,9 @@
import { Body, Controller, Get, HttpCode, Module, Param, ParseIntPipe, Post, Query, Res, UseGuards } from '@nestjs/common'; import { Body, Controller, ForbiddenException, Get, HttpCode, Module, Param, ParseIntPipe, Post, Query, Res, UseGuards } from '@nestjs/common';
import { ConfigService } from '@nestjs/config'; import { ConfigService } from '@nestjs/config';
import { Throttle } from '@nestjs/throttler'; import { Throttle } from '@nestjs/throttler';
import { IsIn } from 'class-validator'; import { IsIn } from 'class-validator';
import type { Response } from 'express'; import type { Response } from 'express';
import { EntitlementsService } from '../billing/entitlements.service'; import { ModulesService } from '../modules/modules.service';
import { JwtPayload } from '../common/auth.types'; import { JwtPayload } from '../common/auth.types';
import { AdminGuard, CurrentUser, JwtAuthGuard, StaffGuard, StaffRoles } from '../common/guards'; import { AdminGuard, CurrentUser, JwtAuthGuard, StaffGuard, StaffRoles } from '../common/guards';
import { emailLayout, esc } from '../mail/email-layout'; import { emailLayout, esc } from '../mail/email-layout';
@ -34,11 +34,11 @@ class ExportDto {
@Controller('admin/stores/:id') @Controller('admin/stores/:id')
@UseGuards(JwtAuthGuard, AdminGuard) @UseGuards(JwtAuthGuard, AdminGuard)
export class AdminStatsController { export class AdminStatsController {
constructor(private stats: StatsService, private exports: ExportService, private entitlements: EntitlementsService) {} constructor(private stats: StatsService, private exports: ExportService, private modules: ModulesService) {}
@Get('stats') @Get('stats')
async get(@Param('id') id: string, @Query('days', new ParseIntPipe({ optional: true })) days = 30) { async get(@Param('id') id: string, @Query('days', new ParseIntPipe({ optional: true })) days = 30) {
const [data, allowed] = await Promise.all([this.stats.compute(id, period(days)), this.entitlements.can(id, 'advancedStats')]); const [data, allowed] = await Promise.all([this.stats.compute(id, period(days)), this.modules.active(id, 'stats')]);
return { ...data, allowed }; return { ...data, allowed };
} }
@ -61,7 +61,7 @@ export class StaffStatsController {
constructor( constructor(
private stats: StatsService, private stats: StatsService,
private exports: ExportService, private exports: ExportService,
private entitlements: EntitlementsService, private modules: ModulesService,
private prisma: PrismaService, private prisma: PrismaService,
private mail: MailService, private mail: MailService,
private config: ConfigService, private config: ConfigService,
@ -70,7 +70,7 @@ export class StaffStatsController {
@Get('stats') @Get('stats')
async get(@CurrentUser() user: JwtPayload, @Query('days', new ParseIntPipe({ optional: true })) days = 30) { async get(@CurrentUser() user: JwtPayload, @Query('days', new ParseIntPipe({ optional: true })) days = 30) {
if (user.kind !== 'staff') throw new Error('StaffGuard manquant'); if (user.kind !== 'staff') throw new Error('StaffGuard manquant');
await this.entitlements.require(user.storeId, 'advancedStats'); await this.modules.require(user.storeId, 'stats');
return this.stats.compute(user.storeId, period(days)); return this.stats.compute(user.storeId, period(days));
} }
@ -80,7 +80,8 @@ export class StaffStatsController {
@Throttle({ default: { limit: 5, ttl: 10 * 60_000 } }) @Throttle({ default: { limit: 5, ttl: 10 * 60_000 } })
async export(@CurrentUser() user: JwtPayload, @Body() dto: ExportDto) { async export(@CurrentUser() user: JwtPayload, @Body() dto: ExportDto) {
if (user.kind !== 'staff') throw new Error('StaffGuard manquant'); if (user.kind !== 'staff') throw new Error('StaffGuard manquant');
await this.entitlements.require(user.storeId, 'csvExport'); const config = await this.modules.require(user.storeId, 'stats');
if (!config.csvExport) throw new ForbiddenException({ statusCode: 403, code: 'MODULE_DISABLED', message: 'L’export CSV est désactivé dans les réglages du module Statistiques.' });
const staff = await this.prisma.staffUser.findUniqueOrThrow({ where: { id: user.sub }, include: { store: { select: { name: true } } } }); const staff = await this.prisma.staffUser.findUniqueOrThrow({ where: { id: user.sub }, include: { store: { select: { name: true } } } });
const file = dto.kind === 'customers' ? await this.exports.customers(user.storeId) : await this.exports.transactions(user.storeId, dto.days); const file = dto.kind === 'customers' ? await this.exports.customers(user.storeId) : await this.exports.transactions(user.storeId, dto.days);
const what = dto.kind === 'customers' ? 'Fichier clients' : `Opérations des ${dto.days} derniers jours`; const what = dto.kind === 'customers' ? 'Fichier clients' : `Opérations des ${dto.days} derniers jours`;

View file

@ -5,7 +5,24 @@ import { join } from 'path';
import { Jimp } from 'jimp'; import { Jimp } from 'jimp';
import { PKPass } from 'passkit-generator'; import { PKPass } from 'passkit-generator';
import { UPLOADS_DIR } from '../card-design/card-design.service'; import { UPLOADS_DIR } from '../card-design/card-design.service';
import { CardWithContext, newsText, nextRewardText, referralLink, referralOffered, reviewLink, reviewOffered, rewardsText, unitLabel } from './wallet.types'; import { moduleActive, moduleConfig } from '../modules/catalog';
/** Les libellés des liens sont saisis par le commerçant : échappés dans le HTML d'Apple. */
const escapeXml = (s: string) => s.replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]!);
import {
CardWithContext,
newsLabels,
newsText,
nextRewardText,
referralLink,
referralLinkLabel,
referralOffered,
reviewLink,
reviewLinkLabel,
reviewOffered,
rewardsText,
unitLabel,
} from './wallet.types';
type Certificates = { wwdr: Buffer; signerCert: Buffer; signerKey: Buffer; signerKeyPassphrase?: string }; type Certificates = { wwdr: Buffer; signerCert: Buffer; signerKey: Buffer; signerKeyPassphrase?: string };
@ -69,7 +86,7 @@ export class ApplePassService {
}), }),
backFields: [ backFields: [
// Toujours présent : quand sa valeur change (nouvelle campagne), l'iPhone affiche le message sur l'écran verrouillé. // Toujours présent : quand sa valeur change (nouvelle campagne), l'iPhone affiche le message sur l'écran verrouillé.
{ key: 'news', label: 'Actualité', value: newsText(card) ?? 'Aucune actualité pour le moment.', changeMessage: '%@' }, { key: 'news', label: newsLabels(card.store).label, value: newsText(card) ?? newsLabels(card.store).empty, changeMessage: '%@' },
{ key: 'rewards', label: 'Récompenses', value: rewardsText(card) }, { key: 'rewards', label: 'Récompenses', value: rewardsText(card) },
{ {
key: 'store', key: 'store',
@ -82,12 +99,12 @@ export class ApplePassService {
value: `${this.config.get('webUrl')}/carte/${card.serial}?k=${card.accessKey}`, value: `${this.config.get('webUrl')}/carte/${card.serial}?k=${card.accessKey}`,
}, },
...(reviewOffered(card.store) ...(reviewOffered(card.store)
? [{ key: 'review', label: 'Votre avis', value: reviewLink(this.config.get('webUrl')!, card), attributedValue: `<a href="${reviewLink(this.config.get('webUrl')!, card)}">Laisser un avis Google</a>` }] ? [{ key: 'review', label: 'Votre avis', value: reviewLink(this.config.get('webUrl')!, card), attributedValue: `<a href="${reviewLink(this.config.get('webUrl')!, card)}">${escapeXml(reviewLinkLabel(card.store))}</a>` }]
: []), : []),
...(referralOffered(card.store) && referralLink(this.config.get('webUrl')!, card) ...(referralOffered(card.store) && referralLink(this.config.get('webUrl')!, card)
? [{ key: 'referral', label: 'Parrainez vos proches', value: referralLink(this.config.get('webUrl')!, card)!, attributedValue: `<a href="${referralLink(this.config.get('webUrl')!, card)}">Mon lien de parrainage</a>` }] ? [{ key: 'referral', label: String(moduleConfig(card.store, 'referral').sectionTitle), value: referralLink(this.config.get('webUrl')!, card)!, attributedValue: `<a href="${referralLink(this.config.get('webUrl')!, card)}">${escapeXml(referralLinkLabel(card.store))}</a>` }]
: []), : []),
{ key: 'powered', label: '', value: 'Propulsé par MonEspacePro' }, ...(moduleActive(card.store, 'whiteLabel') ? [] : [{ key: 'powered', label: '', value: 'Propulsé par MonEspacePro' }]),
], ],
}, },
}; };

View file

@ -2,7 +2,7 @@ import { Injectable, Logger, ServiceUnavailableException } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'; import { ConfigService } from '@nestjs/config';
import { readFileSync } from 'fs'; import { readFileSync } from 'fs';
import { importPKCS8, SignJWT } from 'jose'; import { importPKCS8, SignJWT } from 'jose';
import { CardWithContext, nextRewardText, referralLink, referralOffered, reviewLink, reviewOffered, rewardsText, unitLabel } from './wallet.types'; import { CardWithContext, nextRewardText, referralLink, referralLinkLabel, referralOffered, reviewLink, reviewLinkLabel, reviewOffered, rewardsText, unitLabel } from './wallet.types';
type ServiceAccount = { client_email: string; private_key: string }; type ServiceAccount = { client_email: string; private_key: string };
type StoreForClass = CardWithContext['store']; type StoreForClass = CardWithContext['store'];
@ -142,8 +142,8 @@ export class GoogleWalletService {
linksModuleData: { linksModuleData: {
uris: [ uris: [
{ id: 'manage', uri: `${webUrl}/carte/${card.serial}?k=${card.accessKey}`, description: 'Ma carte' }, { id: 'manage', uri: `${webUrl}/carte/${card.serial}?k=${card.accessKey}`, description: 'Ma carte' },
...(referralOffered(card.store) && referralLink(webUrl, card) ? [{ id: 'referral', uri: referralLink(webUrl, card)!, description: 'Parrainer un proche' }] : []), ...(referralOffered(card.store) && referralLink(webUrl, card) ? [{ id: 'referral', uri: referralLink(webUrl, card)!, description: referralLinkLabel(card.store) }] : []),
...(reviewOffered(card.store) ? [{ id: 'review', uri: reviewLink(webUrl, card), description: 'Laisser un avis Google' }] : []), ...(reviewOffered(card.store) ? [{ id: 'review', uri: reviewLink(webUrl, card), description: reviewLinkLabel(card.store) }] : []),
], ],
}, },
}; };

View file

@ -1,5 +1,5 @@
import { Prisma } from '@prisma/client'; import { Prisma } from '@prisma/client';
import { hasFeature } from '../billing/plans'; import { fill, ModuleId, moduleActive, moduleConfig, quantity } from '../modules/catalog';
/** Tout ce qu'il faut pour dessiner une carte, chargé en une requête. */ /** Tout ce qu'il faut pour dessiner une carte, chargé en une requête. */
export const CARD_WITH_CONTEXT = { export const CARD_WITH_CONTEXT = {
@ -44,36 +44,41 @@ export function rewardsText(card: CardWithContext) {
} }
export const DEFAULT_REMINDER = 'Vous nous manquez, {prenom} ! Votre solde de {solde} vous attend en magasin.'; const stampMode = (store: CardWithContext['store']) => store.cardDesign?.pointsMode === 'STAMP';
/** Variables communes à tous les messages : {prenom}, {magasin}, {solde}, {programme}. */
export function messageVars(card: CardWithContext) {
return {
prenom: card.customer.firstName,
magasin: card.store.name,
programme: card.store.cardDesign?.programName ?? card.store.name,
solde: quantity(card.balance, stampMode(card.store)),
};
}
/** Titre des notifications Google d'un module (« {magasin} » par défaut). */
export function notificationTitle(store: CardWithContext['store'], id: ModuleId) {
const t = moduleConfig(store, id).title;
return fill(typeof t === 'string' ? t : '{magasin}', { magasin: store.name }) || store.name;
}
/** Texte de relance personnalisé pour ce client. */ /** Texte de relance personnalisé pour ce client. */
export function reminderText(card: CardWithContext) { export function reminderText(card: CardWithContext) {
const unit = card.store.cardDesign?.pointsMode === 'STAMP' ? 'tampon' : 'point'; return fill(String(moduleConfig(card.store, 'reminders').message), messageVars(card));
const solde = `${card.balance} ${unit}${card.balance > 1 ? 's' : ''}`;
return (card.store.reminderMessage || DEFAULT_REMINDER)
.replaceAll('{prenom}', card.customer.firstName)
.replaceAll('{solde}', solde);
} }
export const DEFAULT_BIRTHDAY = 'Joyeux anniversaire, {prenom} ! {cadeau}'; /** Annonce du cadeau d'anniversaire (« 3 tampons offerts sur votre carte. »), vide si message seulement. */
export function birthdayGiftText(store: CardWithContext['store']) {
/** « 5 tampons offerts sur votre carte. » (ou rien si le magasin n'offre pas de points). */ const c = moduleConfig(store, 'birthday');
export function birthdayGiftText(card: CardWithContext) { const n = Number(c.points);
const n = card.store.birthdayPoints; return n > 0 ? fill(String(c.giftText), { quantite: quantity(n, stampMode(store)) }) : '';
if (n <= 0) return '';
const unit = card.store.cardDesign?.pointsMode === 'STAMP' ? 'tampon' : 'point';
return `${n} ${unit}${n > 1 ? 's' : ''} offert${n > 1 ? 's' : ''} sur votre carte.`;
} }
export function birthdayText(card: CardWithContext) { export function birthdayText(card: CardWithContext) {
return (card.store.birthdayMessage || DEFAULT_BIRTHDAY) return fill(String(moduleConfig(card.store, 'birthday').message), { ...messageVars(card), cadeau: birthdayGiftText(card.store) });
.replaceAll('{prenom}', card.customer.firstName)
.replaceAll('{cadeau}', birthdayGiftText(card))
.replace(/\s+/g, ' ')
.trim();
} }
/** Rubrique « Actualité » : le message le plus récent entre campagne, relance et anniversaire. */ /** Rubrique « Actualité » : le message le plus récent entre campagne, relance, anniversaire, avis et parrainage. */
export function newsText(card: CardWithContext) { export function newsText(card: CardWithContext) {
const campaign = card.store.campaigns[0]; const campaign = card.store.campaigns[0];
const items: [Date | null | undefined, () => string][] = [ const items: [Date | null | undefined, () => string][] = [
@ -87,20 +92,23 @@ export function newsText(card: CardWithContext) {
return latest ? latest[1]() : null; return latest ? latest[1]() : null;
} }
export const DEFAULT_REVIEW = 'Merci pour vos visites, {prenom} ! Votre avis compte beaucoup pour nous : laissez-nous un avis Google en une minute.'; /** Titre et texte vide de la rubrique « Actualité » (module Campagnes). */
export function newsLabels(store: CardWithContext['store']) {
const c = moduleConfig(store, 'campaigns');
return { label: String(c.newsLabel), empty: String(c.emptyNews) };
}
/** Collecte d'avis active pour ce magasin (formule Pro + lien renseigné). */ /** Collecte d'avis active pour ce magasin (module disponible, activé, lien renseigné). */
export function reviewOffered(store: CardWithContext['store']) { export function reviewOffered(store: CardWithContext['store']) {
return ( return moduleActive(store, 'reviews') && !!moduleConfig(store, 'reviews').url;
store.reviewEnabled &&
!!store.googleReviewUrl &&
store.subscription?.status === 'ACTIVE' &&
hasFeature(store.subscription.plan, 'googleReview')
);
} }
export function reviewText(card: CardWithContext) { export function reviewText(card: CardWithContext) {
return (card.store.reviewMessage || DEFAULT_REVIEW).replaceAll('{prenom}', card.customer.firstName); return fill(String(moduleConfig(card.store, 'reviews').message), messageVars(card));
}
export function reviewLinkLabel(store: CardWithContext['store']) {
return String(moduleConfig(store, 'reviews').linkLabel);
} }
/** Lien suivi (compte les clics) qui redirige vers la fiche Google. */ /** Lien suivi (compte les clics) qui redirige vers la fiche Google. */
@ -108,9 +116,13 @@ export function reviewLink(webUrl: string, card: CardWithContext) {
return `${webUrl}/api/public/cards/${card.serial}/review?k=${card.accessKey}`; return `${webUrl}/api/public/cards/${card.serial}/review?k=${card.accessKey}`;
} }
/** Parrainage actif pour ce magasin (formule Pro). */ /** Parrainage actif pour ce magasin. */
export function referralOffered(store: CardWithContext['store']) { export function referralOffered(store: CardWithContext['store']) {
return store.referralEnabled && store.subscription?.status === 'ACTIVE' && hasFeature(store.subscription.plan, 'referral'); return moduleActive(store, 'referral');
}
export function referralLinkLabel(store: CardWithContext['store']) {
return String(moduleConfig(store, 'referral').linkLabel);
} }
/** Lien d'inscription à partager par le client (null tant que son code n'est pas créé). */ /** Lien d'inscription à partager par le client (null tant que son code n'est pas créé). */

View file

@ -49,12 +49,9 @@ function Navigator() {
<Stack.Screen name="done" options={{ headerShown: false, gestureEnabled: false }} /> <Stack.Screen name="done" options={{ headerShown: false, gestureEnabled: false }} />
<Stack.Screen name="history" options={{ title: 'Historique' }} /> <Stack.Screen name="history" options={{ title: 'Historique' }} />
<Stack.Screen name="campaigns" options={{ title: 'Campagnes' }} /> <Stack.Screen name="campaigns" options={{ title: 'Campagnes' }} />
<Stack.Screen name="reminders" options={{ title: 'Relance des inactifs' }} />
<Stack.Screen name="birthday" options={{ title: "Offre d'anniversaire" }} />
<Stack.Screen name="reviews" options={{ title: 'Avis Google' }} />
<Stack.Screen name="referral" options={{ title: 'Parrainage' }} />
<Stack.Screen name="stats" options={{ title: 'Statistiques' }} /> <Stack.Screen name="stats" options={{ title: 'Statistiques' }} />
<Stack.Screen name="loyalty" options={{ title: 'Fidélisation' }} /> <Stack.Screen name="loyalty" options={{ title: 'Modules' }} />
<Stack.Screen name="module/[id]" options={{ title: 'Module' }} />
</Stack.Protected> </Stack.Protected>
</Stack> </Stack>
); );

View file

@ -1,120 +0,0 @@
import { useCallback, useState } from 'react';
import { Pressable, ScrollView, Switch, TextInput, View } from 'react-native';
import { useFocusEffect } from 'expo-router';
import { api } from '../src/api';
import { describe } from '../src/errors';
import { useStore } from '../src/session';
import { Banner, Button, Card, T, unit } from '../src/ui';
import { font, useColors } from '../src/theme';
interface Birthday {
allowed: boolean;
settings: { enabled: boolean; points: number; message: string | null };
defaultMessage: string;
maxPoints: number;
stats: { cards: number; known: number; giftedThisYear: number };
}
/** Offre d'anniversaire (gérants, formule Pro). */
export default function BirthdayScreen() {
const c = useColors();
const store = useStore();
const [data, setData] = useState<Birthday | null>(null);
const [enabled, setEnabled] = useState(false);
const [points, setPoints] = useState(0);
const [message, setMessage] = useState('');
const [error, setError] = useState<string | null>(null);
const [saved, setSaved] = useState(false);
const [busy, setBusy] = useState(false);
const apply = (d: Birthday) => {
setData(d);
setEnabled(d.settings.enabled);
setPoints(d.settings.points);
setMessage(d.settings.message ?? '');
};
useFocusEffect(
useCallback(() => {
api.get<Birthday>('/api/staff/birthday').then(apply).catch((e) => setError(describe(e).detail));
}, []),
);
async function save() {
setBusy(true);
setError(null);
setSaved(false);
try {
apply(await api.put<Birthday>('/api/staff/birthday', { enabled, points, message: message.trim() || null }));
setSaved(true);
} catch (e) {
setError(describe(e).detail);
} finally {
setBusy(false);
}
}
if (!data) return <View style={{ padding: 20 }}>{error ? <Banner tone="error">{error}</Banner> : <T v="muted">Chargement…</T>}</View>;
const step = (d: number) => setPoints((p) => Math.max(0, Math.min(data.maxPoints, p + d)));
const stepper = (label: string, d: number) => (
<Pressable
accessibilityRole="button"
accessibilityLabel={d > 0 ? 'Plus' : 'Moins'}
onPress={() => step(d)}
style={{ width: 48, height: 48, borderRadius: 24, borderWidth: 1, borderColor: c.border, backgroundColor: c.surface, alignItems: 'center', justifyContent: 'center' }}
>
<T style={{ fontFamily: font.bold, fontSize: 22 }}>{label}</T>
</Pressable>
);
return (
<ScrollView contentContainerStyle={{ padding: 20, gap: 16 }} keyboardShouldPersistTaps="handled">
{error && <Banner tone="error">{error}</Banner>}
{saved && <Banner tone="ok">Réglages enregistrés.</Banner>}
{!data.allowed && <Banner tone="warn">L'offre d'anniversaire est incluse dans la formule Pro. Contactez MonEspacePro pour changer de formule.</Banner>}
<T v="muted">
Vos clients indiquent leur anniversaire à l'inscription ou sur la page de leur carte. Le jour J, ils reçoivent une notification et votre cadeau. Un cadeau par an.
</T>
<Card style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', padding: 16 }}>
<T v="label">Offre d'anniversaire</T>
<Switch value={enabled} onValueChange={setEnabled} disabled={!data.allowed && !enabled} accessibilityLabel="Offre d'anniversaire" />
</Card>
<T v="label">Cadeau</T>
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 16 }}>
{stepper('−', -1)}
<T style={{ fontFamily: font.extrabold, fontSize: 26, minWidth: 40, textAlign: 'center' }}>{points}</T>
{stepper('+', 1)}
<T v="muted" style={{ flex: 1 }}>{points === 0 ? 'message seulement' : `${unit(store.design.pointsMode, points)} offert${points > 1 ? 's' : ''}`}</T>
</View>
<T v="label">Message</T>
<TextInput
value={message}
onChangeText={setMessage}
multiline
maxLength={160}
placeholder={data.defaultMessage}
placeholderTextColor={c.text3}
accessibilityLabel="Message d'anniversaire"
style={{ minHeight: 90, borderWidth: 1, borderColor: c.border, borderRadius: 14, padding: 14, backgroundColor: c.surface, color: c.text, fontFamily: font.regular, fontSize: 16, textAlignVertical: 'top' }}
/>
<T v="muted" style={{ fontSize: 13 }}>Vide = texte par défaut. {'{prenom}'} et {'{cadeau}'} sont remplacés automatiquement.</T>
<Button label="Enregistrer" onPress={save} loading={busy} />
<View style={{ flexDirection: 'row', gap: 12 }}>
{[
[`${data.stats.known}/${data.stats.cards}`, 'anniversaires connus'],
[data.stats.giftedThisYear, 'cadeaux (12 mois)'],
].map(([n, l]) => (
<Card key={String(l)} style={{ flex: 1, padding: 14, gap: 2 }}>
<T style={{ fontFamily: font.extrabold, fontSize: 22 }}>{n}</T>
<T v="muted" style={{ fontSize: 13 }}>{l}</T>
</Card>
))}
</View>
</ScrollView>
);
}

View file

@ -9,12 +9,13 @@ import { font, useColors } from '../src/theme';
interface Overview { interface Overview {
allowed: boolean; allowed: boolean;
maxLength: number;
minIntervalHours: number;
audience: { cards: number; appleDevices: number }; audience: { cards: number; appleDevices: number };
nextAllowedAt: string | null; nextAllowedAt: string | null;
items: { id: string; message: string; sentByName: string; cards: number; createdAt: string }[]; items: { id: string; message: string; sentByName: string; cards: number; createdAt: string }[];
} }
const MAX = 160;
const when = (d: string) => const when = (d: string) =>
new Date(d).toLocaleString('fr-FR', { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' }); new Date(d).toLocaleString('fr-FR', { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' });
@ -70,7 +71,7 @@ export default function Campaigns() {
<ScrollView contentContainerStyle={{ padding: 20, gap: 16 }} keyboardShouldPersistTaps="handled"> <ScrollView contentContainerStyle={{ padding: 20, gap: 16 }} keyboardShouldPersistTaps="handled">
{error && <Banner tone="error">{error}</Banner>} {error && <Banner tone="error">{error}</Banner>}
{sent && <Banner tone="ok">Campagne envoyée. Les cartes de vos clients se mettent à jour dans les minutes qui suivent.</Banner>} {sent && <Banner tone="ok">Campagne envoyée. Les cartes de vos clients se mettent à jour dans les minutes qui suivent.</Banner>}
{data && !data.allowed && <Banner tone="warn">Les campagnes sont incluses dans la formule Pro. Contactez MonEspacePro pour changer de formule.</Banner>} {data && !data.allowed && <Banner tone="warn">Le module Campagnes n'est pas actif : activez-le dans Modules, ou contactez MonEspacePro s'il n'est pas inclus dans votre formule.</Banner>}
<T v="muted"> <T v="muted">
Votre message apparaît en notification sur le téléphone de vos clients et reste visible sur leur carte. Votre message apparaît en notification sur le téléphone de vos clients et reste visible sur leur carte.
@ -81,7 +82,7 @@ export default function Campaigns() {
onChangeText={setMessage} onChangeText={setMessage}
editable={!blocked && !busy} editable={!blocked && !busy}
multiline multiline
maxLength={MAX} maxLength={data?.maxLength ?? 160}
placeholder="Ex. : -20 % sur les viennoiseries ce samedi !" placeholder="Ex. : -20 % sur les viennoiseries ce samedi !"
placeholderTextColor={c.text3} placeholderTextColor={c.text3}
accessibilityLabel="Message de la campagne" accessibilityLabel="Message de la campagne"
@ -99,7 +100,7 @@ export default function Campaigns() {
opacity: blocked ? 0.6 : 1, opacity: blocked ? 0.6 : 1,
}} }}
/> />
<T v="muted" style={{ fontSize: 13 }}>{text.length} / {MAX} · 1 campagne par jour maximum</T> <T v="muted" style={{ fontSize: 13 }}>{text.length} / {data?.maxLength ?? 160} · une campagne toutes les {data?.minIntervalHours ?? 24} h maximum</T>
{data?.nextAllowedAt && <Banner tone="warn">Prochain envoi possible le {when(data.nextAllowedAt)}.</Banner>} {data?.nextAllowedAt && <Banner tone="warn">Prochain envoi possible le {when(data.nextAllowedAt)}.</Banner>}
<Button label="Envoyer la campagne" onPress={send} disabled={blocked || text.length < 5} loading={busy} /> <Button label="Envoyer la campagne" onPress={send} disabled={blocked || text.length < 5} loading={busy} />

View file

@ -112,7 +112,7 @@ export default function Home() {
</View> </View>
<View style={{ flex: 1 }} /> <View style={{ flex: 1 }} />
{isManager && <Button label="Fidélisation" variant="secondary" onPress={() => router.push('/loyalty')} />} {isManager && <Button label="Modules" variant="secondary" onPress={() => router.push('/loyalty')} />}
{isManager && <Button label="Statistiques" variant="secondary" onPress={() => router.push('/stats')} />} {isManager && <Button label="Statistiques" variant="secondary" onPress={() => router.push('/stats')} />}
<Button label="Historique des opérations" variant="secondary" onPress={() => router.push('/history')} /> <Button label="Historique des opérations" variant="secondary" onPress={() => router.push('/history')} />
</ScrollView> </ScrollView>

View file

@ -1,17 +1,43 @@
import { ScrollView } from 'react-native'; import { useCallback, useState } from 'react';
import { router } from 'expo-router'; import { Pressable, ScrollView, View } from 'react-native';
import { Button, T } from '../src/ui'; import { router, useFocusEffect } from 'expo-router';
import { api } from '../src/api';
import { describe } from '../src/errors';
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. */
export default function Modules() {
const c = useColors();
const [list, setList] = useState<ModuleInfo[] | null>(null);
const [error, setError] = useState<string | null>(null);
useFocusEffect(
useCallback(() => {
api.get<ModuleInfo[]>('/api/staff/modules').then(setList).catch((e) => setError(describe(e).detail));
}, []),
);
/** Outils de fidélisation (gérants, formule Pro). */
export default function Loyalty() {
return ( return (
<ScrollView contentContainerStyle={{ padding: 20, gap: 12 }}> <ScrollView contentContainerStyle={{ padding: 20, gap: 12 }}>
<T v="muted">Faites revenir vos clients avec des messages sur leur carte Wallet.</T> <T v="muted">Faites revenir vos clients avec des messages sur leur carte Wallet. Chaque module se règle entièrement : textes, délais, heures d'envoi.</T>
<Button label="Envoyer une campagne" variant="secondary" onPress={() => router.push('/campaigns')} /> {error && <Banner tone="error">{error}</Banner>}
<Button label="Relance des clients inactifs" variant="secondary" onPress={() => router.push('/reminders')} /> {list?.map((m) => {
<Button label="Offre d'anniversaire" variant="secondary" onPress={() => router.push('/birthday')} /> const state = !m.available ? ['Non inclus', c.text3] : m.config.enabled ? ['Activé', c.ok] : ['Désactivé', c.text3];
<Button label="Avis Google" variant="secondary" onPress={() => router.push('/reviews')} /> return (
<Button label="Parrainage" variant="secondary" onPress={() => router.push('/referral')} /> <Pressable key={m.id} accessibilityRole="button" onPress={() => router.push({ pathname: '/module/[id]', params: { id: m.id } })}>
{({ pressed }) => (
<Card style={{ padding: 16, gap: 4, opacity: pressed ? 0.7 : 1 }}>
<View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
<T style={{ fontFamily: font.bold, fontSize: 17 }}>{m.name}</T>
<T style={{ fontFamily: font.semibold, fontSize: 13, color: state[1] }}>{state[0]}</T>
</View>
<T v="muted" style={{ fontSize: 14 }}>{m.tagline}</T>
</Card>
)}
</Pressable>
);
})}
</ScrollView> </ScrollView>
); );
} }

153
pro/app/module/[id].tsx Normal file
View file

@ -0,0 +1,153 @@
import { useCallback, useState } from 'react';
import { Pressable, ScrollView, Switch, TextInput, View } from 'react-native';
import { router, Stack, useFocusEffect, useLocalSearchParams } from 'expo-router';
import { api } from '../../src/api';
import { describe } from '../../src/errors';
import { FieldDef, ModuleInfo, Value } from '../../src/modules';
import { Banner, Button, Card, T } from '../../src/ui';
import { font, useColors } from '../../src/theme';
function Field({ f, value, onChange }: { f: FieldDef; value: Value; onChange: (v: Value) => void }) {
const c = useColors();
const input = { borderWidth: 1, borderColor: c.border, borderRadius: 14, padding: 14, backgroundColor: c.surface, color: c.text, fontFamily: font.regular, fontSize: 16 } as const;
const help = [f.help, 'variables' in f && f.variables?.length ? `Variables : ${f.variables.join(' ')}` : null].filter(Boolean).join(' ');
if (f.type === 'boolean') {
return (
<Card style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', padding: 16, gap: 12 }}>
<View style={{ flex: 1 }}>
<T v="label">{f.label}</T>
{!!f.help && <T v="muted" style={{ fontSize: 13 }}>{f.help}</T>}
</View>
<Switch value={!!value} onValueChange={onChange} accessibilityLabel={f.label} />
</Card>
);
}
if (f.type === 'int' || f.type === 'hour') {
const n = Number(value);
const set = (v: number) => onChange(Math.max(f.min, Math.min(f.max, v)));
const btn = (d: number) => (
<Pressable
accessibilityRole="button"
accessibilityLabel={`${f.label} : ${d > 0 ? 'plus' : 'moins'}`}
onPress={() => set(n + d)}
style={{ width: 44, height: 44, borderRadius: 22, borderWidth: 1, borderColor: c.border, backgroundColor: c.surface, alignItems: 'center', justifyContent: 'center' }}
>
<T style={{ fontFamily: font.bold, fontSize: 20 }}>{d > 0 ? '+' : '−'}</T>
</Pressable>
);
return (
<View style={{ gap: 6 }}>
<T v="label">{f.label}</T>
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 10 }}>
{btn(-1)}
<TextInput
value={String(n)}
onChangeText={(t) => set(Math.floor(Number(t.replace(/\D/g, '')) || 0))}
keyboardType="number-pad"
accessibilityLabel={f.label}
style={{ ...input, width: 76, textAlign: 'center', paddingVertical: 10 }}
/>
{btn(1)}
<T v="muted" style={{ flex: 1 }}>{f.type === 'hour' ? 'h' : f.unit}</T>
</View>
{!!help && <T v="muted" style={{ fontSize: 13 }}>{help}</T>}
</View>
);
}
const t = f as Extract<FieldDef, { maxLength: number }>;
const text = String(value ?? '');
return (
<View style={{ gap: 6 }}>
<T v="label">{t.label}</T>
<TextInput
value={text}
onChangeText={onChange}
multiline={t.type === 'textarea'}
maxLength={t.maxLength}
autoCapitalize={t.type === 'url' ? 'none' : 'sentences'}
autoCorrect={t.type !== 'url'}
keyboardType={t.type === 'url' ? 'url' : 'default'}
accessibilityLabel={t.label}
style={{ ...input, ...(t.type === 'textarea' && { minHeight: 90, textAlignVertical: 'top' as const }) }}
/>
<View style={{ flexDirection: 'row', justifyContent: 'space-between', gap: 8 }}>
<T v="muted" style={{ fontSize: 13, flex: 1 }}>{help}</T>
<T v="muted" style={{ fontSize: 12 }}>{text.length}/{t.maxLength}</T>
</View>
{t.type !== 'url' && text !== t.default && (
<Pressable accessibilityRole="button" onPress={() => onChange(t.default)}>
<T style={{ color: c.primary, fontSize: 14 }}>Remettre le texte par défaut</T>
</Pressable>
)}
</View>
);
}
/** Réglages complets d'un module (gérants). */
export default function ModuleScreen() {
const { id } = useLocalSearchParams<{ id: string }>();
const [m, setM] = useState<ModuleInfo | null>(null);
const [values, setValues] = useState<Record<string, Value>>({});
const [error, setError] = useState<string | null>(null);
const [saved, setSaved] = useState(false);
const [busy, setBusy] = useState(false);
const apply = (next: ModuleInfo) => {
setM(next);
setValues(next.config);
};
useFocusEffect(
useCallback(() => {
api.get<ModuleInfo>(`/api/staff/modules/${id}`).then(apply).catch((e) => setError(describe(e).detail));
}, [id]),
);
async function save() {
setBusy(true);
setError(null);
setSaved(false);
try {
apply(await api.put<ModuleInfo>(`/api/staff/modules/${id}`, values));
setSaved(true);
} catch (e) {
setError(describe(e).detail);
} finally {
setBusy(false);
}
}
if (!m) return <View style={{ padding: 20 }}>{error ? <Banner tone="error">{error}</Banner> : <T v="muted">Chargement…</T>}</View>;
const dirty = JSON.stringify(values) !== JSON.stringify(m.config);
return (
<ScrollView contentContainerStyle={{ padding: 20, gap: 16 }} keyboardShouldPersistTaps="handled">
<Stack.Screen options={{ title: m.name }} />
{error && <Banner tone="error">{error}</Banner>}
{saved && <Banner tone="ok">Réglages enregistrés.</Banner>}
{!m.available && <Banner tone="warn">Ce module n'est pas inclus dans votre formule. Contactez MonEspacePro pour l'ajouter.</Banner>}
<T v="muted">{m.description}</T>
{m.available && m.config.enabled && m.id === 'campaigns' && <Button label="Envoyer une campagne" onPress={() => router.push('/campaigns')} />}
{m.available && m.config.enabled && m.id === 'stats' && <Button label="Voir les statistiques" onPress={() => router.push('/stats')} />}
<Field f={{ key: 'enabled', type: 'boolean', label: 'Module activé', default: false }} value={values.enabled} onChange={(v) => setValues({ ...values, enabled: v })} />
{m.fields.map((f) => (
<Field key={f.key} f={f} value={values[f.key]} onChange={(v) => setValues({ ...values, [f.key]: v })} />
))}
<Button label="Enregistrer" onPress={save} loading={busy} disabled={!dirty} />
{m.stats && (
<View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 12 }}>
{Object.entries(m.stats).map(([k, v]) => (
<Card key={k} style={{ width: '47%', flexGrow: 1, padding: 14, gap: 2 }}>
<T style={{ fontFamily: font.extrabold, fontSize: 22 }}>{v ?? '—'}</T>
<T v="muted" style={{ fontSize: 13 }}>{k}</T>
</Card>
))}
</View>
)}
</ScrollView>
);
}

View file

@ -1,113 +0,0 @@
import { useCallback, useState } from 'react';
import { Pressable, ScrollView, Switch, View } from 'react-native';
import { useFocusEffect } from 'expo-router';
import { api } from '../src/api';
import { describe } from '../src/errors';
import { useStore } from '../src/session';
import { Banner, Button, Card, T, unit } from '../src/ui';
import { font, useColors } from '../src/theme';
interface Referral {
allowed: boolean;
settings: { enabled: boolean; points: number; friendPoints: number };
maxPoints: number;
maxRewardsPer30Days: number;
stats: { referred: number; rewarded: number };
}
/** Parrainage (gérants, formule Pro). */
export default function ReferralScreen() {
const c = useColors();
const store = useStore();
const [data, setData] = useState<Referral | null>(null);
const [enabled, setEnabled] = useState(false);
const [points, setPoints] = useState(5);
const [friendPoints, setFriendPoints] = useState(0);
const [error, setError] = useState<string | null>(null);
const [saved, setSaved] = useState(false);
const [busy, setBusy] = useState(false);
const apply = (d: Referral) => {
setData(d);
setEnabled(d.settings.enabled);
setPoints(d.settings.points);
setFriendPoints(d.settings.friendPoints);
};
useFocusEffect(
useCallback(() => {
api.get<Referral>('/api/staff/referral').then(apply).catch((e) => setError(describe(e).detail));
}, []),
);
async function save() {
setBusy(true);
setError(null);
setSaved(false);
try {
apply(await api.put<Referral>('/api/staff/referral', { enabled, points, friendPoints }));
setSaved(true);
} catch (e) {
setError(describe(e).detail);
} finally {
setBusy(false);
}
}
if (!data) return <View style={{ padding: 20 }}>{error ? <Banner tone="error">{error}</Banner> : <T v="muted">Chargement…</T>}</View>;
const btn = (label: string, d: number, value: number, set: (n: number) => void) => (
<Pressable
accessibilityRole="button"
accessibilityLabel={`${label} : ${d > 0 ? 'plus' : 'moins'}`}
onPress={() => set(Math.max(0, Math.min(data.maxPoints, value + d)))}
style={{ width: 48, height: 48, borderRadius: 24, borderWidth: 1, borderColor: c.border, backgroundColor: c.surface, alignItems: 'center', justifyContent: 'center' }}
>
<T style={{ fontFamily: font.bold, fontSize: 22 }}>{d > 0 ? '+' : '−'}</T>
</Pressable>
);
const stepper = (label: string, value: number, set: (n: number) => void) => (
<View style={{ gap: 8 }}>
<T v="label">{label}</T>
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 16 }}>
{btn(label, -1, value, set)}
<T style={{ fontFamily: font.extrabold, fontSize: 24, minWidth: 40, textAlign: 'center' }}>{value}</T>
{btn(label, 1, value, set)}
<T v="muted" style={{ flex: 1 }}>{value === 0 ? 'rien' : unit(store.design.pointsMode, value)}</T>
</View>
</View>
);
return (
<ScrollView contentContainerStyle={{ padding: 20, gap: 16 }}>
{error && <Banner tone="error">{error}</Banner>}
{saved && <Banner tone="ok">Réglages enregistrés.</Banner>}
{!data.allowed && <Banner tone="warn">Le parrainage est inclus dans la formule Pro. Contactez MonEspacePro pour changer de formule.</Banner>}
<T v="muted">
Chaque client a un lien à partager. Quand un ami s'inscrit avec ce lien et fait son premier passage, le parrain est récompensé. Au plus {data.maxRewardsPer30Days} récompenses par parrain sur 30 jours.
</T>
<Card style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', padding: 16 }}>
<T v="label">Parrainage</T>
<Switch value={enabled} onValueChange={setEnabled} disabled={!data.allowed && !enabled} accessibilityLabel="Parrainage" />
</Card>
{stepper('Offerts au parrain', points, setPoints)}
{stepper('Offerts au filleul', friendPoints, setFriendPoints)}
<Button label="Enregistrer" onPress={save} loading={busy} />
<View style={{ flexDirection: 'row', gap: 12 }}>
{[
[data.stats.referred, 'filleuls inscrits'],
[data.stats.rewarded, 'venus en magasin'],
].map(([n, l]) => (
<Card key={String(l)} style={{ flex: 1, padding: 14, gap: 2 }}>
<T style={{ fontFamily: font.extrabold, fontSize: 22 }}>{n}</T>
<T v="muted" style={{ fontSize: 13 }}>{l}</T>
</Card>
))}
</View>
</ScrollView>
);
}

View file

@ -1,116 +0,0 @@
import { useCallback, useState } from 'react';
import { Pressable, ScrollView, Switch, TextInput, View } from 'react-native';
import { useFocusEffect } from 'expo-router';
import { api } from '../src/api';
import { describe } from '../src/errors';
import { Banner, Button, Card, T } from '../src/ui';
import { font, useColors } from '../src/theme';
interface Reminders {
allowed: boolean;
settings: { enabled: boolean; days: number; message: string | null };
defaultMessage: string;
dayChoices: number[];
stats: { pending: number; sentLast30Days: number; cameBack: number; totalReminded: number };
}
/** Relance automatique des clients inactifs (gérants, formule Pro). */
export default function RemindersScreen() {
const c = useColors();
const [data, setData] = useState<Reminders | null>(null);
const [enabled, setEnabled] = useState(false);
const [days, setDays] = useState(45);
const [message, setMessage] = useState('');
const [error, setError] = useState<string | null>(null);
const [saved, setSaved] = useState(false);
const [busy, setBusy] = useState(false);
const apply = (d: Reminders) => {
setData(d);
setEnabled(d.settings.enabled);
setDays(d.settings.days);
setMessage(d.settings.message ?? '');
};
useFocusEffect(
useCallback(() => {
api.get<Reminders>('/api/staff/reminders').then(apply).catch((e) => setError(describe(e).detail));
}, []),
);
async function save() {
setBusy(true);
setError(null);
setSaved(false);
try {
apply(await api.put<Reminders>('/api/staff/reminders', { enabled, days, message: message.trim() || null }));
setSaved(true);
} catch (e) {
setError(describe(e).detail);
} finally {
setBusy(false);
}
}
if (!data) return <View style={{ padding: 20 }}>{error ? <Banner tone="error">{error}</Banner> : <T v="muted">Chargement…</T>}</View>;
const s = data.stats;
return (
<ScrollView contentContainerStyle={{ padding: 20, gap: 16 }} keyboardShouldPersistTaps="handled">
{error && <Banner tone="error">{error}</Banner>}
{saved && <Banner tone="ok">Réglages enregistrés.</Banner>}
{!data.allowed && <Banner tone="warn">La relance automatique est incluse dans la formule Pro. Contactez MonEspacePro pour changer de formule.</Banner>}
<T v="muted">
Un client qui n'est pas revenu depuis le délai choisi reçoit une notification sur sa carte, entre 10 h et 19 h. Une seule relance par absence.
</T>
<Card style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', padding: 16 }}>
<T v="label">Relance automatique</T>
<Switch value={enabled} onValueChange={setEnabled} disabled={!data.allowed && !enabled} accessibilityLabel="Relance automatique" />
</Card>
<T v="label">Relancer après</T>
<View style={{ flexDirection: 'row', gap: 8, flexWrap: 'wrap' }}>
{data.dayChoices.map((d) => (
<Pressable
key={d}
accessibilityRole="button"
accessibilityState={{ selected: days === d }}
onPress={() => setDays(d)}
style={{ paddingVertical: 10, paddingHorizontal: 16, borderRadius: 999, borderWidth: 1, borderColor: days === d ? c.primary : c.border, backgroundColor: days === d ? c.primarySoft : c.surface }}
>
<T style={{ fontFamily: font.semibold, color: days === d ? c.primary : c.text }}>{d} jours</T>
</Pressable>
))}
</View>
<T v="label">Message</T>
<TextInput
value={message}
onChangeText={setMessage}
multiline
maxLength={160}
placeholder={data.defaultMessage}
placeholderTextColor={c.text3}
accessibilityLabel="Message de relance"
style={{ minHeight: 90, borderWidth: 1, borderColor: c.border, borderRadius: 14, padding: 14, backgroundColor: c.surface, color: c.text, fontFamily: font.regular, fontSize: 16, textAlignVertical: 'top' }}
/>
<T v="muted" style={{ fontSize: 13 }}>Vide = texte par défaut. {'{prenom}'} et {'{solde}'} sont remplacés automatiquement.</T>
<Button label="Enregistrer" onPress={save} loading={busy} />
<View style={{ flexDirection: 'row', gap: 12 }}>
{[
[s.pending, 'à relancer'],
[s.sentLast30Days, 'relances (30 j)'],
[`${s.cameBack}/${s.totalReminded}`, 'revenus'],
].map(([n, l]) => (
<Card key={String(l)} style={{ flex: 1, padding: 14, gap: 2 }}>
<T style={{ fontFamily: font.extrabold, fontSize: 22 }}>{n}</T>
<T v="muted" style={{ fontSize: 13 }}>{l}</T>
</Card>
))}
</View>
</ScrollView>
);
}

View file

@ -1,111 +0,0 @@
import { useCallback, useState } from 'react';
import { Pressable, ScrollView, Switch, TextInput, View } from 'react-native';
import { useFocusEffect } from 'expo-router';
import { api } from '../src/api';
import { describe } from '../src/errors';
import { Banner, Button, Card, T } from '../src/ui';
import { font, useColors } from '../src/theme';
interface Reviews {
allowed: boolean;
settings: { enabled: boolean; url: string | null; afterVisits: number; message: string | null };
defaultMessage: string;
visitChoices: number[];
stats: { asked: number; clicked: number };
}
/** Collecte d'avis Google (gérants, formule Pro). */
export default function ReviewsScreen() {
const c = useColors();
const [data, setData] = useState<Reviews | null>(null);
const [enabled, setEnabled] = useState(false);
const [url, setUrl] = useState('');
const [afterVisits, setAfterVisits] = useState(2);
const [message, setMessage] = useState('');
const [error, setError] = useState<string | null>(null);
const [saved, setSaved] = useState(false);
const [busy, setBusy] = useState(false);
const apply = (d: Reviews) => {
setData(d);
setEnabled(d.settings.enabled);
setUrl(d.settings.url ?? '');
setAfterVisits(d.settings.afterVisits);
setMessage(d.settings.message ?? '');
};
useFocusEffect(
useCallback(() => {
api.get<Reviews>('/api/staff/reviews').then(apply).catch((e) => setError(describe(e).detail));
}, []),
);
async function save() {
setBusy(true);
setError(null);
setSaved(false);
try {
apply(await api.put<Reviews>('/api/staff/reviews', { enabled, url: url.trim() || null, afterVisits, message: message.trim() || null }));
setSaved(true);
} catch (e) {
setError(describe(e).detail);
} finally {
setBusy(false);
}
}
if (!data) return <View style={{ padding: 20 }}>{error ? <Banner tone="error">{error}</Banner> : <T v="muted">Chargement…</T>}</View>;
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>}
{saved && <Banner tone="ok">Réglages enregistrés.</Banner>}
{!data.allowed && <Banner tone="warn">La collecte d'avis est incluse dans la formule Pro. Contactez MonEspacePro pour changer de formule.</Banner>}
<T v="muted">
Après quelques passages, vos clients reçoivent une seule fois une invitation à laisser un avis Google. Règle Google : aucune récompense en échange d'un avis.
</T>
<Card style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', padding: 16 }}>
<T v="label">Collecte d'avis</T>
<Switch value={enabled} onValueChange={setEnabled} disabled={!data.allowed && !enabled} accessibilityLabel="Collecte d'avis" />
</Card>
<T v="label">Lien de votre fiche Google</T>
<TextInput value={url} onChangeText={setUrl} autoCapitalize="none" autoCorrect={false} keyboardType="url" placeholder="https://g.page/r/…/review" placeholderTextColor={c.text3} accessibilityLabel="Lien de la fiche Google" style={input} />
<T v="muted" style={{ fontSize: 13 }}>Google Business Profile → « Demander des avis » → copier le lien.</T>
<T v="label">Demander après</T>
<View style={{ flexDirection: 'row', gap: 8, flexWrap: 'wrap' }}>
{data.visitChoices.map((n) => (
<Pressable
key={n}
accessibilityRole="button"
accessibilityState={{ selected: afterVisits === n }}
onPress={() => setAfterVisits(n)}
style={{ paddingVertical: 10, paddingHorizontal: 16, borderRadius: 999, borderWidth: 1, borderColor: afterVisits === n ? c.primary : c.border, backgroundColor: afterVisits === n ? c.primarySoft : c.surface }}
>
<T style={{ fontFamily: font.semibold, color: afterVisits === n ? c.primary : c.text }}>{n} passage{n > 1 ? 's' : ''}</T>
</Pressable>
))}
</View>
<T v="label">Message</T>
<TextInput value={message} onChangeText={setMessage} multiline maxLength={160} placeholder={data.defaultMessage} placeholderTextColor={c.text3} accessibilityLabel="Message de demande d'avis" style={{ ...input, minHeight: 90, textAlignVertical: 'top' }} />
<Button label="Enregistrer" onPress={save} loading={busy} />
<View style={{ flexDirection: 'row', gap: 12 }}>
{[
[data.stats.asked, 'demandes envoyées'],
[data.stats.clicked, 'clics vers Google'],
].map(([n, l]) => (
<Card key={String(l)} style={{ flex: 1, padding: 14, gap: 2 }}>
<T style={{ fontFamily: font.extrabold, fontSize: 22 }}>{n}</T>
<T v="muted" style={{ fontSize: 13 }}>{l}</T>
</Card>
))}
</View>
</ScrollView>
);
}

View file

@ -46,7 +46,7 @@ export default function StatsScreen() {
setData(await api.get<Stats>(`/api/staff/stats?days=${d}`)); setData(await api.get<Stats>(`/api/staff/stats?days=${d}`));
} catch (e) { } catch (e) {
const info = describe(e); const info = describe(e);
if (e instanceof ApiError && e.code === 'PLAN_REQUIRED') setLocked(true); if (e instanceof ApiError && (e.code === 'PLAN_REQUIRED' || e.code === 'MODULE_DISABLED')) setLocked(true);
else setError(info.detail); else setError(info.detail);
} }
}, []); }, []);
@ -71,7 +71,7 @@ export default function StatsScreen() {
if (locked) { if (locked) {
return ( return (
<View style={{ padding: 20 }}> <View style={{ padding: 20 }}>
<Banner tone="warn">Les statistiques et exports sont inclus dans la formule Pro. Contactez MonEspacePro pour changer de formule.</Banner> <Banner tone="warn">Le module Statistiques & export n'est pas actif : activez-le dans Modules, ou contactez MonEspacePro s'il n'est pas inclus dans votre formule.</Banner>
</View> </View>
); );
} }

20
pro/src/modules.ts Normal file
View file

@ -0,0 +1,20 @@
/** Modules complémentaires : définitions envoyées par l'API (backend/src/modules/catalog.ts). */
export type Value = string | number | boolean;
export type FieldDef =
| { key: string; type: 'boolean'; label: string; help?: string; default: boolean }
| { key: string; type: 'int' | 'hour'; label: string; help?: string; default: number; min: number; max: number; unit?: string }
| { key: string; type: 'text' | 'textarea' | 'url'; label: string; help?: string; default: string; maxLength: number; variables?: string[] };
export interface ModuleInfo {
id: string;
name: string;
tagline: string;
description: string;
fields: FieldDef[];
inPlan: boolean;
override: boolean | null;
available: boolean;
config: Record<string, Value> & { enabled: boolean };
stats?: Record<string, number | string | null> | null;
}

View file

@ -5,8 +5,9 @@ const path = require('path');
const backend = path.join(__dirname, '..', 'backend'); const backend = path.join(__dirname, '..', 'backend');
require(path.join(backend, 'node_modules', 'ts-node')).register({ transpileOnly: true, compilerOptions: { module: 'commonjs' } }); 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, TRIAL_DAYS } = require(path.join(backend, 'src', 'billing', 'plans.ts'));
const { MODULES } = require(path.join(backend, 'src', 'modules', 'catalog.ts'));
/** Fonctions vendues sur le site ; `soon: true` = pas encore développée (affichée « Bientôt »). */ /** Fonctions de base de chaque formule (les modules sont listés à part, depuis le catalogue) ; `soon: true` = affichée « Bientôt ». */
const MARKETING = { const MARKETING = {
ESSENTIEL: { ESSENTIEL: {
intro: null, intro: null,
@ -23,13 +24,6 @@ const MARKETING = {
intro: 'Tout Essentiel, plus :', intro: 'Tout Essentiel, plus :',
items: [ items: [
{ label: 'Employés illimités' }, { label: 'Employés illimités' },
{ label: 'Sans la mention « Propulsé par MonEspacePro »' },
{ label: 'Notifications et campagnes sur l’écran du téléphone' },
{ label: 'Relance automatique des clients inactifs' },
{ label: 'Offre d’anniversaire' },
{ label: 'Collecte d’avis Google' },
{ label: 'Parrainage' },
{ label: 'Statistiques avancées et export CSV' },
], ],
}, },
RESEAU: { RESEAU: {
@ -69,9 +63,45 @@ ${m.items
) )
.join('\n')} .join('\n')}
</ul> </ul>
<p style="font-weight:700;margin:20px 0 0">${def.modules.length ? `Modules inclus (${def.modules.length})` : 'Modules'}</p>
${
def.modules.length
? `<ul class="fl" style="margin-top:12px">\n${def.modules
.map((id) => `<li title="${moduleOf(id).tagline}"><svg class="ico"><use href="#i-check"/></svg><span>${moduleOf(id).name}</span></li>`)
.join('\n')}\n</ul>`
: '<p class="mu" style="margin-top:8px;font-size:15px">Aucun module inclus. Besoin d’un module en particulier&nbsp;? Nous l’ajoutons sur mesure.</p>'
}
</div>`; </div>`;
} }
const moduleOf = (id) => MODULES.find((m) => m.id === id);
/** Tableau des modules : ce que chaque formule inclut. */
const MODULES_TABLE = `<section class="sec" style="padding-top:0">
<div class="w">
<p class="eb">Modules</p>
<h2 style="max-width:22ch">Des modules complémentaires, réglables à 100&nbsp;%.</h2>
<p class="lead" style="margin:16px 0 32px">Chaque module s’active et se règle séparément&nbsp;: textes des messages, délais, heures d’envoi, points offerts. Un module absent de votre formule peut être ajouté sur mesure.</p>
<div class="mod-table" role="region" aria-label="Modules inclus par formule" tabindex="0">
<table>
<thead><tr><th scope="col">Module</th>${plans.map((p) => `<th scope="col">${p.name}</th>`).join('')}</tr></thead>
<tbody>
${MODULES.map(
(m) =>
`<tr><th scope="row"><strong>${m.name}</strong><span class="mu">${m.description}</span></th>${plans
.map((p) =>
p.modules.includes(m.id)
? '<td><svg class="ico" role="img" aria-label="Inclus"><use href="#i-check"/></svg></td>'
: '<td><span class="mu">Sur mesure</span></td>',
)
.join('')}</tr>`,
).join('\n')}
</tbody>
</table>
</div>
</div>
</section>`;
const TARIF_HERO = `<section class="sec" style="padding-bottom:40px"> const TARIF_HERO = `<section class="sec" style="padding-bottom:40px">
<div class="w"> <div class="w">
<p class="eb">Tarif</p> <p class="eb">Tarif</p>
@ -86,7 +116,8 @@ ${plans.map(planCard).join('\n')}
</div> </div>
<p class="mu" style="margin-top:20px;font-size:15px">Prix TTC. TVA non applicable, art. 293 B du CGI. Les fonctions « Bientôt » sont incluses dans la formule dès leur sortie, sans supplément.</p> <p class="mu" style="margin-top:20px;font-size:15px">Prix TTC. TVA non applicable, art. 293 B du CGI. Les fonctions « Bientôt » sont incluses dans la formule dès leur sortie, sans supplément.</p>
</div> </div>
</section>`; </section>
${MODULES_TABLE}`;
const SIMULATOR_INTRO = `<p class="lead">Choisissez une formule et le nombre de magasins : le total s’affiche, au mois ou à l’année.</p>`; const SIMULATOR_INTRO = `<p class="lead">Choisissez une formule et le nombre de magasins : le total s’affiche, au mois ou à l’année.</p>`;
@ -142,7 +173,7 @@ function applyPricing(file, body) {
const DESCRIPTIONS = { 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.`, '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.`, '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.`,
}; };
const CSS = [ const CSS = [
@ -156,6 +187,17 @@ const CSS = [
'.mep .plan-price small{font-size:17px;font-weight:600;color:var(--mu);margin-left:6px;letter-spacing:0}', '.mep .plan-price small{font-size:17px;font-weight:600;color:var(--mu);margin-left:6px;letter-spacing:0}',
'.mep .plan-note{font-size:14px;margin-top:4px;min-height:1.5em}', '.mep .plan-note{font-size:14px;margin-top:4px;min-height:1.5em}',
'.mep .fl .soon{color:var(--mu)}', '.mep .fl .soon{color:var(--mu)}',
'.mep .mod-table{overflow-x:auto;border:1px solid var(--bd);border-radius:20px;background:var(--sf)}',
'.mep .mod-table table{width:100%;min-width:640px;border-collapse:collapse}',
'.mep .mod-table th,.mep .mod-table td{padding:16px 20px;border-bottom:1px solid var(--bd);text-align:center;vertical-align:middle}',
'.mep .mod-table tbody tr:last-child>*{border-bottom:0}',
'.mep .mod-table thead th{font-size:15px;font-weight:700}',
'.mep .mod-table tbody th{text-align:left;font-weight:400;max-width:440px}',
'.mep .mod-table tbody th strong{display:block;font-size:17px;margin-bottom:2px}',
'.mep .mod-table tbody th .mu{display:block;font-size:14px;line-height:1.45}',
'.mep .mod-table td .ico{color:var(--gr);width:22px;height:22px}',
'.mep .mod-table td .mu{font-size:13px;white-space:nowrap}',
'.mep .mod-table thead th:first-child{text-align:left}',
'.mep .soon-tag{display:inline-block;font-size:12px;font-weight:700;padding:2px 8px;border-radius:999px;background:var(--tint);color:var(--grt);margin-left:6px;vertical-align:1px;white-space:nowrap}', '.mep .soon-tag{display:inline-block;font-size:12px;font-weight:700;padding:2px 8px;border-radius:999px;background:var(--tint);color:var(--grt);margin-left:6px;vertical-align:1px;white-space:nowrap}',
].join('\n'); ].join('\n');

View file

@ -196,4 +196,15 @@ textarea.in{padding:14px 16px;min-height:140px;resize:vertical}
.mep .plan-price small{font-size:17px;font-weight:600;color:var(--mu);margin-left:6px;letter-spacing:0} .mep .plan-price small{font-size:17px;font-weight:600;color:var(--mu);margin-left:6px;letter-spacing:0}
.mep .plan-note{font-size:14px;margin-top:4px;min-height:1.5em} .mep .plan-note{font-size:14px;margin-top:4px;min-height:1.5em}
.mep .fl .soon{color:var(--mu)} .mep .fl .soon{color:var(--mu)}
.mep .mod-table{overflow-x:auto;border:1px solid var(--bd);border-radius:20px;background:var(--sf)}
.mep .mod-table table{width:100%;min-width:640px;border-collapse:collapse}
.mep .mod-table th,.mep .mod-table td{padding:16px 20px;border-bottom:1px solid var(--bd);text-align:center;vertical-align:middle}
.mep .mod-table tbody tr:last-child>*{border-bottom:0}
.mep .mod-table thead th{font-size:15px;font-weight:700}
.mep .mod-table tbody th{text-align:left;font-weight:400;max-width:440px}
.mep .mod-table tbody th strong{display:block;font-size:17px;margin-bottom:2px}
.mep .mod-table tbody th .mu{display:block;font-size:14px;line-height:1.45}
.mep .mod-table td .ico{color:var(--gr);width:22px;height:22px}
.mep .mod-table td .mu{font-size:13px;white-space:nowrap}
.mep .mod-table thead th:first-child{text-align:left}
.mep .soon-tag{display:inline-block;font-size:12px;font-weight:700;padding:2px 8px;border-radius:999px;background:var(--tint);color:var(--grt);margin-left:6px;vertical-align:1px;white-space:nowrap} .mep .soon-tag{display:inline-block;font-size:12px;font-weight:700;padding:2px 8px;border-radius:999px;background:var(--tint);color:var(--grt);margin-left:6px;vertical-align:1px;white-space:nowrap}

View file

@ -4,12 +4,12 @@
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>Tarif — MonEspacePro</title> <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."> <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.">
<link rel="canonical" href="https://monespacepro.eu/tarif/"> <link rel="canonical" href="https://monespacepro.eu/tarif/">
<meta name="theme-color" content="#0E7A66"> <meta name="theme-color" content="#0E7A66">
<meta property="og:type" content="website"> <meta property="og:type" content="website">
<meta property="og:title" content="Tarif — MonEspacePro"> <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."> <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:url" content="https://monespacepro.eu/tarif/"> <meta property="og:url" content="https://monespacepro.eu/tarif/">
<meta property="og:image" content="https://monespacepro.eu/assets/og.png"> <meta property="og:image" content="https://monespacepro.eu/assets/og.png">
<link rel="icon" type="image/svg+xml" href="/favicon.svg"> <link rel="icon" type="image/svg+xml" href="/favicon.svg">
@ -105,6 +105,8 @@
<li><svg class="ico"><use href="#i-check"/></svg><span>Anti-triche : plafond, délai, historique par employé</span></li> <li><svg class="ico"><use href="#i-check"/></svg><span>Anti-triche : plafond, délai, historique par employé</span></li>
<li><svg class="ico"><use href="#i-check"/></svg><span>Affichette de comptoir A5 / A6</span></li> <li><svg class="ico"><use href="#i-check"/></svg><span>Affichette de comptoir A5 / A6</span></li>
</ul> </ul>
<p style="font-weight:700;margin:20px 0 0">Modules</p>
<p class="mu" style="margin-top:8px;font-size:15px">Aucun module inclus. Besoin d’un module en particulier&nbsp;? Nous l’ajoutons sur mesure.</p>
</div> </div>
<div class="cd plan plan-pro"> <div class="cd plan plan-pro">
<span class="pill plan-tag">Conseillée</span> <span class="pill plan-tag">Conseillée</span>
@ -116,13 +118,16 @@
<p style="font-weight:700;margin:20px 0 0">Tout Essentiel, plus :</p> <p style="font-weight:700;margin:20px 0 0">Tout Essentiel, plus :</p>
<ul class="fl" style="margin-top:12px"> <ul class="fl" style="margin-top:12px">
<li><svg class="ico"><use href="#i-check"/></svg><span>Employés illimités</span></li> <li><svg class="ico"><use href="#i-check"/></svg><span>Employés illimités</span></li>
<li><svg class="ico"><use href="#i-check"/></svg><span>Sans la mention « Propulsé par MonEspacePro »</span></li> </ul>
<li><svg class="ico"><use href="#i-check"/></svg><span>Notifications et campagnes sur l’écran du téléphone</span></li> <p style="font-weight:700;margin:20px 0 0">Modules inclus (7)</p>
<li><svg class="ico"><use href="#i-check"/></svg><span>Relance automatique des clients inactifs</span></li> <ul class="fl" style="margin-top:12px">
<li><svg class="ico"><use href="#i-check"/></svg><span>Offre d’anniversaire</span></li> <li title="Notifications push à tous vos clients"><svg class="ico"><use href="#i-check"/></svg><span>Campagnes</span></li>
<li><svg class="ico"><use href="#i-check"/></svg><span>Collecte d’avis Google</span></li> <li title="Relance automatique des clients absents"><svg class="ico"><use href="#i-check"/></svg><span>Relance des inactifs</span></li>
<li><svg class="ico"><use href="#i-check"/></svg><span>Parrainage</span></li> <li title="Un cadeau le jour de l’anniversaire"><svg class="ico"><use href="#i-check"/></svg><span>Offre d'anniversaire</span></li>
<li><svg class="ico"><use href="#i-check"/></svg><span>Statistiques avancées et export CSV</span></li> <li title="Invitation à laisser un avis Google"><svg class="ico"><use href="#i-check"/></svg><span>Avis Google</span></li>
<li title="Vos clients recrutent leurs proches"><svg class="ico"><use href="#i-check"/></svg><span>Parrainage</span></li>
<li title="Statistiques avancées et export CSV"><svg class="ico"><use href="#i-check"/></svg><span>Statistiques & export</span></li>
<li title="Sans « Propulsé par MonEspacePro »"><svg class="ico"><use href="#i-check"/></svg><span>Marque blanche</span></li>
</ul> </ul>
</div> </div>
<div class="cd plan"> <div class="cd plan">
@ -138,11 +143,42 @@
<li class="soon"><svg class="ico"><use href="#i-check"/></svg><span>Tableau de bord consolidé <span class="soon-tag">Bientôt</span></span></li> <li class="soon"><svg class="ico"><use href="#i-check"/></svg><span>Tableau de bord consolidé <span class="soon-tag">Bientôt</span></span></li>
<li><svg class="ico"><use href="#i-check"/></svg><span>Tarif par magasin, à partir de 3 magasins</span></li> <li><svg class="ico"><use href="#i-check"/></svg><span>Tarif par magasin, à partir de 3 magasins</span></li>
</ul> </ul>
<p style="font-weight:700;margin:20px 0 0">Modules inclus (7)</p>
<ul class="fl" style="margin-top:12px">
<li title="Notifications push à tous vos clients"><svg class="ico"><use href="#i-check"/></svg><span>Campagnes</span></li>
<li title="Relance automatique des clients absents"><svg class="ico"><use href="#i-check"/></svg><span>Relance des inactifs</span></li>
<li title="Un cadeau le jour de l’anniversaire"><svg class="ico"><use href="#i-check"/></svg><span>Offre d'anniversaire</span></li>
<li title="Invitation à laisser un avis Google"><svg class="ico"><use href="#i-check"/></svg><span>Avis Google</span></li>
<li title="Vos clients recrutent leurs proches"><svg class="ico"><use href="#i-check"/></svg><span>Parrainage</span></li>
<li title="Statistiques avancées et export CSV"><svg class="ico"><use href="#i-check"/></svg><span>Statistiques & export</span></li>
<li title="Sans « Propulsé par MonEspacePro »"><svg class="ico"><use href="#i-check"/></svg><span>Marque blanche</span></li>
</ul>
</div> </div>
</div> </div>
<p class="mu" style="margin-top:20px;font-size:15px">Prix TTC. TVA non applicable, art. 293 B du CGI. Les fonctions « Bientôt » sont incluses dans la formule dès leur sortie, sans supplément.</p> <p class="mu" style="margin-top:20px;font-size:15px">Prix TTC. TVA non applicable, art. 293 B du CGI. Les fonctions « Bientôt » sont incluses dans la formule dès leur sortie, sans supplément.</p>
</div> </div>
</section> </section>
<section class="sec" style="padding-top:0">
<div class="w">
<p class="eb">Modules</p>
<h2 style="max-width:22ch">Des modules complémentaires, réglables à 100&nbsp;%.</h2>
<p class="lead" style="margin:16px 0 32px">Chaque module s’active et se règle séparément&nbsp;: textes des messages, délais, heures d’envoi, points offerts. Un module absent de votre formule peut être ajouté sur mesure.</p>
<div class="mod-table" role="region" aria-label="Modules inclus par formule" tabindex="0">
<table>
<thead><tr><th scope="col">Module</th><th scope="col">Essentiel</th><th scope="col">Pro</th><th scope="col">Réseau</th></tr></thead>
<tbody>
<tr><th scope="row"><strong>Campagnes</strong><span class="mu">Un message envoyé en notification sur le téléphone de tous les clients, visible ensuite sur leur carte.</span></th><td><span class="mu">Sur mesure</span></td><td><svg class="ico" role="img" aria-label="Inclus"><use href="#i-check"/></svg></td><td><svg class="ico" role="img" aria-label="Inclus"><use href="#i-check"/></svg></td></tr>
<tr><th scope="row"><strong>Relance des inactifs</strong><span class="mu">Un client qui n'est pas revenu depuis le délai choisi reçoit automatiquement une notification. Une seule relance par absence.</span></th><td><span class="mu">Sur mesure</span></td><td><svg class="ico" role="img" aria-label="Inclus"><use href="#i-check"/></svg></td><td><svg class="ico" role="img" aria-label="Inclus"><use href="#i-check"/></svg></td></tr>
<tr><th scope="row"><strong>Offre d'anniversaire</strong><span class="mu">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.</span></th><td><span class="mu">Sur mesure</span></td><td><svg class="ico" role="img" aria-label="Inclus"><use href="#i-check"/></svg></td><td><svg class="ico" role="img" aria-label="Inclus"><use href="#i-check"/></svg></td></tr>
<tr><th scope="row"><strong>Avis Google</strong><span class="mu">Après quelques passages, le client reçoit une seule fois une invitation à laisser un avis. Règle Google : aucune récompense en échange d'un avis.</span></th><td><span class="mu">Sur mesure</span></td><td><svg class="ico" role="img" aria-label="Inclus"><use href="#i-check"/></svg></td><td><svg class="ico" role="img" aria-label="Inclus"><use href="#i-check"/></svg></td></tr>
<tr><th scope="row"><strong>Parrainage</strong><span class="mu">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é.</span></th><td><span class="mu">Sur mesure</span></td><td><svg class="ico" role="img" aria-label="Inclus"><use href="#i-check"/></svg></td><td><svg class="ico" role="img" aria-label="Inclus"><use href="#i-check"/></svg></td></tr>
<tr><th scope="row"><strong>Statistiques & export</strong><span class="mu">Fréquentation, clients fidèles, heures d’affluence, meilleurs clients, et export CSV des clients et des opérations.</span></th><td><span class="mu">Sur mesure</span></td><td><svg class="ico" role="img" aria-label="Inclus"><use href="#i-check"/></svg></td><td><svg class="ico" role="img" aria-label="Inclus"><use href="#i-check"/></svg></td></tr>
<tr><th scope="row"><strong>Marque blanche</strong><span class="mu">La mention « Propulsé par MonEspacePro » disparaît des pages de vos clients.</span></th><td><span class="mu">Sur mesure</span></td><td><svg class="ico" role="img" aria-label="Inclus"><use href="#i-check"/></svg></td><td><svg class="ico" role="img" aria-label="Inclus"><use href="#i-check"/></svg></td></tr>
</tbody>
</table>
</div>
</div>
</section>
<section class="sec alt"> <section class="sec alt">
<div class="w"> <div class="w">