Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr SMS Gateway8 * File : dashboard/src/api.ts9 * Module : dashboard10 * Repository : https://git.spboucher.ai/maclustr-sms11 * Project Website : https://sms.spboucher.ai12 * Created : 2026-11-3013 * Last Modified : 2026-11-3014 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142import { useCallback, useEffect, useRef, useState } from "react"4344export class ApiError extends Error { constructor(public status: number, public code: string, message: string) { super(message) } }4546export async function api<T = any>(method: string, path: string, body?: unknown, headers: Record<string, string> = {}): Promise<T> {47 const res = await fetch(path, { method, credentials: "same-origin", headers: { "x-requested-with": "maclustr-sms", ...(body !== undefined ? { "content-type": "application/json" } : {}), ...headers }, body: body === undefined ? undefined : JSON.stringify(body) })48 const text = await res.text()49 let j: any = null50 try { j = text ? JSON.parse(text) : null } catch {}51 if (!res.ok) {52 if (res.status === 401 && !path.startsWith("/api/auth/")) window.dispatchEvent(new Event("mlsms:unauthenticated"))53 throw new ApiError(res.status, j?.error?.code ?? "http_" + res.status, j?.error?.message ?? `erreur ${res.status}`)54 }55 return j as T56}57export const get = <T = any>(p: string) => api<T>("GET", p)58export const post = <T = any>(p: string, b: unknown = {}) => api<T>("POST", p, b)59export const patch = <T = any>(p: string, b: unknown) => api<T>("PATCH", p, b)60export const del = <T = any>(p: string) => api<T>("DELETE", p)6162// Flux SSE partagé : le serveur signale « quelque chose a changé » par thème, les vues concernées se rechargent.63type Listener = (topics: string[]) => void64const listeners = new Set<Listener>()65let source: EventSource | null = null66function ensureStream() {67 if (source) return68 source = new EventSource("/api/admin/events")69 source.onmessage = e => { try { const t = JSON.parse(e.data); listeners.forEach(l => l(t)) } catch {} }70}71export function closeStream() { source?.close(); source = null }7273/** Charge une ressource, la recharge sur signal temps réel (thèmes) et au moins toutes les 20 s. */74export function useData<T = any>(path: string | null, topics: string[] = []) {75 const [data, setData] = useState<T | null>(null)76 const [error, setError] = useState<string | null>(null)77 const seq = useRef(0)78 const reload = useCallback(async () => {79 if (!path) return80 const n = ++seq.current81 try { const d = await get<T>(path); if (n === seq.current) { setData(d); setError(null) } } catch (e: any) { if (n === seq.current) setError(e.message) }82 }, [path])83 useEffect(() => {84 setData(null); void reload()85 ensureStream()86 const l: Listener = t => { if (t.some(x => topics.includes(x))) void reload() }87 listeners.add(l)88 const timer = setInterval(() => { if (!document.hidden) void reload() }, 20_000)89 return () => { listeners.delete(l); clearInterval(timer) }90 }, [path, reload, topics.join(",")])91 return { data, error, reload }92}93