| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- /**
- * Utilitaires communs : appels API, affichage erreurs.
- */
- const API_BASE = '/api';
- async function apiGet(path, params = {}) {
- const url = new URL(API_BASE + path, window.location.origin);
- Object.entries(params).forEach(([k, v]) => url.searchParams.set(k, v));
- const res = await fetch(url.toString());
- const data = await res.json().catch(() => ({}));
- if (!res.ok) {
- throw new Error(data.error || res.statusText || 'Erreur API');
- }
- return data;
- }
- async function apiPost(path, body) {
- const res = await fetch(API_BASE + path, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(body),
- });
- const data = await res.json().catch(() => ({}));
- if (!res.ok) {
- throw new Error(data.error || res.statusText || 'Erreur API');
- }
- return data;
- }
- async function apiPut(path, body) {
- const res = await fetch(API_BASE + path, {
- method: 'PUT',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(body),
- });
- const data = await res.json().catch(() => ({}));
- if (!res.ok) {
- throw new Error(data.error || res.statusText || 'Erreur API');
- }
- return data;
- }
- async function apiDelete(path) {
- const res = await fetch(API_BASE + path, {
- method: 'DELETE',
- });
- const data = await res.json().catch(() => ({}));
- if (!res.ok) {
- throw new Error(data.error || res.statusText || 'Erreur API');
- }
- return data;
- }
- function showError(message) {
- const el = document.getElementById('error-message');
- if (el) {
- el.textContent = message;
- el.classList.remove('hidden');
- } else {
- alert(message);
- }
- }
- function hideError() {
- const el = document.getElementById('error-message');
- if (el) {
- el.classList.add('hidden');
- el.textContent = '';
- }
- }
- function formatMoney(value) {
- return new Intl.NumberFormat('fr-FR', { style: 'currency', currency: 'EUR' }).format(value);
- }
- function formatDate(str) {
- if (!str) return '-';
- const d = new Date(str);
- return isNaN(d.getTime()) ? str : d.toLocaleDateString('fr-FR');
- }
- function formatNumber(value) {
- if (value == null) return '-';
- return new Intl.NumberFormat('fr-FR').format(value);
- }
|