Liste : chiffres clés (ouverts, en cours d'ouverture, impayés, cartes clients), lignes entièrement cliquables avec survol. Fiche magasin : en-tête en carte avec initiale, contact, étapes d'ouverture (abonnement payé, carte conçue, programme ouvert) et lien d'inscription à copier. L'API indique si la carte est conçue. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
229 lines
7.1 KiB
TypeScript
229 lines
7.1 KiB
TypeScript
/** Client de l'API : jeton d'accès en mémoire + rafraîchissement transparent. */
|
|
|
|
const BASE = import.meta.env.VITE_API_URL ?? '';
|
|
const REFRESH_KEY = 'mep.admin.refresh';
|
|
/** Admin MonEspacePro, ou Dirigeant d'un magasin (espace web /espace). */
|
|
const KIND_KEY = 'mep.admin.kind';
|
|
export type SessionKind = 'admin' | 'staff';
|
|
|
|
let accessToken: string | null = null;
|
|
let onLogout: () => void = () => undefined;
|
|
|
|
export class ApiError extends Error {
|
|
constructor(public status: number, message: string) {
|
|
super(message);
|
|
}
|
|
}
|
|
|
|
export function assetUrl(path: string | null | undefined) {
|
|
return path ? `${BASE}${path}` : null;
|
|
}
|
|
|
|
export function setLogoutHandler(fn: () => void) {
|
|
onLogout = fn;
|
|
}
|
|
|
|
export function hasSession() {
|
|
try {
|
|
return !!localStorage.getItem(REFRESH_KEY);
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/** Type de la session ouverte dans ce navigateur, ou null. */
|
|
export function sessionKind(): SessionKind | null {
|
|
try {
|
|
if (!localStorage.getItem(REFRESH_KEY)) return null;
|
|
return localStorage.getItem(KIND_KEY) === 'staff' ? 'staff' : 'admin';
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function storeTokens(t: { accessToken: string; refreshToken: string }, kind?: SessionKind) {
|
|
accessToken = t.accessToken;
|
|
try {
|
|
localStorage.setItem(REFRESH_KEY, t.refreshToken);
|
|
if (kind) localStorage.setItem(KIND_KEY, kind);
|
|
} catch {
|
|
/* navigation privée : la session durera le temps de l'onglet */
|
|
}
|
|
}
|
|
|
|
export function logout() {
|
|
accessToken = null;
|
|
try {
|
|
localStorage.removeItem(REFRESH_KEY);
|
|
localStorage.removeItem(KIND_KEY);
|
|
} catch {
|
|
/* rien */
|
|
}
|
|
onLogout();
|
|
}
|
|
|
|
export async function login(email: string, password: string) {
|
|
const t = await request<{ accessToken: string; refreshToken: string }>('POST', '/api/auth/admin/login', {
|
|
email,
|
|
password,
|
|
}, false);
|
|
storeTokens(t, 'admin');
|
|
}
|
|
|
|
/** Connexion du Dirigeant (mêmes identifiants que l'app Pro). */
|
|
export async function loginStaff(email: string, password: string) {
|
|
const t = await request<{ accessToken: string; refreshToken: string }>('POST', '/api/auth/staff/login', { email, password }, false);
|
|
storeTokens(t, 'staff');
|
|
}
|
|
|
|
/** Appel sans session (inscription en ligne). */
|
|
export const publicApi = {
|
|
get: <T>(path: string) => request<T>('GET', path, undefined, false),
|
|
post: <T>(path: string, body: unknown) => request<T>('POST', path, body, false),
|
|
};
|
|
|
|
let refreshing: Promise<boolean> | null = null;
|
|
async function refresh(): Promise<boolean> {
|
|
let token: string | null = null;
|
|
try {
|
|
token = localStorage.getItem(REFRESH_KEY);
|
|
} catch {
|
|
/* rien */
|
|
}
|
|
if (!token) return false;
|
|
// Une seule demande de rafraîchissement à la fois, partagée par les requêtes concurrentes.
|
|
refreshing ??= fetch(`${BASE}/api/auth/refresh`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ refreshToken: token }),
|
|
})
|
|
.then(async (r) => {
|
|
if (!r.ok) return false;
|
|
storeTokens(await r.json());
|
|
return true;
|
|
})
|
|
.catch(() => false)
|
|
.finally(() => {
|
|
refreshing = null;
|
|
});
|
|
return refreshing;
|
|
}
|
|
|
|
async function request<T>(method: string, path: string, body?: unknown, auth = true, retry = true): Promise<T> {
|
|
if (auth && !accessToken) await refresh();
|
|
const isForm = body instanceof FormData;
|
|
const res = await fetch(`${BASE}${path}`, {
|
|
method,
|
|
headers: {
|
|
...(body !== undefined && !isForm && { 'Content-Type': 'application/json' }),
|
|
...(auth && accessToken && { Authorization: `Bearer ${accessToken}` }),
|
|
},
|
|
body: body === undefined ? undefined : isForm ? body : JSON.stringify(body),
|
|
});
|
|
if (res.status === 401 && auth) {
|
|
if (retry && (await refresh())) return request(method, path, body, auth, false);
|
|
logout();
|
|
}
|
|
if (!res.ok) {
|
|
const data = await res.json().catch(() => ({}));
|
|
const msg = Array.isArray(data.message) ? data.message.join(' · ') : data.message;
|
|
throw new ApiError(res.status, msg || 'Une erreur est survenue');
|
|
}
|
|
// NestJS renvoie un corps vide quand le contrôleur retourne null (ex. carte pas encore conçue).
|
|
const text = await res.text();
|
|
return (text ? JSON.parse(text) : null) as T;
|
|
}
|
|
|
|
/** Téléchargement d'un fichier protégé (le jeton ne peut pas passer par un simple lien). */
|
|
export async function downloadFile(path: string, filename: string) {
|
|
if (!accessToken) await refresh();
|
|
let res = await fetch(`${BASE}${path}`, { headers: { Authorization: `Bearer ${accessToken}` } });
|
|
if (res.status === 401 && (await refresh())) {
|
|
res = await fetch(`${BASE}${path}`, { headers: { Authorization: `Bearer ${accessToken}` } });
|
|
}
|
|
if (!res.ok) throw new ApiError(res.status, 'Téléchargement impossible');
|
|
const url = URL.createObjectURL(await res.blob());
|
|
const a = Object.assign(document.createElement('a'), { href: url, download: filename });
|
|
a.click();
|
|
setTimeout(() => URL.revokeObjectURL(url), 10_000);
|
|
}
|
|
|
|
export const api = {
|
|
get: <T>(path: string) => request<T>('GET', path),
|
|
post: <T>(path: string, body?: unknown) => request<T>('POST', path, body ?? {}),
|
|
put: <T>(path: string, body: unknown) => request<T>('PUT', path, body),
|
|
patch: <T>(path: string, body: unknown) => request<T>('PATCH', path, body),
|
|
};
|
|
|
|
// ── Types partagés avec l'API ─────────────────────────────────
|
|
export type StoreStatus = 'DRAFT' | 'ACTIVE' | 'SUSPENDED' | 'CLOSED';
|
|
export type SubscriptionStatus = 'INCOMPLETE' | 'ACTIVE' | 'PAST_DUE' | 'CANCELED';
|
|
export type Plan = 'ESSENTIEL' | 'PRO' | 'RESEAU';
|
|
export type BillingInterval = 'MONTH' | 'YEAR';
|
|
export const PLAN_LABEL: Record<Plan, string> = { ESSENTIEL: 'Essentiel', PRO: 'Pro', RESEAU: 'Réseau' };
|
|
|
|
export interface Store {
|
|
id: string;
|
|
slug: string;
|
|
name: string;
|
|
addressLine: string;
|
|
postalCode: string;
|
|
city: string;
|
|
siret: string;
|
|
contactName: string;
|
|
contactEmail: string;
|
|
contactPhone: string;
|
|
status: StoreStatus;
|
|
billingSuspended: boolean;
|
|
maxAmountEuros: number;
|
|
minScanIntervalMin: number;
|
|
createdAt: string;
|
|
}
|
|
|
|
export interface StoreListItem extends Store {
|
|
customers: number;
|
|
subscriptionStatus: SubscriptionStatus | null;
|
|
plan: Plan | null;
|
|
}
|
|
|
|
export interface StoreDetail extends Store {
|
|
/** Carte de fidélité conçue. */
|
|
hasCard: boolean;
|
|
counts: { cards: number; staff: number; transactions: number };
|
|
subscription: { status: SubscriptionStatus; plan: Plan; stripeSubscriptionId: string | null } | null;
|
|
/** Lien encodé dans le QR d'inscription. */
|
|
enrollUrl: string;
|
|
}
|
|
|
|
export type PointsMode = 'AMOUNT' | 'STAMP';
|
|
|
|
export interface Reward {
|
|
id?: string;
|
|
label: string;
|
|
cost: number;
|
|
active?: boolean;
|
|
}
|
|
|
|
export interface CardDesign {
|
|
programName: string;
|
|
backgroundColor: string;
|
|
foregroundColor: string;
|
|
labelColor: string;
|
|
pointsMode: PointsMode;
|
|
pointsPerEuro: number;
|
|
rewards: Reward[];
|
|
logoUrl: string | null;
|
|
stripUrl: string | null;
|
|
}
|
|
|
|
export type StaffRole = 'MANAGER' | 'EMPLOYEE';
|
|
|
|
export interface StaffUser {
|
|
id: string;
|
|
email: string;
|
|
displayName: string;
|
|
role: StaffRole;
|
|
active: boolean;
|
|
createdAt: string;
|
|
provisionalPassword?: string;
|
|
}
|