MonEspacePro/pro/src/api.ts
Tony AVERTY 226f3cedb8 Espace web du Dirigeant, inscription en ligne, employés et cadeaux dans l'app Pro
- Admin : /inscription (formule, magasin, mot de passe, paiement Stripe) et
  /espace (connexion Dirigeant, état de l'abonnement, conception de la carte)
- Admin : formule obligatoire à la création d'un magasin, plus d'essai gratuit,
  lien d'abonnement permanent, titre des campagnes
- App Pro : écran Employés (création avec rôle Employé / Dirigeant), Mon compte
  (mot de passe), titre des campagnes, remise des cadeaux en caisse, accueil
  avant la conception de la carte
- Site : boutons « Choisir » vers l'inscription, avec la périodicité choisie

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 11:52:09 +02:00

170 lines
5 KiB
TypeScript

import * as SecureStore from 'expo-secure-store';
/**
* Client de l'API MonEspacePro. Le jeton de rafraîchissement est rangé dans
* le trousseau (SecureStore) ; le jeton d'accès reste en mémoire.
* En développement : EXPO_PUBLIC_API_URL=http://<IP du PC>:3100 dans pro/.env
*/
export const API_URL = (process.env.EXPO_PUBLIC_API_URL ?? 'http://localhost:3100').replace(/\/$/, '');
const REFRESH_KEY = 'mep.refresh';
let accessToken: string | null = null;
let onLogout: () => void = () => undefined;
export class ApiError extends Error {
constructor(
public status: number,
message: string,
public code?: string,
public data: Record<string, unknown> = {},
) {
super(message);
}
}
export function setLogoutHandler(fn: () => void) {
onLogout = fn;
}
export async function hasSession() {
return !!(await SecureStore.getItemAsync(REFRESH_KEY));
}
async function storeTokens(t: { accessToken: string; refreshToken: string }) {
accessToken = t.accessToken;
await SecureStore.setItemAsync(REFRESH_KEY, t.refreshToken);
}
export async function logout() {
accessToken = null;
await SecureStore.deleteItemAsync(REFRESH_KEY);
onLogout();
}
export async function login(email: string, password: string) {
const res = await request<{ accessToken: string; refreshToken: string }>('POST', '/api/auth/staff/login', { email, password }, false);
await storeTokens(res);
}
let refreshing: Promise<boolean> | null = null;
function refresh(): Promise<boolean> {
refreshing ??= (async () => {
const token = await SecureStore.getItemAsync(REFRESH_KEY);
if (!token) return false;
try {
const r = await fetch(`${API_URL}/api/auth/refresh`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ refreshToken: token }),
});
if (!r.ok) return false;
await storeTokens(await r.json());
return true;
} catch {
return 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();
let res: Response;
try {
res = await fetch(`${API_URL}${path}`, {
method,
headers: {
...(body !== undefined && { 'Content-Type': 'application/json' }),
...(auth && accessToken && { Authorization: `Bearer ${accessToken}` }),
},
body: body === undefined ? undefined : JSON.stringify(body),
});
} catch {
throw new ApiError(0, 'Pas de connexion au serveur. Vérifiez le réseau.', 'NETWORK');
}
if (res.status === 401 && auth) {
if (retry && (await refresh())) return request(method, path, body, auth, false);
await logout();
}
const text = await res.text();
const data = text ? JSON.parse(text) : null;
if (!res.ok) {
const msg = Array.isArray(data?.message) ? data.message.join(' · ') : data?.message;
throw new ApiError(res.status, msg || 'Une erreur est survenue', data?.code, data ?? {});
}
return data as T;
}
export const api = {
get: <T>(path: string) => request<T>('GET', path),
post: <T>(path: string, body: unknown = {}) => request<T>('POST', path, body),
put: <T>(path: string, body: unknown) => request<T>('PUT', path, body),
patch: <T>(path: string, body: unknown) => request<T>('PATCH', path, body),
};
// ── Types de l'API ─────────────────────────────────────────────
export type StaffRole = 'MANAGER' | 'EMPLOYEE';
export type PointsMode = 'AMOUNT' | 'STAMP';
export interface Reward {
id: string;
label: string;
cost: number;
}
export interface Me {
id: string;
displayName: string;
role: StaffRole;
store: {
id: string;
name: string;
city: string;
maxAmountCents: number;
minScanIntervalSec: number;
cardDesign: {
programName: string;
backgroundColor: string;
foregroundColor: string;
pointsMode: PointsMode;
pointsPerEuro: number;
logoUrl: string | null;
rewards: Reward[];
} | null;
};
}
export interface CardInfo {
serial: string;
firstName: string;
balance: number;
memberSince: string;
lastCreditAt: string | null;
nextCreditAt: string | null;
/** Cadeaux en nature à remettre (anniversaire, parrainage). */
gifts: { id: string; label: string; source: 'BIRTHDAY' | 'REFERRAL' | 'REFERRAL_FRIEND'; createdAt: string }[];
}
export interface Summary {
operations: number;
pointsGiven: number;
rewards: number;
}
export type TransactionType = 'CREDIT' | 'REDEEM' | 'ADJUST' | 'REJECTED';
export type RejectReason = 'AMOUNT_OVER_LIMIT' | 'TOO_SOON' | 'INSUFFICIENT_BALANCE';
export interface Operation {
id: string;
type: TransactionType;
amountCents: number | null;
points: number;
balanceAfter: number;
rejectReason: RejectReason | null;
createdAt: string;
reward: { label: string } | null;
staff: { id: string; displayName: string };
customerFirstName: string;
}