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://: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 = {}, ) { 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 | null = null; function refresh(): Promise { 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(method: string, path: string, body?: unknown, auth = true, retry = true): Promise { 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: (path: string) => request('GET', path), post: (path: string, body: unknown = {}) => request('POST', path, body), put: (path: string, body: unknown) => request('PUT', path, body), patch: (path: string, body: unknown) => request('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; }