Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
766d853d30 | ||
|
|
fc3cde3d65 | ||
|
|
af464cfcb7 | ||
|
|
b5e4741178 | ||
|
|
4fd0f5dd37 | ||
|
|
58674dde4d | ||
|
|
6ad76ca773 | ||
|
|
82a1b93211 | ||
|
|
ddd0197130 | ||
|
|
8b8121ca1c | ||
|
|
270283e96d |
@@ -23,6 +23,7 @@ jobs:
|
||||
set -e
|
||||
echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login git.nfteam.ovh -u "${{ secrets.REGISTRY_USER }}" --password-stdin
|
||||
docker build --build-arg VITE_API_URL="${VITE_API_URL}" \
|
||||
--build-arg APP_BUILD="${GITHUB_SHA::12}" \
|
||||
-t "${IMAGE}:latest" -t "${IMAGE}:${GITHUB_SHA::12}" ./DataSentinel
|
||||
docker push --all-tags "${IMAGE}"
|
||||
echo "pushed ${IMAGE}"
|
||||
|
||||
@@ -11,6 +11,11 @@ ARG VITE_API_URL
|
||||
ENV VITE_API_URL=$VITE_API_URL
|
||||
RUN pnpm build
|
||||
|
||||
# SHA du commit construit, servi sur /version.json : permet de vérifier quelle
|
||||
# version est réellement déployée sans se fier au cache du navigateur.
|
||||
ARG APP_BUILD=local
|
||||
RUN printf '{"build":"%s"}' "$APP_BUILD" > /app/dist/version.json
|
||||
|
||||
FROM nginx:alpine
|
||||
COPY --from=build /app/dist /usr/share/nginx/html
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
// src/App.jsx
|
||||
// Configuration du routing React Router v6 avec protection des routes
|
||||
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
|
||||
import { AuthProvider, useAuth } from './context/AuthContext';
|
||||
import { AuthProvider } from './context/AuthContext';
|
||||
import { useAuth } from './context/useAuth';
|
||||
import Layout from './components/Layout/Layout';
|
||||
import Login from './pages/Login/Login';
|
||||
import Dashboard from './pages/Dashboard/Dashboard';
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
/* Écran d'administration des référentiels.
|
||||
|
||||
Avant correction, les boutons Modifier / Désactiver n'appelaient rien
|
||||
(console.log) et « Enregistrer » se contentait de fermer la modale. Ces
|
||||
tests vérifient que chaque action atteint réellement l'API et que les
|
||||
erreurs métier remontent à l'utilisateur. */
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { render, screen, waitFor, within } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import Admin from '../pages/Admin/Admin';
|
||||
import * as api from '../services/api';
|
||||
|
||||
const SERVICES = [
|
||||
{ id_service: 1, nom_service: 'Contrat' },
|
||||
{ id_service: 2, nom_service: 'Fournisseur' },
|
||||
];
|
||||
const CATEGORIES = [{ id_categorie: 1, intitule_categorie: 'Tiers-payeurs' }];
|
||||
const MONITORINGS = [{
|
||||
id_monito: 1, monito_intitule: 'Erreurs tiers payeurs', id_service: 1,
|
||||
id_categorie: 1, table_source: 'MONITO_TIERS_PAYEURS', bdd_source: 'Sage',
|
||||
}];
|
||||
|
||||
function stubLectures() {
|
||||
vi.spyOn(api, 'getServices').mockResolvedValue(SERVICES);
|
||||
vi.spyOn(api, 'getCategories').mockResolvedValue(CATEGORIES);
|
||||
vi.spyOn(api, 'getContacts').mockResolvedValue([]);
|
||||
vi.spyOn(api, 'getMonitorings').mockResolvedValue(MONITORINGS);
|
||||
}
|
||||
|
||||
async function ouvrirOnglet(utilisateur, nom) {
|
||||
await utilisateur.click(screen.getByRole('button', { name: nom }));
|
||||
}
|
||||
|
||||
describe('Admin — CRUD des référentiels', () => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
stubLectures();
|
||||
vi.spyOn(window, 'confirm').mockReturnValue(true);
|
||||
});
|
||||
|
||||
it('crée un service via l’API et recharge la liste', async () => {
|
||||
const creation = vi.spyOn(api, 'createService').mockResolvedValue({ id_service: 3 });
|
||||
const utilisateur = userEvent.setup();
|
||||
render(<Admin />);
|
||||
|
||||
await screen.findByText('Administration');
|
||||
await ouvrirOnglet(utilisateur, 'Services');
|
||||
await utilisateur.click(screen.getByRole('button', { name: /Ajouter/ }));
|
||||
|
||||
await utilisateur.type(screen.getByLabelText('Nom du service'), 'Comptabilité');
|
||||
await utilisateur.click(screen.getByRole('button', { name: 'Enregistrer' }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(creation).toHaveBeenCalledWith({ nom_service: 'Comptabilité' });
|
||||
});
|
||||
/* Rechargement après écriture : la liste doit être redemandée. */
|
||||
expect(api.getServices).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('pré-remplit le formulaire de modification avec la ligne choisie', async () => {
|
||||
vi.spyOn(api, 'updateService').mockResolvedValue({});
|
||||
const utilisateur = userEvent.setup();
|
||||
render(<Admin />);
|
||||
|
||||
await screen.findByText('Administration');
|
||||
await ouvrirOnglet(utilisateur, 'Services');
|
||||
|
||||
const ligne = screen.getByText('Fournisseur').closest('tr');
|
||||
await utilisateur.click(within(ligne).getByRole('button', { name: /Modifier/ }));
|
||||
|
||||
expect(screen.getByLabelText('Nom du service')).toHaveValue('Fournisseur');
|
||||
});
|
||||
|
||||
it('envoie l’identifiant de la ligne lors d’une modification', async () => {
|
||||
const modification = vi.spyOn(api, 'updateService').mockResolvedValue({});
|
||||
const utilisateur = userEvent.setup();
|
||||
render(<Admin />);
|
||||
|
||||
await screen.findByText('Administration');
|
||||
await ouvrirOnglet(utilisateur, 'Services');
|
||||
|
||||
const ligne = screen.getByText('Fournisseur').closest('tr');
|
||||
await utilisateur.click(within(ligne).getByRole('button', { name: /Modifier/ }));
|
||||
await utilisateur.click(screen.getByRole('button', { name: 'Enregistrer' }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(modification).toHaveBeenCalledWith(2, { nom_service: 'Fournisseur' });
|
||||
});
|
||||
});
|
||||
|
||||
it('demande confirmation avant de supprimer, et n’appelle rien si on refuse', async () => {
|
||||
window.confirm.mockReturnValue(false);
|
||||
const suppression = vi.spyOn(api, 'deleteService').mockResolvedValue({});
|
||||
const utilisateur = userEvent.setup();
|
||||
render(<Admin />);
|
||||
|
||||
await screen.findByText('Administration');
|
||||
await ouvrirOnglet(utilisateur, 'Services');
|
||||
|
||||
const ligne = screen.getByText('Contrat').closest('tr');
|
||||
await utilisateur.click(within(ligne).getByRole('button', { name: /Supprimer/ }));
|
||||
|
||||
expect(window.confirm).toHaveBeenCalled();
|
||||
expect(suppression).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('affiche le refus de l’API quand des enregistrements sont rattachés', async () => {
|
||||
/* Cas réel : l'API renvoie 409 avec le décompte des rattachements. */
|
||||
vi.spyOn(api, 'deleteService').mockRejectedValue(
|
||||
new Error('Erreur 409: Suppression impossible : 5 monitoring(s) rattachés.'),
|
||||
);
|
||||
const utilisateur = userEvent.setup();
|
||||
render(<Admin />);
|
||||
|
||||
await screen.findByText('Administration');
|
||||
await ouvrirOnglet(utilisateur, 'Services');
|
||||
|
||||
const ligne = screen.getByText('Contrat').closest('tr');
|
||||
await utilisateur.click(within(ligne).getByRole('button', { name: /Supprimer/ }));
|
||||
|
||||
expect(await screen.findByText(/5 monitoring\(s\) rattachés/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('parle de désactivation, pas de suppression, pour un monitoring', async () => {
|
||||
/* TABLE_FINAL référence le monitoring : il n'est jamais supprimé. */
|
||||
const desactivation = vi.spyOn(api, 'desactiverMonitoring').mockResolvedValue({});
|
||||
const utilisateur = userEvent.setup();
|
||||
render(<Admin />);
|
||||
|
||||
await screen.findByText('Administration');
|
||||
|
||||
const ligne = screen.getByText('Erreurs tiers payeurs').closest('tr');
|
||||
expect(within(ligne).getByRole('button', { name: /Désactiver/ })).toBeInTheDocument();
|
||||
|
||||
await utilisateur.click(within(ligne).getByRole('button', { name: /Désactiver/ }));
|
||||
await waitFor(() => expect(desactivation).toHaveBeenCalledWith(1));
|
||||
});
|
||||
|
||||
it('affiche le libellé du service plutôt que son identifiant brut', async () => {
|
||||
render(<Admin />);
|
||||
await screen.findByText('Administration');
|
||||
|
||||
const ligne = screen.getByText('Erreurs tiers payeurs').closest('tr');
|
||||
/* id_service = 1 doit s'afficher « Contrat ». */
|
||||
expect(within(ligne).getByText('Contrat')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('convertit en entier les identifiants issus des listes déroulantes', async () => {
|
||||
/* Un <select> renvoie une chaîne ; l'API attend un entier. */
|
||||
const creation = vi.spyOn(api, 'createMonitoring').mockResolvedValue({ id_monito: 9 });
|
||||
const utilisateur = userEvent.setup();
|
||||
render(<Admin />);
|
||||
|
||||
await screen.findByText('Administration');
|
||||
await utilisateur.click(screen.getByRole('button', { name: /Ajouter/ }));
|
||||
|
||||
await utilisateur.type(screen.getByLabelText('Nom'), 'Nouveau monitoring');
|
||||
await utilisateur.selectOptions(screen.getByLabelText('Service'), '2');
|
||||
await utilisateur.selectOptions(screen.getByLabelText('Catégorie'), '1');
|
||||
await utilisateur.type(screen.getByLabelText('Table source'), 'MONITO_TEST');
|
||||
await utilisateur.type(screen.getByLabelText('Base source'), 'Sage');
|
||||
await utilisateur.click(screen.getByRole('button', { name: 'Enregistrer' }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(creation).toHaveBeenCalledWith({
|
||||
monito_intitule: 'Nouveau monitoring',
|
||||
id_service: 2,
|
||||
id_categorie: 1,
|
||||
table_source: 'MONITO_TEST',
|
||||
bdd_source: 'Sage',
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,8 @@
|
||||
/* Tests du contexte d'authentification : login / logout */
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import { AuthProvider, useAuth } from '../context/AuthContext';
|
||||
import { AuthProvider } from '../context/AuthContext';
|
||||
import { useAuth } from '../context/useAuth';
|
||||
import * as api from '../services/api';
|
||||
|
||||
describe('AuthContext', () => {
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
/* Filtres du dashboard.
|
||||
|
||||
Le comportement testé ici est la correction apportée aux menus déroulants :
|
||||
ils étaient alimentés par les référentiels SERVICE / CATEGORIE complets,
|
||||
dont certaines entrées (« Business Intelligence ») n'ont aucun monitoring
|
||||
rattaché et menaient sur un écran vide. */
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import Dashboard from '../pages/Dashboard/Dashboard';
|
||||
import * as api from '../services/api';
|
||||
|
||||
/* Ce que renvoie GET /dashboard/filtres : uniquement les valeurs présentes
|
||||
dans VUE_CONSO. Contrat porte 2 catégories, Fournisseur une seule. */
|
||||
const FILTRES = {
|
||||
services: ['Contrat', 'Fournisseur'],
|
||||
categories: ['Comptes fournisseurs', 'DOM-TOM', 'Tiers-payeurs'],
|
||||
combinaisons: [
|
||||
{ service: 'Contrat', categorie: 'DOM-TOM' },
|
||||
{ service: 'Contrat', categorie: 'Tiers-payeurs' },
|
||||
{ service: 'Fournisseur', categorie: 'Comptes fournisseurs' },
|
||||
],
|
||||
};
|
||||
|
||||
function renduDashboard() {
|
||||
return render(<MemoryRouter><Dashboard /></MemoryRouter>);
|
||||
}
|
||||
|
||||
describe('Dashboard — menus de filtre', () => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.spyOn(api, 'getDashboardFiltres').mockResolvedValue(FILTRES);
|
||||
vi.spyOn(api, 'getDashboardSummary').mockResolvedValue({
|
||||
total: 3, ok: 0, critical: 3, total_erreurs: 12,
|
||||
});
|
||||
vi.spyOn(api, 'getDashboard').mockResolvedValue([]);
|
||||
});
|
||||
|
||||
it('ne propose que les services ayant au moins un monitoring', async () => {
|
||||
renduDashboard();
|
||||
|
||||
const selectService = await screen.findByDisplayValue('Tous les services');
|
||||
const options = [...selectService.options].map(o => o.value);
|
||||
|
||||
expect(options).toContain('Contrat');
|
||||
expect(options).toContain('Fournisseur');
|
||||
/* Le cœur du correctif : ces entrées du référentiel ne doivent pas
|
||||
apparaître puisqu'elles ramèneraient un dashboard vide. */
|
||||
expect(options).not.toContain('Business Intelligence');
|
||||
expect(options).not.toContain('Comptabilité');
|
||||
});
|
||||
|
||||
it('restreint les catégories au service sélectionné', async () => {
|
||||
const utilisateur = userEvent.setup();
|
||||
renduDashboard();
|
||||
|
||||
const selectService = await screen.findByDisplayValue('Tous les services');
|
||||
const selectCategorie = screen.getByDisplayValue('Toutes les catégories');
|
||||
|
||||
/* Sans filtre de service : toutes les catégories utilisées */
|
||||
expect([...selectCategorie.options].map(o => o.value)).toEqual(
|
||||
expect.arrayContaining(['DOM-TOM', 'Tiers-payeurs', 'Comptes fournisseurs']),
|
||||
);
|
||||
|
||||
await utilisateur.selectOptions(selectService, 'Fournisseur');
|
||||
|
||||
await waitFor(() => {
|
||||
const restantes = [...selectCategorie.options].map(o => o.value).filter(Boolean);
|
||||
expect(restantes).toEqual(['Comptes fournisseurs']);
|
||||
});
|
||||
});
|
||||
|
||||
it('réinitialise la catégorie devenue sans résultat après changement de service', async () => {
|
||||
const utilisateur = userEvent.setup();
|
||||
renduDashboard();
|
||||
|
||||
const selectService = await screen.findByDisplayValue('Tous les services');
|
||||
const selectCategorie = screen.getByDisplayValue('Toutes les catégories');
|
||||
|
||||
await utilisateur.selectOptions(selectCategorie, 'DOM-TOM');
|
||||
expect(selectCategorie.value).toBe('DOM-TOM');
|
||||
|
||||
/* DOM-TOM n'existe pas pour Fournisseur : garder la sélection
|
||||
produirait une combinaison vide. */
|
||||
await utilisateur.selectOptions(selectService, 'Fournisseur');
|
||||
|
||||
await waitFor(() => expect(selectCategorie.value).toBe(''));
|
||||
});
|
||||
|
||||
it('interroge l’API avec les filtres sélectionnés', async () => {
|
||||
const utilisateur = userEvent.setup();
|
||||
renduDashboard();
|
||||
|
||||
const selectService = await screen.findByDisplayValue('Tous les services');
|
||||
await utilisateur.selectOptions(selectService, 'Contrat');
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.getDashboard).toHaveBeenLastCalledWith('Contrat', '');
|
||||
});
|
||||
});
|
||||
|
||||
it('affiche les KPI renvoyés par l’API', async () => {
|
||||
renduDashboard();
|
||||
expect(await screen.findByText('12')).toBeInTheDocument();
|
||||
expect(screen.getByText('Total erreurs')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
/* Accessibilité des composants transverses.
|
||||
|
||||
Le dossier affirme que les boîtes de dialogue piègent le focus et que les
|
||||
messages dynamiques sont annoncés aux lecteurs d'écran. Ces tests rendent ces
|
||||
affirmations vérifiables : elles étaient auparavant invalidables autrement
|
||||
qu'en relisant le code. */
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import Modal from '../components/common/Modal';
|
||||
import ErrorMessage from '../components/common/ErrorMessage';
|
||||
import LoadingSpinner from '../components/common/LoadingSpinner';
|
||||
|
||||
function ouvrirModale(onClose = () => {}) {
|
||||
return render(
|
||||
<Modal isOpen onClose={onClose} title="Modifier le service">
|
||||
<input aria-label="Nom" />
|
||||
<button>Enregistrer</button>
|
||||
</Modal>,
|
||||
);
|
||||
}
|
||||
|
||||
describe('Modal — accessibilité', () => {
|
||||
it('est exposée comme boîte de dialogue modale', () => {
|
||||
ouvrirModale();
|
||||
const dialogue = screen.getByRole('dialog');
|
||||
expect(dialogue).toHaveAttribute('aria-modal', 'true');
|
||||
});
|
||||
|
||||
it('est nommée par son titre', () => {
|
||||
ouvrirModale();
|
||||
/* Le lecteur d'écran doit annoncer de quoi parle la modale. */
|
||||
expect(screen.getByRole('dialog', { name: 'Modifier le service' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('place le focus sur le premier champ à l’ouverture', () => {
|
||||
ouvrirModale();
|
||||
expect(screen.getByLabelText('Nom')).toHaveFocus();
|
||||
});
|
||||
|
||||
it('referme la modale à la touche Échap', async () => {
|
||||
const onClose = vi.fn();
|
||||
const utilisateur = userEvent.setup();
|
||||
ouvrirModale(onClose);
|
||||
|
||||
await utilisateur.keyboard('{Escape}');
|
||||
expect(onClose).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('retient le focus à l’intérieur de la modale', async () => {
|
||||
const utilisateur = userEvent.setup();
|
||||
ouvrirModale();
|
||||
|
||||
/* Depuis le dernier élément, Tab doit revenir au premier et non filer
|
||||
vers la page située derrière. */
|
||||
const fermer = screen.getByRole('button', { name: 'Fermer' });
|
||||
fermer.focus();
|
||||
await utilisateur.tab();
|
||||
|
||||
expect(document.activeElement).not.toBe(document.body);
|
||||
expect(screen.getByRole('dialog').contains(document.activeElement)).toBe(true);
|
||||
});
|
||||
|
||||
it('n’affiche rien quand elle est fermée', () => {
|
||||
render(<Modal isOpen={false} onClose={() => {}} title="Titre">contenu</Modal>);
|
||||
expect(screen.queryByRole('dialog')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Messages dynamiques — annonce aux lecteurs d’écran', () => {
|
||||
it('annonce une erreur immédiatement', () => {
|
||||
render(<ErrorMessage message="Erreur 500 : service indisponible" />);
|
||||
const alerte = screen.getByRole('alert');
|
||||
expect(alerte).toHaveAttribute('aria-live', 'assertive');
|
||||
expect(alerte).toHaveTextContent('service indisponible');
|
||||
});
|
||||
|
||||
it('annonce le chargement sans interrompre la lecture', () => {
|
||||
render(<LoadingSpinner message="Chargement de l'historique..." />);
|
||||
const statut = screen.getByRole('status');
|
||||
expect(statut).toHaveAttribute('aria-live', 'polite');
|
||||
});
|
||||
|
||||
it('masque les éléments purement décoratifs', () => {
|
||||
/* L'animation du spinner n'apporte rien à l'oral : elle doit être ignorée. */
|
||||
const { container } = render(<LoadingSpinner />);
|
||||
expect(container.querySelector('[aria-hidden="true"]')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
/* Formatage des bornes de période de la page Historique.
|
||||
|
||||
Ces tests protègent une régression précise : la version d'origine utilisait
|
||||
toISOString(), qui convertit en UTC. Depuis un fuseau en avance sur UTC
|
||||
(Paris = UTC+1 en hiver), le 1er janvier local devient le 31 décembre de
|
||||
l'année précédente, et la période affichée est décalée d'un jour. */
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { formatDateISO, periodeParDefaut } from '../utils/dates';
|
||||
|
||||
describe('formatDateISO', () => {
|
||||
it('formate une date en YYYY-MM-DD', () => {
|
||||
expect(formatDateISO(new Date(2026, 7, 15))).toBe('2026-08-15');
|
||||
});
|
||||
|
||||
it('complète le mois et le jour à deux chiffres', () => {
|
||||
expect(formatDateISO(new Date(2026, 0, 5))).toBe('2026-01-05');
|
||||
});
|
||||
|
||||
it('ne décale pas la date à minuit en heure locale', () => {
|
||||
/* Le cas qui cassait : minuit local est la veille en UTC dès UTC+1. */
|
||||
const premierJanvierMinuit = new Date(2026, 0, 1, 0, 0, 0);
|
||||
expect(formatDateISO(premierJanvierMinuit)).toBe('2026-01-01');
|
||||
});
|
||||
|
||||
it('ne décale pas non plus en fin de journée', () => {
|
||||
/* Symétrique : 23h local bascule au lendemain pour les fuseaux négatifs. */
|
||||
const finDeJournee = new Date(2026, 11, 31, 23, 30, 0);
|
||||
expect(formatDateISO(finDeJournee)).toBe('2026-12-31');
|
||||
});
|
||||
});
|
||||
|
||||
describe('periodeParDefaut', () => {
|
||||
it('démarre au 1er janvier de l’année de la date fournie', () => {
|
||||
expect(periodeParDefaut(new Date(2026, 7, 15)).debut).toBe('2026-01-01');
|
||||
});
|
||||
|
||||
it('se termine à la date fournie', () => {
|
||||
expect(periodeParDefaut(new Date(2026, 7, 15)).fin).toBe('2026-08-15');
|
||||
});
|
||||
|
||||
it('reste cohérente le 1er janvier (début = fin)', () => {
|
||||
const periode = periodeParDefaut(new Date(2026, 0, 1));
|
||||
expect(periode.debut).toBe('2026-01-01');
|
||||
expect(periode.fin).toBe('2026-01-01');
|
||||
});
|
||||
|
||||
it('suit le changement d’année', () => {
|
||||
expect(periodeParDefaut(new Date(2027, 2, 9)).debut).toBe('2027-01-01');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
/* Export CSV, utilisé par les pages Vue consolidée, Contrat, Fournisseur,
|
||||
Historique et Détail monitoring. Les données exportées viennent de Sage et
|
||||
du CRM : elles contiennent des intitulés avec virgules et apostrophes, d'où
|
||||
l'importance de l'échappement. */
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { exportToCSV } from '../services/api';
|
||||
|
||||
/* Capture le contenu du Blob passé à URL.createObjectURL, sans télécharger. */
|
||||
function capturerCSV(data, filename) {
|
||||
let contenu = '';
|
||||
let nomFichier = '';
|
||||
|
||||
vi.stubGlobal('Blob', class {
|
||||
constructor(parties) { contenu = parties.join(''); }
|
||||
});
|
||||
vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:fake');
|
||||
vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {});
|
||||
vi.spyOn(document, 'createElement').mockReturnValue({
|
||||
set download(valeur) { nomFichier = valeur; },
|
||||
get download() { return nomFichier; },
|
||||
href: '',
|
||||
click: () => {},
|
||||
});
|
||||
|
||||
exportToCSV(data, filename);
|
||||
return { contenu, nomFichier };
|
||||
}
|
||||
|
||||
describe('exportToCSV', () => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('écrit une ligne d’en-têtes puis une ligne par enregistrement', () => {
|
||||
const { contenu } = capturerCSV(
|
||||
[{ nom: 'Tiers payeurs', erreurs: 5 }, { nom: 'DOM-TOM', erreurs: 3 }],
|
||||
'export.csv',
|
||||
);
|
||||
const lignes = contenu.split('\n');
|
||||
expect(lignes[0]).toBe('nom,erreurs');
|
||||
expect(lignes[1]).toBe('Tiers payeurs,5');
|
||||
expect(lignes[2]).toBe('DOM-TOM,3');
|
||||
});
|
||||
|
||||
it('entoure de guillemets une valeur contenant une virgule', () => {
|
||||
/* Sans échappement, la virgule créerait une colonne fantôme. */
|
||||
const { contenu } = capturerCSV([{ intitule: 'XEFI Lyon, agence Est' }], 'x.csv');
|
||||
expect(contenu.split('\n')[1]).toBe('"XEFI Lyon, agence Est"');
|
||||
});
|
||||
|
||||
it('double les guillemets internes', () => {
|
||||
const { contenu } = capturerCSV([{ intitule: 'Client "Test"' }], 'x.csv');
|
||||
expect(contenu.split('\n')[1]).toBe('"Client ""Test"""');
|
||||
});
|
||||
|
||||
it('protège une valeur contenant un saut de ligne', () => {
|
||||
const { contenu } = capturerCSV([{ adresse: 'Ligne 1\nLigne 2' }], 'x.csv');
|
||||
expect(contenu).toContain('"Ligne 1\nLigne 2"');
|
||||
});
|
||||
|
||||
it('rend les valeurs nulles ou absentes par une cellule vide', () => {
|
||||
const { contenu } = capturerCSV([{ a: null, b: undefined, c: 'ok' }], 'x.csv');
|
||||
expect(contenu.split('\n')[1]).toBe(',,ok');
|
||||
});
|
||||
|
||||
it('conserve le zéro au lieu de le traiter comme une valeur vide', () => {
|
||||
/* 0 est falsy : un test de vérité naïf l’effacerait alors que
|
||||
« 0 erreur » est justement l’information utile. */
|
||||
const { contenu } = capturerCSV([{ nb_erreurs: 0 }], 'x.csv');
|
||||
expect(contenu.split('\n')[1]).toBe('0');
|
||||
});
|
||||
|
||||
it('utilise le nom de fichier demandé', () => {
|
||||
const { nomFichier } = capturerCSV([{ a: 1 }], 'historique_2026.csv');
|
||||
expect(nomFichier).toBe('historique_2026.csv');
|
||||
});
|
||||
|
||||
it('n’exporte rien si la liste est vide', () => {
|
||||
const creerElement = vi.spyOn(document, 'createElement');
|
||||
exportToCSV([], 'vide.csv');
|
||||
expect(creerElement).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
/* Règle métier de classement d'un monitoring selon son nombre d'erreurs.
|
||||
Elle était dupliquée dans trois composants avant d'être centralisée : ces
|
||||
tests fixent le contrat pour que les trois écrans restent cohérents. */
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { getStatutMonitoring, SEUIL_ATTENTION } from '../utils/statutMonitoring';
|
||||
|
||||
describe('getStatutMonitoring', () => {
|
||||
it('classe OK un monitoring sans erreur', () => {
|
||||
expect(getStatutMonitoring(0).label).toBe('OK');
|
||||
expect(getStatutMonitoring(0).variant).toBe('ok');
|
||||
});
|
||||
|
||||
it('classe Attention en dessous du seuil', () => {
|
||||
expect(getStatutMonitoring(1).label).toBe('Attention');
|
||||
expect(getStatutMonitoring(SEUIL_ATTENTION - 1).label).toBe('Attention');
|
||||
});
|
||||
|
||||
it('bascule en Critique à partir du seuil, pas avant', () => {
|
||||
/* La borne est le point où une erreur de type < / <= se verrait. */
|
||||
expect(getStatutMonitoring(SEUIL_ATTENTION - 1).label).toBe('Attention');
|
||||
expect(getStatutMonitoring(SEUIL_ATTENTION).label).toBe('Critique');
|
||||
expect(getStatutMonitoring(SEUIL_ATTENTION + 1).label).toBe('Critique');
|
||||
});
|
||||
|
||||
it('fournit toujours un libellé, une variante et une couleur', () => {
|
||||
for (const nb of [0, 5, 50]) {
|
||||
const statut = getStatutMonitoring(nb);
|
||||
expect(statut.label).toBeTruthy();
|
||||
expect(statut.variant).toBeTruthy();
|
||||
expect(statut.color).toMatch(/^var\(--/);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
/* En-tête fixe de l'application Data Sentinel */
|
||||
|
||||
import { Bell, LogOut, Menu } from 'lucide-react';
|
||||
import { useAuth } from '../../context/AuthContext';
|
||||
import { useAuth } from '../../context/useAuth';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import styles from './Header.module.css';
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
FileText,
|
||||
ScrollText,
|
||||
} from 'lucide-react';
|
||||
import { useAuth } from '../../context/AuthContext';
|
||||
import { useAuth } from '../../context/useAuth';
|
||||
import styles from './Sidebar.module.css';
|
||||
|
||||
/* Un lien de navigation avec icône */
|
||||
|
||||
@@ -4,9 +4,12 @@ import { AlertCircle } from 'lucide-react';
|
||||
import styles from './ErrorMessage.module.css';
|
||||
|
||||
export default function ErrorMessage({ message = 'Une erreur est survenue.', onRetry }) {
|
||||
/* role="alert" annonce l'erreur immédiatement au lecteur d'écran : elle
|
||||
apparaît après le chargement de la page, sans quoi elle passerait
|
||||
inaperçue pour un utilisateur non voyant. */
|
||||
return (
|
||||
<div className={styles.container}>
|
||||
<AlertCircle size={20} color="var(--color-primary)" />
|
||||
<div className={styles.container} role="alert" aria-live="assertive">
|
||||
<AlertCircle size={20} color="var(--color-primary)" aria-hidden="true" />
|
||||
<p className={styles.text}>{message}</p>
|
||||
{onRetry && (
|
||||
<button className={styles.retryBtn} onClick={onRetry}>
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import styles from './KpiCard.module.css';
|
||||
|
||||
export default function KpiCard({ label, value, color }) {
|
||||
return (
|
||||
<div className={styles.kpiCard}>
|
||||
<span className={styles.kpiValue} style={{ color }}>{value}</span>
|
||||
<span className={styles.kpiLabel}>{label}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
.kpiCard {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
padding: 20px;
|
||||
background: var(--color-white);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
.kpiValue {
|
||||
font-size: 36px;
|
||||
font-weight: 700;
|
||||
line-height: 1;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.kpiLabel {
|
||||
font-size: 12px;
|
||||
color: var(--color-muted, #888);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.kpiValue {
|
||||
font-size: 28px;
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,11 @@
|
||||
import styles from './LoadingSpinner.module.css';
|
||||
|
||||
export default function LoadingSpinner({ message = 'Chargement...' }) {
|
||||
/* aria-live="polite" fait annoncer la fin du chargement sans interrompre la
|
||||
lecture en cours ; l'animation elle-même n'apporte rien à l'oral. */
|
||||
return (
|
||||
<div className={styles.container}>
|
||||
<div className={styles.spinner} />
|
||||
<div className={styles.container} role="status" aria-live="polite">
|
||||
<div className={styles.spinner} aria-hidden="true" />
|
||||
{message && <p className={styles.message}>{message}</p>}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import { useEffect, useId, useRef } from 'react';
|
||||
import styles from './Modal.module.css';
|
||||
|
||||
/* Sélecteur des éléments qui peuvent recevoir le focus au clavier. */
|
||||
const ELEMENTS_FOCUSABLES =
|
||||
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])';
|
||||
|
||||
export default function Modal({ isOpen, onClose, title, children }) {
|
||||
const conteneur = useRef(null);
|
||||
/* useId fournit un identifiant stable et unique par instance, sans tirage
|
||||
aléatoire pendant le rendu et sans collision si deux modales coexistent. */
|
||||
const titreId = useId();
|
||||
|
||||
/* Piège le focus dans la modale et gère la touche Échap.
|
||||
Sans cela, la tabulation continue de parcourir la page située derrière,
|
||||
ce qui rend la boîte de dialogue inutilisable au clavier. */
|
||||
useEffect(() => {
|
||||
if (!isOpen) return undefined;
|
||||
|
||||
const elementActifAvant = document.activeElement;
|
||||
/* On vise d'abord le contenu : sur une modale de formulaire, ouvrir sur le
|
||||
premier champ évite à l'utilisateur une tabulation inutile. À défaut, on
|
||||
se rabat sur le premier élément focusable, souvent le bouton de fermeture. */
|
||||
const corps = conteneur.current?.querySelector(`.${styles.modalBody}`);
|
||||
const premier = corps?.querySelector(ELEMENTS_FOCUSABLES)
|
||||
?? conteneur.current?.querySelector(ELEMENTS_FOCUSABLES);
|
||||
premier?.focus();
|
||||
|
||||
function handleKeyDown(evenement) {
|
||||
if (evenement.key === 'Escape') {
|
||||
onClose();
|
||||
return;
|
||||
}
|
||||
if (evenement.key !== 'Tab') return;
|
||||
|
||||
const focusables = conteneur.current?.querySelectorAll(ELEMENTS_FOCUSABLES);
|
||||
if (!focusables?.length) return;
|
||||
|
||||
const premier = focusables[0];
|
||||
const dernier = focusables[focusables.length - 1];
|
||||
|
||||
if (evenement.shiftKey && document.activeElement === premier) {
|
||||
evenement.preventDefault();
|
||||
dernier.focus();
|
||||
} else if (!evenement.shiftKey && document.activeElement === dernier) {
|
||||
evenement.preventDefault();
|
||||
premier.focus();
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('keydown', handleKeyDown);
|
||||
return () => {
|
||||
document.removeEventListener('keydown', handleKeyDown);
|
||||
elementActifAvant?.focus?.();
|
||||
};
|
||||
}, [isOpen, onClose]);
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
return (
|
||||
<div className={styles.modalOverlay} onClick={onClose}>
|
||||
<div
|
||||
className={styles.modal}
|
||||
ref={conteneur}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby={titreId}
|
||||
onClick={e => e.stopPropagation()}
|
||||
>
|
||||
<div className={styles.modalHeader}>
|
||||
<h2 id={titreId}>{title}</h2>
|
||||
<button className={styles.closeBtn} onClick={onClose} aria-label="Fermer">×</button>
|
||||
</div>
|
||||
<div className={styles.modalBody}>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
.modalOverlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background-color: rgba(0, 0, 0, 0.6);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 1000;
|
||||
}
|
||||
|
||||
.modal {
|
||||
background-color: var(--color-white);
|
||||
border-radius: var(--radius);
|
||||
border-top: 4px solid var(--color-primary);
|
||||
width: 90%;
|
||||
max-width: 500px;
|
||||
max-height: 80vh;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.modalHeader {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 20px 24px;
|
||||
border-bottom: 1px solid var(--color-gray-border);
|
||||
}
|
||||
|
||||
.modalHeader h2 {
|
||||
margin: 0;
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.closeBtn {
|
||||
background: none;
|
||||
border: none;
|
||||
font-size: 24px;
|
||||
color: var(--color-text-secondary);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.modalBody {
|
||||
padding: 24px;
|
||||
}
|
||||
@@ -2,20 +2,14 @@
|
||||
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import Badge from './Badge';
|
||||
import { getStatutMonitoring } from '../../utils/statutMonitoring';
|
||||
import styles from './MonitoringCard.module.css';
|
||||
|
||||
/* Détermine le statut visuel selon le nombre d'erreurs */
|
||||
function getStatut(nbErreurs) {
|
||||
if (nbErreurs === 0) return { label: 'OK', variant: 'ok', color: 'var(--color-ok)' };
|
||||
if (nbErreurs < 10) return { label: 'Attention', variant: 'warning', color: 'var(--color-warning)' };
|
||||
return { label: 'Critique', variant: 'critical', color: 'var(--color-primary)' };
|
||||
}
|
||||
|
||||
export default function MonitoringCard({ monitoring }) {
|
||||
const navigate = useNavigate();
|
||||
const nbErreurs = monitoring.nb_erreurs ?? monitoring.count ?? 0;
|
||||
const monitoringId = monitoring.id ?? monitoring.id_monito;
|
||||
const statut = getStatut(nbErreurs);
|
||||
const statut = getStatutMonitoring(nbErreurs);
|
||||
|
||||
/* Calcul du pourcentage de la barre de progression (max 100%) */
|
||||
const progressPct = Math.min((nbErreurs / 20) * 100, 100);
|
||||
|
||||
@@ -1,17 +1,15 @@
|
||||
/* Contexte d'authentification global : gestion de l'utilisateur connecté */
|
||||
|
||||
import { createContext, useContext, useState } from 'react';
|
||||
import { useState } from 'react';
|
||||
import * as api from '../services/api';
|
||||
|
||||
const AuthContext = createContext(null);
|
||||
|
||||
const STORAGE_KEY = 'ds_user';
|
||||
import { USER_KEY } from '../services/api';
|
||||
import { AuthContext } from './authContextObject';
|
||||
|
||||
/* Fournisseur du contexte d'authentification */
|
||||
export function AuthProvider({ children }) {
|
||||
const [user, setUser] = useState(() => {
|
||||
/* Restauration de la session depuis le localStorage au montage */
|
||||
const stored = localStorage.getItem(STORAGE_KEY);
|
||||
const stored = localStorage.getItem(USER_KEY);
|
||||
return stored ? JSON.parse(stored) : null;
|
||||
});
|
||||
|
||||
@@ -19,7 +17,7 @@ export function AuthProvider({ children }) {
|
||||
async function login(username, password) {
|
||||
const connectedUser = await api.login(username, password);
|
||||
setUser(connectedUser);
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(connectedUser));
|
||||
localStorage.setItem(USER_KEY, JSON.stringify(connectedUser));
|
||||
return connectedUser;
|
||||
}
|
||||
|
||||
@@ -27,7 +25,7 @@ export function AuthProvider({ children }) {
|
||||
function logout() {
|
||||
api.clearToken();
|
||||
setUser(null);
|
||||
localStorage.removeItem(STORAGE_KEY);
|
||||
localStorage.removeItem(USER_KEY);
|
||||
}
|
||||
|
||||
/* Booléen pratique pour savoir si l'utilisateur est connecté */
|
||||
@@ -40,11 +38,3 @@ export function AuthProvider({ children }) {
|
||||
);
|
||||
}
|
||||
|
||||
/* Hook personnalisé pour accéder au contexte d'authentification */
|
||||
export function useAuth() {
|
||||
const context = useContext(AuthContext);
|
||||
if (!context) {
|
||||
throw new Error('useAuth doit être utilisé dans un AuthProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
/* Objet de contexte isolé : un fichier qui exporte un composant ne doit
|
||||
exporter que des composants, sans quoi le rafraîchissement à chaud de Vite
|
||||
(react-refresh) cesse de fonctionner pour ce fichier. */
|
||||
|
||||
import { createContext } from 'react';
|
||||
|
||||
export const AuthContext = createContext(null);
|
||||
@@ -0,0 +1,15 @@
|
||||
/* Hook d'accès au contexte d'authentification.
|
||||
|
||||
Séparé de AuthContext.jsx : un fichier qui exporte à la fois un composant
|
||||
et autre chose casse le rafraîchissement à chaud de Vite (react-refresh). */
|
||||
|
||||
import { useContext } from 'react';
|
||||
import { AuthContext } from './authContextObject';
|
||||
|
||||
export function useAuth() {
|
||||
const context = useContext(AuthContext);
|
||||
if (!context) {
|
||||
throw new Error('useAuth doit être utilisé dans un AuthProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
/* Hook générique pour les appels API : retourne { data, loading, error, refetch } */
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
|
||||
/**
|
||||
* @param {Function} fetchFn - Fonction async à appeler (depuis api.js)
|
||||
* @param {Array} deps - Dépendances qui déclenchent un re-fetch (optionnel)
|
||||
*/
|
||||
export function useApi(fetchFn, deps = []) {
|
||||
const [data, setData] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
const fetch = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const result = await fetchFn();
|
||||
setData(result);
|
||||
} catch (err) {
|
||||
setError(err.message || 'Une erreur est survenue.');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, deps);
|
||||
|
||||
useEffect(() => {
|
||||
fetch();
|
||||
}, [fetch]);
|
||||
|
||||
return { data, loading, error, refetch: fetch };
|
||||
}
|
||||
@@ -1,229 +1,186 @@
|
||||
// src/pages/Admin/Admin.jsx
|
||||
// Page Administration : onglets pour gérer monitorings, services, catégories, contacts
|
||||
import { useState, useEffect } from 'react';
|
||||
// Page Administration : CRUD sur les référentiels (monitorings, services,
|
||||
// catégories, contacts). Réservée au rôle Admin côté API.
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { Plus, Edit, Trash2 } from 'lucide-react';
|
||||
import { getMonitorings, getServices, getCategories, getContacts } from '../../services/api';
|
||||
import DataTable from '../../components/common/DataTable';
|
||||
import LoadingSpinner from '../../components/common/LoadingSpinner';
|
||||
import ErrorMessage from '../../components/common/ErrorMessage';
|
||||
import Button from '../../components/common/Button';
|
||||
import Modal from '../../components/common/Modal';
|
||||
import ReferentielForm from './ReferentielForm';
|
||||
import { REFERENTIELS, LIBELLES_REFERENTIEL } from './referentielsConfig';
|
||||
import styles from './Admin.module.css';
|
||||
|
||||
/* Modale générique pour ajouter/modifier */
|
||||
function Modal({ isOpen, onClose, title, children }) {
|
||||
if (!isOpen) return null;
|
||||
|
||||
return (
|
||||
<div className={styles.modalOverlay} onClick={onClose}>
|
||||
<div className={styles.modal} onClick={e => e.stopPropagation()}>
|
||||
<div className={styles.modalHeader}>
|
||||
<h2>{title}</h2>
|
||||
<button className={styles.closeBtn} onClick={onClose}>×</button>
|
||||
</div>
|
||||
<div className={styles.modalBody}>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
async function chargerReferentiels() {
|
||||
const [monitorings, services, categories, contacts] = await Promise.all([
|
||||
getMonitorings(),
|
||||
getServices(),
|
||||
getCategories(),
|
||||
getContacts(),
|
||||
]);
|
||||
return {
|
||||
monitorings: Array.isArray(monitorings) ? monitorings : [],
|
||||
services: Array.isArray(services) ? services : [],
|
||||
categories: Array.isArray(categories) ? categories : [],
|
||||
contacts: Array.isArray(contacts) ? contacts : [],
|
||||
};
|
||||
}
|
||||
|
||||
export default function Admin() {
|
||||
const [activeTab, setActiveTab] = useState('monitorings');
|
||||
const [data, setData] = useState({});
|
||||
const [ongletActif, setOngletActif] = useState(REFERENTIELS[0].key);
|
||||
const [donnees, setDonnees] = useState({});
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [erreur, setErreur] = useState('');
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [editingItem, setEditingItem] = useState(null);
|
||||
const [modaleOuverte, setModaleOuverte] = useState(false);
|
||||
const [elementEnEdition, setElementEnEdition] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
async function loadData() {
|
||||
setLoading(true);
|
||||
setErreur('');
|
||||
try {
|
||||
const [monitorings, services, categories, contacts] = await Promise.all([
|
||||
getMonitorings(),
|
||||
getServices(),
|
||||
getCategories(),
|
||||
getContacts()
|
||||
]);
|
||||
setData({
|
||||
monitorings: Array.isArray(monitorings) ? monitorings : [],
|
||||
services: Array.isArray(services) ? services : [],
|
||||
categories: Array.isArray(categories) ? categories : [],
|
||||
contacts: Array.isArray(contacts) ? contacts : []
|
||||
});
|
||||
} catch (e) {
|
||||
setErreur(e.message || 'Erreur lors du chargement des données administratives.');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
const recharger = useCallback(async () => {
|
||||
setErreur('');
|
||||
try {
|
||||
setDonnees(await chargerReferentiels());
|
||||
} catch (e) {
|
||||
setErreur(e.message || 'Erreur lors du chargement des données administratives.');
|
||||
}
|
||||
loadData();
|
||||
}, []);
|
||||
|
||||
function handleAdd() {
|
||||
setEditingItem(null);
|
||||
setModalOpen(true);
|
||||
useEffect(() => {
|
||||
let annule = false;
|
||||
async function chargerAuMontage() {
|
||||
try {
|
||||
const resultat = await chargerReferentiels();
|
||||
if (!annule) setDonnees(resultat);
|
||||
} catch (e) {
|
||||
if (!annule) setErreur(e.message || 'Erreur lors du chargement des données administratives.');
|
||||
} finally {
|
||||
if (!annule) setLoading(false);
|
||||
}
|
||||
}
|
||||
chargerAuMontage();
|
||||
return () => { annule = true; };
|
||||
}, []);
|
||||
|
||||
const referentiel = REFERENTIELS.find(r => r.key === ongletActif);
|
||||
|
||||
function ouvrirCreation() {
|
||||
setElementEnEdition(null);
|
||||
setModaleOuverte(true);
|
||||
}
|
||||
|
||||
function handleEdit(item) {
|
||||
setEditingItem(item);
|
||||
setModalOpen(true);
|
||||
function ouvrirEdition(element) {
|
||||
setElementEnEdition(element);
|
||||
setModaleOuverte(true);
|
||||
}
|
||||
|
||||
function handleDelete(item) {
|
||||
// Simulation de suppression (pas d'API pour ça)
|
||||
console.log('Supprimer', item);
|
||||
async function handleEnregistrer(corps) {
|
||||
if (elementEnEdition) {
|
||||
await referentiel.modifier(elementEnEdition[referentiel.idField], corps);
|
||||
} else {
|
||||
await referentiel.creer(corps);
|
||||
}
|
||||
setModaleOuverte(false);
|
||||
await recharger();
|
||||
}
|
||||
|
||||
const tabs = [
|
||||
{ key: 'monitorings', label: 'Monitorings' },
|
||||
{ key: 'services', label: 'Services' },
|
||||
{ key: 'categories', label: 'Catégories' },
|
||||
{ key: 'contacts', label: 'Contacts' }
|
||||
async function handleSupprimer(element) {
|
||||
const action = referentiel.suppressionEstDesactivation ? 'Désactiver' : 'Supprimer';
|
||||
const nom = element[referentiel.colonnes[0].key];
|
||||
if (!window.confirm(`${action} « ${nom} » ?`)) return;
|
||||
|
||||
setErreur('');
|
||||
try {
|
||||
await referentiel.supprimer(element[referentiel.idField]);
|
||||
await recharger();
|
||||
} catch (e) {
|
||||
setErreur(e.message || 'La suppression a échoué.');
|
||||
}
|
||||
}
|
||||
|
||||
/* Affiche le libellé d'un référentiel lié plutôt que son identifiant brut. */
|
||||
function libelleLie(nomReferentiel, id) {
|
||||
const { idField, labelField } = LIBELLES_REFERENTIEL[nomReferentiel];
|
||||
const trouve = (donnees[nomReferentiel] || []).find(item => item[idField] === id);
|
||||
return trouve ? trouve[labelField] : id;
|
||||
}
|
||||
|
||||
const colonnes = [
|
||||
...referentiel.colonnes.map(colonne => ({
|
||||
key: colonne.key,
|
||||
label: colonne.label,
|
||||
render: colonne.referentiel
|
||||
? val => libelleLie(colonne.referentiel, val)
|
||||
: undefined,
|
||||
})),
|
||||
{
|
||||
key: 'actions',
|
||||
label: 'Actions',
|
||||
render: (val, row) => (
|
||||
<div className={styles.actions}>
|
||||
<button className={styles.actionBtn} onClick={() => ouvrirEdition(row)}>
|
||||
<Edit size={14} />
|
||||
Modifier
|
||||
</button>
|
||||
<button className={styles.actionBtn} onClick={() => handleSupprimer(row)}>
|
||||
<Trash2 size={14} />
|
||||
{referentiel.suppressionEstDesactivation ? 'Désactiver' : 'Supprimer'}
|
||||
</button>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
const columns = {
|
||||
monitorings: [
|
||||
{ key: 'monito_intitule', label: 'Nom' },
|
||||
{ key: 'id_service', label: 'Service' },
|
||||
{ key: 'id_categorie', label: 'Catégorie' },
|
||||
{ key: 'bdd_source', label: 'Source' },
|
||||
{ key: 'table_source', label: 'Table' },
|
||||
{
|
||||
key: 'actions',
|
||||
label: 'Actions',
|
||||
render: (val, row) => (
|
||||
<div className={styles.actions}>
|
||||
<button className={styles.actionBtn} onClick={() => handleEdit(row)}>
|
||||
<Edit size={14} />
|
||||
Modifier
|
||||
</button>
|
||||
<button className={styles.actionBtn} onClick={() => handleDelete(row)}>
|
||||
<Trash2 size={14} />
|
||||
Désactiver
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
],
|
||||
services: [
|
||||
{ key: 'nom_service', label: 'Nom' },
|
||||
{
|
||||
key: 'actions',
|
||||
label: 'Actions',
|
||||
render: (val, row) => (
|
||||
<div className={styles.actions}>
|
||||
<button className={styles.actionBtn} onClick={() => handleEdit(row)}>
|
||||
<Edit size={14} />
|
||||
Modifier
|
||||
</button>
|
||||
<button className={styles.actionBtn} onClick={() => handleDelete(row)}>
|
||||
<Trash2 size={14} />
|
||||
Désactiver
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
],
|
||||
categories: [
|
||||
{ key: 'intitule_categorie', label: 'Nom' },
|
||||
{
|
||||
key: 'actions',
|
||||
label: 'Actions',
|
||||
render: (val, row) => (
|
||||
<div className={styles.actions}>
|
||||
<button className={styles.actionBtn} onClick={() => handleEdit(row)}>
|
||||
<Edit size={14} />
|
||||
Modifier
|
||||
</button>
|
||||
<button className={styles.actionBtn} onClick={() => handleDelete(row)}>
|
||||
<Trash2 size={14} />
|
||||
Désactiver
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
],
|
||||
contacts: [
|
||||
{ key: 'intitule_contact', label: 'Intitulé' },
|
||||
{ key: 'nom', label: 'Nom' },
|
||||
{ key: 'prenom', label: 'Prénom' },
|
||||
{ key: 'mail', label: 'Email' },
|
||||
{ key: 'id_service', label: 'Service' },
|
||||
{
|
||||
key: 'actions',
|
||||
label: 'Actions',
|
||||
render: (val, row) => (
|
||||
<div className={styles.actions}>
|
||||
<button className={styles.actionBtn} onClick={() => handleEdit(row)}>
|
||||
<Edit size={14} />
|
||||
Modifier
|
||||
</button>
|
||||
<button className={styles.actionBtn} onClick={() => handleDelete(row)}>
|
||||
<Trash2 size={14} />
|
||||
Désactiver
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
if (loading) return <LoadingSpinner message="Chargement des données administratives..." />;
|
||||
if (erreur) return <ErrorMessage message={erreur} />;
|
||||
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
<h1 className={styles.title}>Administration</h1>
|
||||
|
||||
{/* Onglets */}
|
||||
<div className={styles.tabs}>
|
||||
{tabs.map(tab => (
|
||||
{REFERENTIELS.map(item => (
|
||||
<button
|
||||
key={tab.key}
|
||||
className={`${styles.tab} ${activeTab === tab.key ? styles.active : ''}`}
|
||||
onClick={() => setActiveTab(tab.key)}
|
||||
key={item.key}
|
||||
className={`${styles.tab} ${ongletActif === item.key ? styles.active : ''}`}
|
||||
onClick={() => setOngletActif(item.key)}
|
||||
>
|
||||
{tab.label}
|
||||
{item.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Contenu de l'onglet actif */}
|
||||
{erreur && <ErrorMessage message={erreur} />}
|
||||
|
||||
<div className={styles.tabContent}>
|
||||
<div className={styles.header}>
|
||||
<h2>{tabs.find(t => t.key === activeTab)?.label}</h2>
|
||||
<Button variant="primary" onClick={handleAdd}>
|
||||
<h2>{referentiel.label}</h2>
|
||||
<Button variant="primary" onClick={ouvrirCreation}>
|
||||
<Plus size={14} />
|
||||
Ajouter
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
columns={columns[activeTab]}
|
||||
data={data[activeTab] || []}
|
||||
columns={colonnes}
|
||||
data={donnees[ongletActif] || []}
|
||||
pageSize={50}
|
||||
emptyMessage={`Aucun ${activeTab.slice(0, -1)} trouvé.`}
|
||||
emptyMessage={`Aucun ${referentiel.singulier} trouvé.`}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Modale */}
|
||||
<Modal
|
||||
isOpen={modalOpen}
|
||||
onClose={() => setModalOpen(false)}
|
||||
title={`${editingItem ? 'Modifier' : 'Ajouter'} ${tabs.find(t => t.key === activeTab)?.label.slice(0, -1)}`}
|
||||
isOpen={modaleOuverte}
|
||||
onClose={() => setModaleOuverte(false)}
|
||||
title={`${elementEnEdition ? 'Modifier' : 'Ajouter'} ${referentiel.singulier}`}
|
||||
>
|
||||
<p>Formulaire à implémenter selon les besoins.</p>
|
||||
<div className={styles.modalActions}>
|
||||
<Button variant="secondary" onClick={() => setModalOpen(false)}>
|
||||
Annuler
|
||||
</Button>
|
||||
<Button variant="primary" onClick={() => setModalOpen(false)}>
|
||||
Enregistrer
|
||||
</Button>
|
||||
</div>
|
||||
<ReferentielForm
|
||||
/* Remonte le formulaire à zéro quand on change d'onglet ou d'élément */
|
||||
key={`${referentiel.key}-${elementEnEdition?.[referentiel.idField] ?? 'nouveau'}`}
|
||||
referentiel={referentiel}
|
||||
valeurInitiale={elementEnEdition}
|
||||
donnees={donnees}
|
||||
onEnregistrer={handleEnregistrer}
|
||||
onAnnuler={() => setModaleOuverte(false)}
|
||||
/>
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -83,55 +83,33 @@
|
||||
color: var(--color-primary);
|
||||
}
|
||||
|
||||
/* Modale */
|
||||
.modalOverlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background-color: rgba(0, 0, 0, 0.6);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 1000;
|
||||
/* Formulaire de la modale (le conteneur vit dans Modal.module.css) */
|
||||
.field {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.modal {
|
||||
background-color: var(--color-white);
|
||||
border-radius: var(--radius);
|
||||
border-top: 4px solid var(--color-primary);
|
||||
width: 90%;
|
||||
max-width: 500px;
|
||||
max-height: 80vh;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.modalHeader {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 20px 24px;
|
||||
border-bottom: 1px solid var(--color-gray-border);
|
||||
}
|
||||
|
||||
.modalHeader h2 {
|
||||
margin: 0;
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
.label {
|
||||
display: block;
|
||||
margin-bottom: 6px;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.closeBtn {
|
||||
background: none;
|
||||
border: none;
|
||||
font-size: 24px;
|
||||
color: var(--color-text-secondary);
|
||||
cursor: pointer;
|
||||
.input {
|
||||
width: 100%;
|
||||
padding: 8px 12px;
|
||||
border: 1px solid var(--color-gray-border);
|
||||
border-radius: var(--radius);
|
||||
font-size: 14px;
|
||||
font-family: inherit;
|
||||
color: var(--color-text);
|
||||
background-color: var(--color-white);
|
||||
}
|
||||
|
||||
.modalBody {
|
||||
padding: 24px;
|
||||
.input:focus {
|
||||
outline: 2px solid var(--color-primary);
|
||||
outline-offset: -1px;
|
||||
}
|
||||
|
||||
.modalActions {
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import { useState } from 'react';
|
||||
import Button from '../../components/common/Button';
|
||||
import ErrorMessage from '../../components/common/ErrorMessage';
|
||||
import { LIBELLES_REFERENTIEL } from './referentielsConfig';
|
||||
import styles from './Admin.module.css';
|
||||
|
||||
/* Formulaire générique piloté par la description des champs du référentiel
|
||||
(voir referentielsConfig.js) : les 4 onglets partagent ce composant. */
|
||||
export default function ReferentielForm({ referentiel, valeurInitiale, donnees, onEnregistrer, onAnnuler }) {
|
||||
const [valeurs, setValeurs] = useState(() =>
|
||||
Object.fromEntries(
|
||||
referentiel.champs.map(champ => [champ.name, valeurInitiale?.[champ.name] ?? ''])
|
||||
)
|
||||
);
|
||||
const [enCours, setEnCours] = useState(false);
|
||||
const [erreur, setErreur] = useState('');
|
||||
|
||||
function handleChange(name, valeur) {
|
||||
setValeurs(precedentes => ({ ...precedentes, [name]: valeur }));
|
||||
}
|
||||
|
||||
async function handleSubmit(event) {
|
||||
event.preventDefault();
|
||||
setErreur('');
|
||||
setEnCours(true);
|
||||
try {
|
||||
/* Les identifiants de référentiel arrivent en chaîne depuis <select> :
|
||||
l'API attend des entiers. */
|
||||
const corps = Object.fromEntries(
|
||||
referentiel.champs.map(champ => [
|
||||
champ.name,
|
||||
champ.type === 'select' ? Number(valeurs[champ.name]) : valeurs[champ.name],
|
||||
])
|
||||
);
|
||||
await onEnregistrer(corps);
|
||||
} catch (e) {
|
||||
setErreur(e.message || "L'enregistrement a échoué.");
|
||||
} finally {
|
||||
setEnCours(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit}>
|
||||
{referentiel.champs.map(champ => (
|
||||
<div key={champ.name} className={styles.field}>
|
||||
<label className={styles.label} htmlFor={champ.name}>{champ.label}</label>
|
||||
{champ.type === 'select' ? (
|
||||
<select
|
||||
id={champ.name}
|
||||
className={styles.input}
|
||||
value={valeurs[champ.name]}
|
||||
onChange={e => handleChange(champ.name, e.target.value)}
|
||||
required={champ.required}
|
||||
>
|
||||
<option value="">— Choisir —</option>
|
||||
{(donnees[champ.options] || []).map(option => {
|
||||
const { idField, labelField } = LIBELLES_REFERENTIEL[champ.options];
|
||||
return (
|
||||
<option key={option[idField]} value={option[idField]}>
|
||||
{option[labelField]}
|
||||
</option>
|
||||
);
|
||||
})}
|
||||
</select>
|
||||
) : (
|
||||
<input
|
||||
id={champ.name}
|
||||
type={champ.type}
|
||||
className={styles.input}
|
||||
value={valeurs[champ.name]}
|
||||
onChange={e => handleChange(champ.name, e.target.value)}
|
||||
required={champ.required}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
|
||||
{erreur && <ErrorMessage message={erreur} />}
|
||||
|
||||
<div className={styles.modalActions}>
|
||||
<Button variant="secondary" type="button" onClick={onAnnuler} disabled={enCours}>
|
||||
Annuler
|
||||
</Button>
|
||||
<Button variant="primary" type="submit" disabled={enCours}>
|
||||
{enCours ? 'Enregistrement…' : 'Enregistrer'}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
/* Les appels API sont référencés via l'espace de noms et résolus au moment de
|
||||
l'appel, et non capturés à l'import : la configuration ne fige donc pas une
|
||||
implémentation, ce qui la découple du module d'API. */
|
||||
import * as api from '../../services/api';
|
||||
|
||||
/* Description déclarative des 4 référentiels administrables.
|
||||
Les colonnes du tableau, les champs du formulaire et les appels API sont
|
||||
décrits ici plutôt que répétés onglet par onglet : les 4 onglets partagent
|
||||
ainsi un seul tableau et un seul formulaire. */
|
||||
export const REFERENTIELS = [
|
||||
{
|
||||
key: 'monitorings',
|
||||
label: 'Monitorings',
|
||||
singulier: 'monitoring',
|
||||
idField: 'id_monito',
|
||||
/* Désactivation logique : TABLE_FINAL référence le monitoring. */
|
||||
suppressionEstDesactivation: true,
|
||||
colonnes: [
|
||||
{ key: 'monito_intitule', label: 'Nom' },
|
||||
{ key: 'id_service', label: 'Service', referentiel: 'services' },
|
||||
{ key: 'id_categorie', label: 'Catégorie', referentiel: 'categories' },
|
||||
{ key: 'bdd_source', label: 'Source' },
|
||||
{ key: 'table_source', label: 'Table' },
|
||||
],
|
||||
champs: [
|
||||
{ name: 'monito_intitule', label: 'Nom', type: 'text', required: true },
|
||||
{ name: 'id_service', label: 'Service', type: 'select', options: 'services', required: true },
|
||||
{ name: 'id_categorie', label: 'Catégorie', type: 'select', options: 'categories', required: true },
|
||||
{ name: 'table_source', label: 'Table source', type: 'text', required: true },
|
||||
{ name: 'bdd_source', label: 'Base source', type: 'text', required: true },
|
||||
],
|
||||
creer: body => api.createMonitoring(body),
|
||||
modifier: (id, body) => api.updateMonitoring(id, body),
|
||||
supprimer: id => api.desactiverMonitoring(id),
|
||||
},
|
||||
{
|
||||
key: 'services',
|
||||
label: 'Services',
|
||||
singulier: 'service',
|
||||
idField: 'id_service',
|
||||
colonnes: [{ key: 'nom_service', label: 'Nom' }],
|
||||
champs: [{ name: 'nom_service', label: 'Nom du service', type: 'text', required: true }],
|
||||
creer: body => api.createService(body),
|
||||
modifier: (id, body) => api.updateService(id, body),
|
||||
supprimer: id => api.deleteService(id),
|
||||
},
|
||||
{
|
||||
key: 'categories',
|
||||
label: 'Catégories',
|
||||
singulier: 'catégorie',
|
||||
idField: 'id_categorie',
|
||||
colonnes: [{ key: 'intitule_categorie', label: 'Nom' }],
|
||||
champs: [{ name: 'intitule_categorie', label: 'Intitulé', type: 'text', required: true }],
|
||||
creer: body => api.createCategorie(body),
|
||||
modifier: (id, body) => api.updateCategorie(id, body),
|
||||
supprimer: id => api.deleteCategorie(id),
|
||||
},
|
||||
{
|
||||
key: 'contacts',
|
||||
label: 'Contacts',
|
||||
singulier: 'contact',
|
||||
idField: 'id_contact',
|
||||
colonnes: [
|
||||
{ key: 'intitule_contact', label: 'Intitulé' },
|
||||
{ key: 'nom', label: 'Nom' },
|
||||
{ key: 'prenom', label: 'Prénom' },
|
||||
{ key: 'mail', label: 'Email' },
|
||||
{ key: 'id_service', label: 'Service', referentiel: 'services' },
|
||||
],
|
||||
champs: [
|
||||
{ name: 'intitule_contact', label: 'Intitulé', type: 'text', required: true },
|
||||
{ name: 'nom', label: 'Nom', type: 'text', required: true },
|
||||
{ name: 'prenom', label: 'Prénom', type: 'text', required: true },
|
||||
{ name: 'mail', label: 'Email', type: 'email', required: true },
|
||||
{ name: 'id_service', label: 'Service', type: 'select', options: 'services', required: true },
|
||||
],
|
||||
creer: body => api.createContact(body),
|
||||
modifier: (id, body) => api.updateContact(id, body),
|
||||
supprimer: id => api.deleteContact(id),
|
||||
},
|
||||
];
|
||||
|
||||
/* Libellés des listes déroulantes et des colonnes qui affichent un identifiant. */
|
||||
export const LIBELLES_REFERENTIEL = {
|
||||
services: { idField: 'id_service', labelField: 'nom_service' },
|
||||
categories: { idField: 'id_categorie', labelField: 'intitule_categorie' },
|
||||
};
|
||||
@@ -4,20 +4,11 @@ import { useState, useEffect, useCallback, useMemo } from 'react';
|
||||
import { RefreshCw } from 'lucide-react';
|
||||
import { getDashboard, getDashboardSummary, getDashboardFiltres } from '../../services/api';
|
||||
import MonitoringCard from '../../components/common/MonitoringCard';
|
||||
import KpiCard from '../../components/common/KpiCard';
|
||||
import LoadingSpinner from '../../components/common/LoadingSpinner';
|
||||
import ErrorMessage from '../../components/common/ErrorMessage';
|
||||
import styles from './Dashboard.module.css';
|
||||
|
||||
/* Carte KPI affichant un indicateur clé */
|
||||
function KpiCard({ label, value, color }) {
|
||||
return (
|
||||
<div className={styles.kpiCard}>
|
||||
<span className={styles.kpiValue} style={{ color }}>{value}</span>
|
||||
<span className={styles.kpiLabel}>{label}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Dashboard() {
|
||||
const [summary, setSummary] = useState(null);
|
||||
const [monitorings, setMonitorings] = useState([]);
|
||||
@@ -27,6 +18,7 @@ export default function Dashboard() {
|
||||
const [filtreCategorie, setFiltreCategorie] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [erreur, setErreur] = useState('');
|
||||
const [rafraichissement, setRafraichissement] = useState(0);
|
||||
|
||||
/* Chargement initial des filtres.
|
||||
On n'utilise pas les référentiels SERVICE / CATEGORIE complets : ils
|
||||
@@ -61,39 +53,57 @@ export default function Dashboard() {
|
||||
/* Changer de service peut rendre la catégorie sélectionnée sans résultat :
|
||||
on la remet à zéro dans le même rendu, pour ne déclencher qu'un seul appel. */
|
||||
function handleServiceChange(service) {
|
||||
setLoading(true);
|
||||
setFiltreService(service);
|
||||
if (filtreCategorie && !categoriesDisponibles(service).includes(filtreCategorie)) {
|
||||
setFiltreCategorie('');
|
||||
}
|
||||
}
|
||||
|
||||
/* Chargement des données dashboard */
|
||||
const loadData = useCallback(async () => {
|
||||
function handleCategorieChange(categorie) {
|
||||
setLoading(true);
|
||||
setErreur('');
|
||||
try {
|
||||
const [sum, data] = await Promise.all([
|
||||
getDashboardSummary(),
|
||||
getDashboard(filtreService, filtreCategorie),
|
||||
]);
|
||||
setSummary(sum);
|
||||
setMonitorings(Array.isArray(data) ? data : []);
|
||||
} catch (e) {
|
||||
setErreur(e.message || 'Erreur lors du chargement du dashboard.');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [filtreService, filtreCategorie]);
|
||||
setFiltreCategorie(categorie);
|
||||
}
|
||||
|
||||
/* Le bouton Actualiser relance l'effet en changeant cette valeur. */
|
||||
function handleActualiser() {
|
||||
setLoading(true);
|
||||
setRafraichissement(compteur => compteur + 1);
|
||||
}
|
||||
|
||||
/* Les données sont rechargées à chaque changement de filtre. L'indicateur de
|
||||
chargement est allumé par les gestionnaires d'événement ci-dessus, jamais
|
||||
dans l'effet : y appeler setState de façon synchrone provoquerait un rendu
|
||||
en cascade. */
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
}, [loadData]);
|
||||
let annule = false;
|
||||
|
||||
async function charger() {
|
||||
try {
|
||||
const [sum, data] = await Promise.all([
|
||||
getDashboardSummary(),
|
||||
getDashboard(filtreService, filtreCategorie),
|
||||
]);
|
||||
if (annule) return;
|
||||
setSummary(sum);
|
||||
setMonitorings(Array.isArray(data) ? data : []);
|
||||
setErreur('');
|
||||
} catch (e) {
|
||||
if (!annule) setErreur(e.message || 'Erreur lors du chargement du dashboard.');
|
||||
} finally {
|
||||
if (!annule) setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
charger();
|
||||
return () => { annule = true; };
|
||||
}, [filtreService, filtreCategorie, rafraichissement]);
|
||||
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
<div className={styles.pageHeader}>
|
||||
<h1 className={styles.title}>Dashboard</h1>
|
||||
<button className={styles.refreshBtn} onClick={loadData} disabled={loading}>
|
||||
<button className={styles.refreshBtn} onClick={handleActualiser} disabled={loading}>
|
||||
<RefreshCw size={14} className={loading ? styles.spinning : ''} />
|
||||
Actualiser
|
||||
</button>
|
||||
@@ -140,7 +150,7 @@ export default function Dashboard() {
|
||||
<select
|
||||
className={styles.select}
|
||||
value={filtreCategorie}
|
||||
onChange={e => setFiltreCategorie(e.target.value)}
|
||||
onChange={e => handleCategorieChange(e.target.value)}
|
||||
>
|
||||
<option value="">Toutes les catégories</option>
|
||||
{categories.map(c => (
|
||||
@@ -153,7 +163,7 @@ export default function Dashboard() {
|
||||
{loading ? (
|
||||
<LoadingSpinner message="Chargement du dashboard..." />
|
||||
) : erreur ? (
|
||||
<ErrorMessage message={erreur} onRetry={loadData} />
|
||||
<ErrorMessage message={erreur} onRetry={handleActualiser} />
|
||||
) : (
|
||||
<>
|
||||
{monitorings.length === 0 ? (
|
||||
|
||||
@@ -55,29 +55,6 @@
|
||||
margin-bottom: 32px;
|
||||
}
|
||||
|
||||
.kpiCard {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
padding: 20px;
|
||||
background: var(--color-white);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
.kpiValue {
|
||||
font-size: 36px;
|
||||
font-weight: 700;
|
||||
line-height: 1;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.kpiLabel {
|
||||
font-size: 12px;
|
||||
color: var(--color-muted, #888);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.filtres {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
@@ -131,10 +108,6 @@
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.kpiValue {
|
||||
font-size: 28px;
|
||||
}
|
||||
|
||||
.filtres {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// src/pages/Documentation/Documentation.jsx
|
||||
// Page documentation technique de Data Sentinel
|
||||
import { ExternalLink, Book, Code, Database, Shield } from 'lucide-react';
|
||||
import { Book, Code, Database, Shield } from 'lucide-react';
|
||||
import styles from './Documentation.module.css';
|
||||
|
||||
const sections = [
|
||||
|
||||
@@ -8,27 +8,9 @@ import DataTable from '../../components/common/DataTable';
|
||||
import LoadingSpinner from '../../components/common/LoadingSpinner';
|
||||
import ErrorMessage from '../../components/common/ErrorMessage';
|
||||
import Button from '../../components/common/Button';
|
||||
import { periodeParDefaut } from '../../utils/dates';
|
||||
import styles from './Historique.module.css';
|
||||
|
||||
/* Formate une date au format attendu par <input type="date"> (YYYY-MM-DD).
|
||||
On lit les composantes en heure locale plutôt que d'utiliser toISOString(),
|
||||
qui bascule en UTC : un 1er janvier saisi depuis Paris (UTC+1) y devient le
|
||||
31 décembre de l'année précédente. */
|
||||
function formatDateISO(date) {
|
||||
const mois = String(date.getMonth() + 1).padStart(2, '0');
|
||||
const jour = String(date.getDate()).padStart(2, '0');
|
||||
return `${date.getFullYear()}-${mois}-${jour}`;
|
||||
}
|
||||
|
||||
/* Période affichée par défaut : du 1er janvier de l'année courante à aujourd'hui. */
|
||||
function periodeParDefaut() {
|
||||
const aujourdhui = new Date();
|
||||
return {
|
||||
debut: formatDateISO(new Date(aujourdhui.getFullYear(), 0, 1)),
|
||||
fin: formatDateISO(aujourdhui),
|
||||
};
|
||||
}
|
||||
|
||||
/* Récupère le tableau d'historique et la série du graphique pour les filtres
|
||||
donnés. Sans monitoring sélectionné, on prend la courbe globale.
|
||||
Fonction pure : elle ne touche à aucun état, ce qui permet de l'appeler
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useAuth } from '../../context/AuthContext';
|
||||
import { useAuth } from '../../context/useAuth';
|
||||
import styles from './Login.module.css';
|
||||
|
||||
/* Génère deux entiers aléatoires pour le captcha additif */
|
||||
|
||||
@@ -9,15 +9,9 @@ import LoadingSpinner from '../../components/common/LoadingSpinner';
|
||||
import ErrorMessage from '../../components/common/ErrorMessage';
|
||||
import Badge from '../../components/common/Badge';
|
||||
import Button from '../../components/common/Button';
|
||||
import { getStatutMonitoring } from '../../utils/statutMonitoring';
|
||||
import styles from './MonitoringDetail.module.css';
|
||||
|
||||
/* Détermine le statut selon le nombre d'erreurs */
|
||||
function getStatut(nbErreurs) {
|
||||
if (nbErreurs === 0) return { label: 'OK', variant: 'ok' };
|
||||
if (nbErreurs < 10) return { label: 'Attention', variant: 'warning' };
|
||||
return { label: 'Critique', variant: 'critical' };
|
||||
}
|
||||
|
||||
export default function MonitoringDetail() {
|
||||
const { id } = useParams();
|
||||
const navigate = useNavigate();
|
||||
@@ -72,7 +66,7 @@ export default function MonitoringDetail() {
|
||||
if (loading) return <LoadingSpinner message="Chargement du monitoring..." />;
|
||||
if (erreur) return <ErrorMessage message={erreur} />;
|
||||
|
||||
const statut = getStatut(count);
|
||||
const statut = getStatutMonitoring(count);
|
||||
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
|
||||
@@ -7,6 +7,7 @@ import DataTable from '../../components/common/DataTable';
|
||||
import LoadingSpinner from '../../components/common/LoadingSpinner';
|
||||
import ErrorMessage from '../../components/common/ErrorMessage';
|
||||
import Button from '../../components/common/Button';
|
||||
import { buildMonitoringColumns } from '../../utils/monitoringColumns';
|
||||
import styles from './ServiceMonitorings.module.css';
|
||||
|
||||
export default function ServiceMonitorings({ serviceLabel, serviceName }) {
|
||||
@@ -34,22 +35,7 @@ export default function ServiceMonitorings({ serviceLabel, serviceName }) {
|
||||
if (loading) return <LoadingSpinner message={`Chargement des monitorings ${serviceLabel.toLowerCase()}...`} />;
|
||||
if (erreur) return <ErrorMessage message={erreur} />;
|
||||
|
||||
const columns = [
|
||||
{ key: 'nom', label: 'Monitoring' },
|
||||
{ key: 'service', label: 'Service' },
|
||||
{ key: 'categorie', label: 'Catégorie' },
|
||||
{ key: 'bdd_source', label: 'Source' },
|
||||
{ key: 'nb_erreurs', label: 'Erreurs', render: (val) => val ?? 0 },
|
||||
{
|
||||
key: 'actions',
|
||||
label: 'Actions',
|
||||
render: (val, row) => (
|
||||
<Button variant="link" onClick={() => navigate(`/monitoring/${row.id || row.id_monito}`)}>
|
||||
Voir détail →
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
];
|
||||
const columns = buildMonitoringColumns(navigate);
|
||||
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
|
||||
@@ -43,9 +43,25 @@ export default function Users() {
|
||||
}
|
||||
}, []);
|
||||
|
||||
/* Chargement initial. Le drapeau `annule` évite d'écrire dans un composant
|
||||
déjà démonté si l'utilisateur quitte la page pendant la requête. */
|
||||
useEffect(() => {
|
||||
charger();
|
||||
}, [charger]);
|
||||
let annule = false;
|
||||
|
||||
async function chargerAuMontage() {
|
||||
try {
|
||||
const data = await getUsers();
|
||||
if (!annule) setUsers(Array.isArray(data) ? data : []);
|
||||
} catch (e) {
|
||||
if (!annule) setErreur(e.message || 'Erreur lors du chargement des utilisateurs.');
|
||||
} finally {
|
||||
if (!annule) setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
chargerAuMontage();
|
||||
return () => { annule = true; };
|
||||
}, []);
|
||||
|
||||
/* Ouverture des modales */
|
||||
function ouvrirCreation() {
|
||||
|
||||
@@ -9,15 +9,10 @@ import DataTable from '../../components/common/DataTable';
|
||||
import LoadingSpinner from '../../components/common/LoadingSpinner';
|
||||
import ErrorMessage from '../../components/common/ErrorMessage';
|
||||
import Button from '../../components/common/Button';
|
||||
import { getStatutMonitoring } from '../../utils/statutMonitoring';
|
||||
import { buildMonitoringColumns } from '../../utils/monitoringColumns';
|
||||
import styles from './VueConso.module.css';
|
||||
|
||||
/* Détermine la couleur selon le statut */
|
||||
function getStatusColor(nbErreurs) {
|
||||
if (nbErreurs === 0) return 'var(--color-ok)';
|
||||
if (nbErreurs < 10) return 'var(--color-warning)';
|
||||
return 'var(--color-primary)';
|
||||
}
|
||||
|
||||
export default function VueConso() {
|
||||
const navigate = useNavigate();
|
||||
const [data, setData] = useState([]);
|
||||
@@ -47,26 +42,10 @@ export default function VueConso() {
|
||||
const chartData = data.map(item => ({
|
||||
name: item.nom || item.nom_monito || item.libelle || 'Monitoring',
|
||||
erreurs: item.nb_erreurs ?? item.count ?? 0,
|
||||
fill: getStatusColor(item.nb_erreurs ?? item.count ?? 0)
|
||||
fill: getStatutMonitoring(item.nb_erreurs ?? item.count ?? 0).color
|
||||
}));
|
||||
|
||||
/* Colonnes du tableau */
|
||||
const columns = [
|
||||
{ key: 'nom', label: 'Monitoring' },
|
||||
{ key: 'service', label: 'Service' },
|
||||
{ key: 'categorie', label: 'Catégorie' },
|
||||
{ key: 'bdd_source', label: 'Source' },
|
||||
{ key: 'nb_erreurs', label: 'Erreurs', render: (val) => val ?? 0 },
|
||||
{
|
||||
key: 'actions',
|
||||
label: 'Actions',
|
||||
render: (val, row) => (
|
||||
<Button variant="link" onClick={() => navigate(`/monitoring/${row.id || row.id_monito}`)}>
|
||||
Voir détail →
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
];
|
||||
const columns = buildMonitoringColumns(navigate);
|
||||
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
|
||||
@@ -3,9 +3,11 @@
|
||||
/* Utilise la variable d'environnement Vite si définie, sinon localhost par défaut */
|
||||
const BASE_URL = import.meta.env.VITE_API_URL ?? 'http://localhost:8000';
|
||||
|
||||
/* Clés de stockage local pour le token JWT et l'utilisateur connecté */
|
||||
/* Clés de stockage local pour le token JWT et l'utilisateur connecté.
|
||||
USER_KEY est exporté : AuthContext lit/écrit la même entrée, et une clé
|
||||
dupliquée des deux côtés divergerait silencieusement au premier renommage. */
|
||||
const TOKEN_KEY = 'ds_token';
|
||||
const USER_KEY = 'ds_user';
|
||||
export const USER_KEY = 'ds_user';
|
||||
|
||||
/* Helpers de gestion du token JWT dans le localStorage */
|
||||
export function getToken() {
|
||||
@@ -188,6 +190,58 @@ export async function getContacts(id_service) {
|
||||
return fetchApi('/contacts', { id_service });
|
||||
}
|
||||
|
||||
/* ---------- Administration du référentiel (réservé Admin) ---------- */
|
||||
|
||||
export async function createService(body) {
|
||||
return sendJson('/services', 'POST', body);
|
||||
}
|
||||
|
||||
export async function updateService(id_service, body) {
|
||||
return sendJson(`/services/${id_service}`, 'PUT', body);
|
||||
}
|
||||
|
||||
export async function deleteService(id_service) {
|
||||
return sendJson(`/services/${id_service}`, 'DELETE');
|
||||
}
|
||||
|
||||
export async function createCategorie(body) {
|
||||
return sendJson('/categories', 'POST', body);
|
||||
}
|
||||
|
||||
export async function updateCategorie(id_categorie, body) {
|
||||
return sendJson(`/categories/${id_categorie}`, 'PUT', body);
|
||||
}
|
||||
|
||||
export async function deleteCategorie(id_categorie) {
|
||||
return sendJson(`/categories/${id_categorie}`, 'DELETE');
|
||||
}
|
||||
|
||||
export async function createContact(body) {
|
||||
return sendJson('/contacts', 'POST', body);
|
||||
}
|
||||
|
||||
export async function updateContact(id_contact, body) {
|
||||
return sendJson(`/contacts/${id_contact}`, 'PUT', body);
|
||||
}
|
||||
|
||||
export async function deleteContact(id_contact) {
|
||||
return sendJson(`/contacts/${id_contact}`, 'DELETE');
|
||||
}
|
||||
|
||||
export async function createMonitoring(body) {
|
||||
return sendJson('/monitorings', 'POST', body);
|
||||
}
|
||||
|
||||
export async function updateMonitoring(id_monito, body) {
|
||||
return sendJson(`/monitorings/${id_monito}`, 'PUT', body);
|
||||
}
|
||||
|
||||
/* Désactivation (actif = 0) : l'historique référence le monitoring,
|
||||
il n'est jamais supprimé physiquement. */
|
||||
export async function desactiverMonitoring(id_monito) {
|
||||
return sendJson(`/monitorings/${id_monito}`, 'DELETE');
|
||||
}
|
||||
|
||||
/* Récupère la nomenclature (monitorings), filtrable par service et catégorie */
|
||||
export async function getMonitorings(id_service, id_categorie) {
|
||||
const data = await fetchApi('/monitorings', { id_service, id_categorie });
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
/* Formate une date au format attendu par <input type="date"> (YYYY-MM-DD).
|
||||
On lit les composantes en heure locale plutôt que d'utiliser toISOString(),
|
||||
qui bascule en UTC : un 1er janvier saisi depuis Paris (UTC+1) y devient le
|
||||
31 décembre de l'année précédente. */
|
||||
export function formatDateISO(date) {
|
||||
const mois = String(date.getMonth() + 1).padStart(2, '0');
|
||||
const jour = String(date.getDate()).padStart(2, '0');
|
||||
return `${date.getFullYear()}-${mois}-${jour}`;
|
||||
}
|
||||
|
||||
/* Période affichée par défaut : du 1er janvier de l'année courante à aujourd'hui. */
|
||||
export function periodeParDefaut(aujourdhui = new Date()) {
|
||||
return {
|
||||
debut: formatDateISO(new Date(aujourdhui.getFullYear(), 0, 1)),
|
||||
fin: formatDateISO(aujourdhui),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import Button from '../components/common/Button';
|
||||
|
||||
/* Colonnes du tableau de monitorings partagées par VueConso et
|
||||
ServiceMonitorings (Contrat/Fournisseur) : même jeu de données
|
||||
(GET /dashboard), même tableau. Centralisé pour qu'une évolution des
|
||||
colonnes (ajout, renommage) ne soit faite qu'à un seul endroit. */
|
||||
export function buildMonitoringColumns(navigate) {
|
||||
return [
|
||||
{ key: 'nom', label: 'Monitoring' },
|
||||
{ key: 'service', label: 'Service' },
|
||||
{ key: 'categorie', label: 'Catégorie' },
|
||||
{ key: 'bdd_source', label: 'Source' },
|
||||
{ key: 'nb_erreurs', label: 'Erreurs', render: (val) => val ?? 0 },
|
||||
{
|
||||
key: 'actions',
|
||||
label: 'Actions',
|
||||
render: (val, row) => (
|
||||
<Button variant="link" onClick={() => navigate(`/monitoring/${row.id || row.id_monito}`)}>
|
||||
Voir détail →
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
/* Règle de statut partagée : un monitoring est "OK" sans erreur, "Attention"
|
||||
en-dessous du seuil, "Critique" au-delà. Centralisé ici pour que le seuil
|
||||
ne soit corrigé qu'à un seul endroit (il était dupliqué dans MonitoringCard,
|
||||
MonitoringDetail et VueConso, avec le risque que l'une des copies diverge). */
|
||||
|
||||
export const SEUIL_ATTENTION = 10;
|
||||
|
||||
export function getStatutMonitoring(nbErreurs) {
|
||||
if (nbErreurs === 0) {
|
||||
return { label: 'OK', variant: 'ok', color: 'var(--color-ok)' };
|
||||
}
|
||||
if (nbErreurs < SEUIL_ATTENTION) {
|
||||
return { label: 'Attention', variant: 'warning', color: 'var(--color-warning)' };
|
||||
}
|
||||
return { label: 'Critique', variant: 'critical', color: 'var(--color-primary)' };
|
||||
}
|
||||
Reference in New Issue
Block a user