/** * Fonctions partagées entre les pages. */ /** * Appelle l'API et retourne la réponse JSON. * Redirige vers la page de connexion si non authentifié (401). */ async function appelerApi(url, options) { const reponse = await fetch(url, options); const donnees = await reponse.json().catch(function () { return {}; }); if (reponse.status === 401 && !url.includes("/api/connexion")) { window.location.href = "/connexion.html"; return null; } if (!reponse.ok) { throw new Error(donnees.erreur || "Erreur serveur"); } return donnees; } /** * Vérifie la session. Redirige vers connexion si besoin. * Affiche le nom et le lien Comptes pour l'admin. */ async function verifierSession() { const session = await appelerApi("/api/session"); if (!session || !session.connecte) { window.location.href = "/connexion.html"; return null; } const nomUtilisateur = document.getElementById("nomUtilisateur"); if (nomUtilisateur) { nomUtilisateur.textContent = session.utilisateur.login + " (" + session.utilisateur.profil + ")"; } const lienComptes = document.getElementById("lienComptes"); if (lienComptes && session.utilisateur.profil === "admin") { lienComptes.hidden = false; } return session.utilisateur; } /** * Branche le bouton de déconnexion s'il est présent sur la page. */ function brancherDeconnexion() { const bouton = document.getElementById("boutonDeconnexion"); if (!bouton) { return; } bouton.addEventListener("click", async function () { await appelerApi("/api/deconnexion", { method: "POST" }); window.location.href = "/connexion.html"; }); } /** * Affiche une étiquette lisible pour le type d'animal. */ function libelleType(type) { return type === "coq" ? "Coq" : "Poule"; } /** * Affiche une étiquette pour l'état de santé. */ function libelleSante(etat) { if (etat === "moyen") { return "Moyen"; } if (etat === "mauvais") { return "Mauvais"; } return "Bon"; } /** * Construit le HTML d'une carte animal (liste). */ function htmlCarteAnimal(animal) { let photoHtml = "
Bague : " + (animal.couleurBague || "—") + " " + (animal.numeroBague || "") + "
" + "Santé : " + libelleSante(animal.etatSante) + "
" + badges + "" ); }