Initialise frontend #2
No files matched your search
@@ -18,18 +18,31 @@ docker compose exec web python manage.py makemigrations --check --dry-run
|
||||
|
||||
Dépendances : `backend/pyproject.toml` + `uv.lock` (uv). Après modification : `uv lock` (dans un conteneur Python 3.12), puis `docker compose build web`.
|
||||
|
||||
URL en dev : API `http://localhost:8000/api/v1/`, doc OpenAPI `/api/docs/`, admin `/admin/`, Mailpit `http://localhost:8025`.
|
||||
Front (`frontend/`, Node 24, hors Docker) :
|
||||
|
||||
```bash
|
||||
npm --prefix frontend install
|
||||
npm --prefix frontend run dev # http://localhost:5173, /api relayé vers Django
|
||||
npm --prefix frontend run test:unit -- --run
|
||||
npm --prefix frontend run type-check && npm --prefix frontend run lint
|
||||
```
|
||||
|
||||
URL en dev : front `http://localhost:5173`, API `http://localhost:8000/api/v1/`, doc OpenAPI `/api/docs/`, admin `/admin/`, Mailpit `http://localhost:8025`.
|
||||
|
||||
## Architecture (`backend/`)
|
||||
|
||||
- `config/` : settings (tout par variables d'environnement via django-environ). URL et couches des sources externes dans `PRISM_SOURCES`.
|
||||
- `accounts/` : `User` (e-mail = identifiant, `status` ; seul `active` peut se connecter), `MailEvent`. Rôles = Groups « Médecin », « Cellule SSMG », « Admin » (migration `0002_roles`). django-otp installé, endpoints d'auth pas encore écrits.
|
||||
- `accounts/` : `User` (e-mail = identifiant, `status` ; seul `active` peut se connecter), `MailEvent`. Rôles = Groups « Médecin », « Cellule SSMG », « Admin » (migration `0002_roles`). Routes `/api/v1/auth/login|logout|me/` (session + CSRF, `me` dépose le cookie CSRF) ; 2FA, inscription et réinitialisation pas encore écrites.
|
||||
- `factors/` : `Factor`, `DataSource`, `ThresholdClass` (valeur source → niveau 1–4 + couleur, par région ; `BE` = repli national), `ContentBlock` (textes, statut brouillon/validé, historique), `Reference` + `ContentReference` (notes numérotées).
|
||||
- `assessments/` :
|
||||
- `geocoding/` : chaîne Best Address (désactivée tant que `BEST_ADDRESS_URL` est vide, format à confirmer) → Nominatim. Région déduite du code postal.
|
||||
- `providers/` : un module par facteur (`FactorProvider.fetch(client, location) -> RawResult`), inscrit dans `registry.py`. Un module lève une exception si sa source ne répond pas ; le service la convertit en `status: unavailable`.
|
||||
- `services.py` : géocode, appelle les modules en parallèle (httpx async), mappe `RawResult.source_value` sur `ThresholdClass.source_value`, joint le `ContentBlock` validé.
|
||||
|
||||
## Front (`frontend/`)
|
||||
|
||||
Vue 3 + TS, sans bibliothèque de composants : composants maison stylés avec Bootstrap (CSS seul) et les variables de `src/styles/main.css`, reprises des maquettes Penpot (fichier « PRISM », page « PRISM – Mockups »). Textes dans `src/locales/fr.json`. Le front appelle l'API en même origine via le proxy Vite ; tests Vitest dans `src/__tests__/` (MapLibre mocké, pas de WebGL dans jsdom).
|
||||
|
||||
État des sources : bruit et inondation Wallonie via WalOnMap (ArcGIS REST `query`), air via irCELine (WMS `GetFeatureInfo`, moyennes annuelles). Bruxelles (bruit, inondation) et radon (AFCN) ne sont pas raccordés : ils renvoient `unavailable`. Pas de PostGIS pour l'instant (aucune donnée géographique stockée).
|
||||
|
||||
## Règles
|
||||
@@ -37,4 +50,5 @@ URL en dev : API `http://localhost:8000/api/v1/`, doc OpenAPI `/api/docs/`, admi
|
||||
- **Aucune adresse ni coordonnée de patient** stockée ou journalisée. Ne jamais journaliser une URL de requête sortante ni le message d'une exception httpx (ils contiennent les coordonnées) : seulement le code du facteur et le type d'erreur. Les loggers `httpx`/`httpcore` restent en WARNING. Un test (`test_address_is_not_logged`) le vérifie.
|
||||
- Seuils, couleurs et textes médicaux sont en base (Django admin), jamais dans le code. Exception : les valeurs guides OMS servant à compter les dépassements (`providers/air.py`).
|
||||
- Ajouter un facteur = un module dans `providers/` + inscription dans `registry.py` + classes et contenus dans l'admin.
|
||||
- Côté front, l'adresse du patient reste en mémoire du composant : jamais dans l'URL, le stockage du navigateur ni les journaux.
|
||||
- Code, commentaires, libellés et messages en français. Licence GPL v3.
|
||||
@@ -49,9 +49,16 @@ docker compose exec web python manage.py seed_factors
|
||||
docker compose exec web python manage.py createsuperuser
|
||||
```
|
||||
|
||||
Front (Node 24) :
|
||||
|
||||
```bash
|
||||
npm --prefix frontend install
|
||||
npm --prefix frontend run dev # http://localhost:5173
|
||||
```
|
||||
|
||||
API : <http://localhost:8000/api/v1/> · documentation OpenAPI : <http://localhost:8000/api/docs/> · admin : <http://localhost:8000/admin/> · e-mails de test (Mailpit) : <http://localhost:8025/>.
|
||||
|
||||
Tests et qualité : `docker compose exec web pytest` et `docker compose exec web ruff check .`
|
||||
Tests et qualité : `docker compose exec web pytest`, `docker compose exec web ruff check .` et `npm --prefix frontend run test:unit`.
|
||||
|
||||
## Documentation
|
||||
|
||||
@@ -63,7 +70,7 @@ Tests et qualité : `docker compose exec web pytest` et `docker compose exec web
|
||||
## État du projet
|
||||
|
||||
- Spécifications et maquettes : en cours de validation.
|
||||
- Code : back-end initialisé (modèles, raccordement des API WalOnMap et irCELine, API REST). Restent : Bruxelles, radon, Best Address, endpoints d'authentification, front Vue.
|
||||
- Code : back-end (modèles, raccordement des API WalOnMap et irCELine, API REST, connexion) et front Vue (connexion, évaluation avec carte MapLibre, pages d'erreur). Restent : Bruxelles, radon, Best Address, inscription, 2FA, mot de passe oublié, page « Mon compte ».
|
||||
- Échéance de la Phase 1 : livraison avant le 31 décembre 2026.
|
||||
|
||||
## Licence
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
[*.{js,jsx,mjs,cjs,ts,tsx,mts,cts,vue,css,scss,sass,less,styl}]
|
||||
charset = utf-8
|
||||
indent_size = 2
|
||||
indent_style = space
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
end_of_line = lf
|
||||
max_line_length = 100
|
||||
@@ -0,0 +1 @@
|
||||
* text=auto eol=lf
|
||||
@@ -0,0 +1,39 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
.DS_Store
|
||||
dist
|
||||
dist-ssr
|
||||
coverage
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
|
||||
*.tsbuildinfo
|
||||
|
||||
.eslintcache
|
||||
|
||||
# Cypress
|
||||
/cypress/videos/
|
||||
/cypress/screenshots/
|
||||
|
||||
# Vitest
|
||||
__screenshots__/
|
||||
|
||||
# Vite
|
||||
*.timestamp-*-*.mjs
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||
"plugins": ["eslint", "typescript", "unicorn", "oxc", "vue", "vitest"],
|
||||
"env": {
|
||||
"browser": true
|
||||
},
|
||||
"categories": {
|
||||
"correctness": "error"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/prettierrc",
|
||||
"semi": false,
|
||||
"singleQuote": true,
|
||||
"printWidth": 100
|
||||
}
|
||||
Vendored
+10
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"recommendations": [
|
||||
"Vue.volar",
|
||||
"vitest.explorer",
|
||||
"dbaeumer.vscode-eslint",
|
||||
"EditorConfig.EditorConfig",
|
||||
"oxc.oxc-vscode",
|
||||
"esbenp.prettier-vscode"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
# PRISM – front-end
|
||||
|
||||
Vue 3, Vite, TypeScript, Vue Router, vue-i18n, MapLibre GL JS, Bootstrap 5 (CSS seul) et Bootstrap Icons. Design repris des maquettes Penpot (charte ssmg.be, police Roboto).
|
||||
|
||||
```bash
|
||||
npm install
|
||||
npm run dev # http://localhost:5173, /api relayé vers Django (localhost:8000)
|
||||
npm run test:unit # Vitest
|
||||
npm run type-check
|
||||
npm run lint
|
||||
npm run build
|
||||
```
|
||||
|
||||
Le serveur Django doit tourner (`docker compose up -d` à la racine) et `CSRF_TRUSTED_ORIGINS` doit contenir `http://localhost:5173` (voir `.env.example`). Variable `API_PROXY_TARGET` pour relayer vers une autre adresse.
|
||||
|
||||
## Structure
|
||||
|
||||
- `src/api/` : client HTTP (session Django + jeton CSRF) et types des réponses.
|
||||
- `src/composables/useAuth.ts` : utilisateur courant, connexion, déconnexion (état partagé par un `ref`).
|
||||
- `src/router/` : routes et garde (`requiresAuth`, `guestOnly`).
|
||||
- `src/views/` : `LoginView`, `AssessmentView`, `ErrorView` (403, 404).
|
||||
- `src/components/` : `AddressForm`, `AlertBanner`, `ResultMap`, `FactorCard` (avec `ColorBadge`, `DetailList`, `InfoTabs`, `ReferenceList`), `AppHeader`, `AppFooter`.
|
||||
- `src/locales/fr.json` : tous les textes de l'interface.
|
||||
- `src/styles/main.css` : couleurs et surcharges Bootstrap issues des maquettes.
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
@@ -0,0 +1,32 @@
|
||||
import { globalIgnores } from 'eslint/config'
|
||||
import { defineConfigWithVueTs, vueTsConfigs } from '@vue/eslint-config-typescript'
|
||||
import pluginVue from 'eslint-plugin-vue'
|
||||
import pluginVitest from '@vitest/eslint-plugin'
|
||||
import pluginOxlint from 'eslint-plugin-oxlint'
|
||||
import skipFormatting from 'eslint-config-prettier/flat'
|
||||
|
||||
// To allow more languages other than `ts` in `.vue` files, uncomment the following lines:
|
||||
// import { configureVueProject } from '@vue/eslint-config-typescript'
|
||||
// configureVueProject({ scriptLangs: ['ts', 'tsx'] })
|
||||
// More info at https://github.com/vuejs/eslint-config-typescript/#advanced-setup
|
||||
|
||||
export default defineConfigWithVueTs(
|
||||
{
|
||||
name: 'app/files-to-lint',
|
||||
files: ['**/*.{vue,ts,mts,tsx}'],
|
||||
},
|
||||
|
||||
globalIgnores(['**/dist/**', '**/dist-ssr/**', '**/coverage/**']),
|
||||
|
||||
...pluginVue.configs['flat/essential'],
|
||||
vueTsConfigs.recommended,
|
||||
|
||||
{
|
||||
...pluginVitest.configs.recommended,
|
||||
files: ['src/**/__tests__/*'],
|
||||
},
|
||||
|
||||
...pluginOxlint.buildFromOxlintConfigFile('.oxlintrc.json'),
|
||||
|
||||
skipFormatting,
|
||||
)
|
||||
@@ -0,0 +1,13 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="fr">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<link rel="icon" href="/favicon.ico">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>PRISM – Environnement et santé</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
Generated
+6771
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,55 @@
|
||||
{
|
||||
"name": "prism-frontend",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "run-p type-check \"build-only {@}\" --",
|
||||
"preview": "vite preview",
|
||||
"test:unit": "vitest",
|
||||
"build-only": "vite build",
|
||||
"type-check": "vue-tsc --build",
|
||||
"lint": "run-s \"lint:*\"",
|
||||
"lint:oxlint": "oxlint . --fix",
|
||||
"lint:eslint": "eslint . --fix --cache",
|
||||
"format": "prettier --write --experimental-cli src/"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fontsource/roboto": "^5.3.0",
|
||||
"bootstrap": "^5.3.9",
|
||||
"bootstrap-icons": "^1.13.2",
|
||||
"maplibre-gl": "^6.19.0",
|
||||
"vue": "^3.5.42",
|
||||
"vue-i18n": "^11.4.23",
|
||||
"vue-router": "^5.3.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tsconfig/node24": "^24.0.5",
|
||||
"@types/jsdom": "^30.0.0",
|
||||
"@types/node": "^24.13.4",
|
||||
"@vitejs/plugin-vue": "^6.0.8",
|
||||
"@vitest/eslint-plugin": "^1.6.27",
|
||||
"@vue/eslint-config-typescript": "^14.9.0",
|
||||
"@vue/test-utils": "^2.5.0",
|
||||
"@vue/tsconfig": "^0.9.1",
|
||||
"eslint": "^10.10.0",
|
||||
"eslint-config-prettier": "^10.1.8",
|
||||
"eslint-plugin-oxlint": "~1.82.0",
|
||||
"eslint-plugin-vue": "~10.11.0",
|
||||
"jiti": "^2.7.0",
|
||||
"jsdom": "^30.0.1",
|
||||
"npm-run-all2": "^9.0.3",
|
||||
"oxlint": "~1.82.0",
|
||||
"prettier": "3.9.6",
|
||||
"typescript": "~6.0.0",
|
||||
"vite": "^8.2.2",
|
||||
"vite-plugin-vue-devtools": "^8.2.1",
|
||||
"vitest": "^4.1.11",
|
||||
"vue-eslint-parser": "^10.4.1",
|
||||
"vue-tsc": "^3.3.11"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^22.18.0 || >=24.12.0"
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 4.2 KiB |
@@ -0,0 +1,14 @@
|
||||
<script setup lang="ts">
|
||||
import AppFooter from '@/components/AppFooter.vue'
|
||||
import AppHeader from '@/components/AppHeader.vue'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="d-flex flex-column min-vh-100">
|
||||
<AppHeader />
|
||||
<main class="flex-grow-1">
|
||||
<RouterView />
|
||||
</main>
|
||||
<AppFooter />
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,57 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import FactorCard from '@/components/FactorCard.vue'
|
||||
|
||||
import { factor, mountWithPlugins } from './helpers'
|
||||
|
||||
describe('FactorCard', () => {
|
||||
it('affiche le niveau, le résumé, le détail et les références', () => {
|
||||
const wrapper = mountWithPlugins(FactorCard, { props: { factor: factor() } })
|
||||
expect(wrapper.find('h2').text()).toBe('Pollution sonore')
|
||||
expect(wrapper.find('.color-badge').text()).toBe('Impact faible')
|
||||
expect(wrapper.find('.color-badge').classes()).toContain('level-1')
|
||||
expect(wrapper.find('.summary').text()).toBe('moins de 55 dB (Lden)')
|
||||
expect(wrapper.find('dl').text()).toContain('Route')
|
||||
expect(wrapper.find('.references a').attributes('href')).toBe('https://eea.europa.eu')
|
||||
})
|
||||
|
||||
it.each([
|
||||
[2, 'Impact modéré'],
|
||||
[3, 'Impact élevé'],
|
||||
[4, 'Impact très élevé'],
|
||||
])('niveau %i → « %s »', (level, text) => {
|
||||
const wrapper = mountWithPlugins(FactorCard, { props: { factor: factor({ level }) } })
|
||||
expect(wrapper.find('.color-badge').text()).toBe(text)
|
||||
expect(wrapper.find('.factor-dot').classes()).toContain(`level-${level}`)
|
||||
})
|
||||
|
||||
it('affiche « Niveau non défini » sans classe de seuil', () => {
|
||||
const wrapper = mountWithPlugins(FactorCard, {
|
||||
props: { factor: factor({ level: null, color: null }) },
|
||||
})
|
||||
expect(wrapper.find('.color-badge').text()).toBe('Niveau non défini')
|
||||
expect(wrapper.find('.factor-dot').classes()).toContain('level-none')
|
||||
})
|
||||
|
||||
it('source indisponible : message, contour pointillé et bouton Réessayer', async () => {
|
||||
const wrapper = mountWithPlugins(FactorCard, {
|
||||
props: { factor: factor({ code: 'radon', label: 'Radon', status: 'unavailable' }) },
|
||||
})
|
||||
expect(wrapper.classes()).toContain('unavailable')
|
||||
expect(wrapper.find('.color-badge').text()).toBe('Donnée indisponible')
|
||||
expect(wrapper.text()).toContain('Le service de données « radon » ne répond pas')
|
||||
expect(wrapper.find('dl').exists()).toBe(false)
|
||||
|
||||
await wrapper.find('button').trigger('click')
|
||||
expect(wrapper.emitted('retry')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('donnée absente : message sans bouton Réessayer', () => {
|
||||
const wrapper = mountWithPlugins(FactorCard, {
|
||||
props: { factor: factor({ status: 'no_data' }) },
|
||||
})
|
||||
expect(wrapper.find('.color-badge').text()).toBe('Donnée absente')
|
||||
expect(wrapper.text()).toContain('Aucune donnée')
|
||||
expect(wrapper.find('button').exists()).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,59 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import ResultMap from '@/components/ResultMap.vue'
|
||||
|
||||
import { mountWithPlugins } from './helpers'
|
||||
|
||||
// MapLibre a besoin de WebGL, absent de jsdom : on vérifie les appels.
|
||||
type Fn = (...args: unknown[]) => unknown
|
||||
|
||||
const mapInstance = {
|
||||
addControl: vi.fn<Fn>(),
|
||||
resize: vi.fn<Fn>(),
|
||||
jumpTo: vi.fn<Fn>(),
|
||||
setLayoutProperty: vi.fn<Fn>(),
|
||||
remove: vi.fn<Fn>(),
|
||||
}
|
||||
const marker = {
|
||||
setLngLat: vi.fn<Fn>().mockReturnThis(),
|
||||
addTo: vi.fn<Fn>().mockReturnThis(),
|
||||
remove: vi.fn<Fn>(),
|
||||
}
|
||||
|
||||
vi.mock('maplibre-gl', () => ({
|
||||
Map: vi.fn<() => typeof mapInstance>(function () {
|
||||
return mapInstance
|
||||
}),
|
||||
Marker: vi.fn<() => typeof marker>(function () {
|
||||
return marker
|
||||
}),
|
||||
NavigationControl: vi.fn<Fn>(),
|
||||
ScaleControl: vi.fn<Fn>(),
|
||||
}))
|
||||
|
||||
describe('ResultMap', () => {
|
||||
it("centre la carte et place le marqueur sur l'adresse", async () => {
|
||||
const wrapper = mountWithPlugins(ResultMap, { props: { location: null } })
|
||||
expect(marker.setLngLat).not.toHaveBeenCalled()
|
||||
|
||||
await wrapper.setProps({ location: { lat: 50.668, lon: 4.617, region: 'WAL' } })
|
||||
|
||||
expect(marker.setLngLat).toHaveBeenCalledWith([4.617, 50.668])
|
||||
expect(mapInstance.jumpTo).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ center: [4.617, 50.668], zoom: 15 }),
|
||||
)
|
||||
})
|
||||
|
||||
it('affiche ou masque une couche WMS', async () => {
|
||||
const wrapper = mountWithPlugins(ResultMap, { props: { location: null } })
|
||||
await wrapper.find('#layer-noise').setValue(true)
|
||||
expect(mapInstance.setLayoutProperty).toHaveBeenCalledWith('noise', 'visibility', 'visible')
|
||||
await wrapper.find('#layer-flood').trigger('change')
|
||||
expect(mapInstance.setLayoutProperty).toHaveBeenCalledWith('flood', 'visibility', 'none')
|
||||
})
|
||||
|
||||
it('libère la carte au démontage', () => {
|
||||
mountWithPlugins(ResultMap, { props: { location: null } }).unmount()
|
||||
expect(mapInstance.remove).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,70 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { api, ApiError, csrfToken } from '@/api/client'
|
||||
|
||||
import { ASSESSMENT, jsonResponse, mockFetch } from './helpers'
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
document.cookie = 'csrftoken=; expires=Thu, 01 Jan 1970 00:00:00 GMT'
|
||||
})
|
||||
|
||||
describe('csrfToken', () => {
|
||||
it('lit le cookie csrftoken', () => {
|
||||
document.cookie = 'autre=1'
|
||||
document.cookie = 'csrftoken=abc123'
|
||||
expect(csrfToken()).toBe('abc123')
|
||||
})
|
||||
|
||||
it('renvoie une chaîne vide sans cookie', () => {
|
||||
expect(csrfToken()).toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
describe('api', () => {
|
||||
it('envoie le jeton CSRF et le corps JSON sur un POST', async () => {
|
||||
document.cookie = 'csrftoken=jeton'
|
||||
const fetch = mockFetch(jsonResponse(200, ASSESSMENT))
|
||||
|
||||
const result = await api.assess('Place de l’Université 1')
|
||||
|
||||
expect(result).toEqual(ASSESSMENT)
|
||||
const [url, init] = fetch.mock.calls[0]!
|
||||
expect(url).toBe('/api/v1/assessments/')
|
||||
expect(init?.method).toBe('POST')
|
||||
expect(init?.credentials).toBe('same-origin')
|
||||
expect(init?.headers).toMatchObject({
|
||||
'X-CSRFToken': 'jeton',
|
||||
'Content-Type': 'application/json',
|
||||
})
|
||||
expect(JSON.parse(init?.body as string)).toEqual({ address: 'Place de l’Université 1' })
|
||||
})
|
||||
|
||||
it("n'envoie pas de jeton CSRF sur un GET", async () => {
|
||||
const fetch = mockFetch(jsonResponse(200, {}))
|
||||
await api.me()
|
||||
expect(fetch.mock.calls[0]![1]?.headers).not.toHaveProperty('X-CSRFToken')
|
||||
})
|
||||
|
||||
it('accepte une réponse 204 sans corps', async () => {
|
||||
mockFetch(new Response(null, { status: 204 }))
|
||||
await expect(api.logout()).resolves.toBeUndefined()
|
||||
})
|
||||
|
||||
it('lève une ApiError avec le statut, le message et le code', async () => {
|
||||
mockFetch(jsonResponse(404, { code: 'address_not_found', detail: 'Adresse introuvable.' }))
|
||||
const error = await api.assess('nulle part').catch((e) => e)
|
||||
expect(error).toBeInstanceOf(ApiError)
|
||||
expect(error.status).toBe(404)
|
||||
expect(error.code).toBe('address_not_found')
|
||||
expect(error.message).toBe('Adresse introuvable.')
|
||||
})
|
||||
|
||||
it('gère une erreur sans corps JSON', async () => {
|
||||
mockFetch(new Response('<html>403</html>', { status: 403 }))
|
||||
const error = await api.me().catch((e) => e)
|
||||
expect(error).toBeInstanceOf(ApiError)
|
||||
expect(error.message).toBe('HTTP 403')
|
||||
expect(error.code).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,108 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import AddressForm from '@/components/AddressForm.vue'
|
||||
import DetailList from '@/components/DetailList.vue'
|
||||
import InfoTabs from '@/components/InfoTabs.vue'
|
||||
import ReferenceList from '@/components/ReferenceList.vue'
|
||||
|
||||
import { factor, mountWithPlugins } from './helpers'
|
||||
|
||||
describe('DetailList', () => {
|
||||
it('affiche une pastille rouge pour un dépassement et verte sinon', () => {
|
||||
const wrapper = mountWithPlugins(DetailList, {
|
||||
props: {
|
||||
details: [
|
||||
{ label: 'PM2,5', value: '7,1 µg/m³ (seuil 5)', status: 'exceeded' },
|
||||
{ label: 'PM10', value: '12,0 µg/m³ (seuil 15)', status: 'ok' },
|
||||
{ label: 'O₃', value: '50,1 µg/m³' },
|
||||
],
|
||||
},
|
||||
})
|
||||
const rows = wrapper.findAll('.detail-row')
|
||||
expect(rows).toHaveLength(3)
|
||||
expect(rows[0]!.find('.dot').classes()).toContain('level-4')
|
||||
expect(rows[0]!.text()).toContain('(dépassé)')
|
||||
expect(rows[1]!.find('.dot').classes()).toContain('level-1')
|
||||
expect(rows[2]!.find('.dot').exists()).toBe(false)
|
||||
})
|
||||
|
||||
it("n'affiche rien sans détail", () => {
|
||||
expect(
|
||||
mountWithPlugins(DetailList, { props: { details: [] } })
|
||||
.find('dl')
|
||||
.exists(),
|
||||
).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('InfoTabs', () => {
|
||||
it('affiche les effets sur la santé par défaut, une ligne par puce', () => {
|
||||
const wrapper = mountWithPlugins(InfoTabs, { props: { tabs: factor().tabs } })
|
||||
expect(wrapper.find('[aria-selected="true"]').text()).toBe('Effets sur la santé')
|
||||
expect(wrapper.findAll('.bullets li').map((li) => li.text())).toEqual([
|
||||
'Gêne, perturbation du sommeil',
|
||||
'Effets cardiovasculaires',
|
||||
])
|
||||
})
|
||||
|
||||
it('change d’onglet', async () => {
|
||||
const wrapper = mountWithPlugins(InfoTabs, { props: { tabs: factor().tabs } })
|
||||
const [, actions, legend] = wrapper.findAll('[role="tab"]')
|
||||
|
||||
await actions!.trigger('click')
|
||||
expect(actions!.attributes('aria-selected')).toBe('true')
|
||||
expect(wrapper.find('.bullets').text()).toBe('Isolation acoustique')
|
||||
|
||||
await legend!.trigger('click')
|
||||
expect(wrapper.find('.scale').text()).toBe('< 55 dB')
|
||||
expect(wrapper.find('.source').text()).toBe('Source : WalOnMap')
|
||||
})
|
||||
|
||||
it('indique un contenu en attente de validation', () => {
|
||||
const tabs = { ...factor().tabs, health_effects: '' }
|
||||
const wrapper = mountWithPlugins(InfoTabs, { props: { tabs } })
|
||||
expect(wrapper.find('.empty').text()).toContain('en cours de validation')
|
||||
})
|
||||
})
|
||||
|
||||
describe('ReferenceList', () => {
|
||||
it('numérote les références et ouvre les liens dans un nouvel onglet', () => {
|
||||
const wrapper = mountWithPlugins(ReferenceList, {
|
||||
props: {
|
||||
references: [
|
||||
{ n: 1, title: 'EEA 2020', url: 'https://eea.europa.eu' },
|
||||
{ n: 2, title: 'Canopea 2021', url: '' },
|
||||
],
|
||||
},
|
||||
})
|
||||
expect(wrapper.text()).toContain('1. EEA 2020')
|
||||
expect(wrapper.text()).toContain('2. Canopea 2021')
|
||||
const link = wrapper.find('a')
|
||||
expect(link.attributes('target')).toBe('_blank')
|
||||
expect(link.attributes('rel')).toContain('noopener')
|
||||
})
|
||||
|
||||
it("n'affiche rien sans référence", () => {
|
||||
const wrapper = mountWithPlugins(ReferenceList, { props: { references: [] } })
|
||||
expect(wrapper.find('.references').exists()).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('AddressForm', () => {
|
||||
it("émet l'adresse sans espaces superflus", async () => {
|
||||
const wrapper = mountWithPlugins(AddressForm, { props: { loading: false } })
|
||||
await wrapper.find('input').setValue(' Rue de la Loi 16, 1000 Bruxelles ')
|
||||
await wrapper.find('form').trigger('submit')
|
||||
expect(wrapper.emitted('submit')).toEqual([['Rue de la Loi 16, 1000 Bruxelles']])
|
||||
})
|
||||
|
||||
it('désactive le bouton sans adresse ou pendant le chargement', async () => {
|
||||
const wrapper = mountWithPlugins(AddressForm, { props: { loading: false } })
|
||||
expect(wrapper.find('button').attributes('disabled')).toBeDefined()
|
||||
await wrapper.find('input').setValue('Rue')
|
||||
expect(wrapper.find('button').attributes('disabled')).toBeUndefined()
|
||||
await wrapper.setProps({ loading: true })
|
||||
expect(wrapper.find('button').text()).toBe('Analyse…')
|
||||
expect(wrapper.find('button').attributes('disabled')).toBeDefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,77 @@
|
||||
import { mount, type ComponentMountingOptions } from '@vue/test-utils'
|
||||
import { vi } from 'vitest'
|
||||
import type { Component } from 'vue'
|
||||
import { createMemoryHistory, createRouter } from 'vue-router'
|
||||
|
||||
import type { Assessment, FactorResult, User } from '@/api/types'
|
||||
import i18n from '@/i18n'
|
||||
import { routes } from '@/router'
|
||||
|
||||
export const USER: User = {
|
||||
email: 'medecin@exemple.be',
|
||||
first_name: 'Jean',
|
||||
last_name: 'Dupont',
|
||||
roles: ['Médecin'],
|
||||
is_staff: false,
|
||||
}
|
||||
|
||||
export function factor(overrides: Partial<FactorResult> = {}): FactorResult {
|
||||
return {
|
||||
code: 'noise',
|
||||
label: 'Pollution sonore',
|
||||
status: 'ok',
|
||||
level: 1,
|
||||
color: 'green',
|
||||
summary: 'moins de 55 dB (Lden)',
|
||||
details: [{ label: 'Route', value: 'moins de 55 dB' }],
|
||||
tabs: {
|
||||
health_effects: 'Gêne, perturbation du sommeil\nEffets cardiovasculaires',
|
||||
actions: 'Isolation acoustique',
|
||||
legend: {
|
||||
source: 'WalOnMap',
|
||||
text: '',
|
||||
scale: [{ level: 1, color: 'green', label: '< 55 dB' }],
|
||||
},
|
||||
},
|
||||
references: [{ n: 1, title: 'EEA 2020', url: 'https://eea.europa.eu' }],
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
export const ASSESSMENT: Assessment = {
|
||||
location: { lat: 50.668, lon: 4.617, region: 'WAL' },
|
||||
factors: [
|
||||
factor(),
|
||||
factor({ code: 'radon', label: 'Radon', status: 'unavailable', level: null, color: null }),
|
||||
],
|
||||
}
|
||||
|
||||
/** Réponse JSON simulée pour `fetch`. */
|
||||
export function jsonResponse(status: number, body?: unknown): Response {
|
||||
return new Response(body === undefined ? null : JSON.stringify(body), {
|
||||
status,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
}
|
||||
|
||||
export function mockFetch(...responses: Response[]) {
|
||||
const fn = vi.fn<typeof fetch>()
|
||||
for (const response of responses) fn.mockResolvedValueOnce(response)
|
||||
vi.stubGlobal('fetch', fn)
|
||||
return fn
|
||||
}
|
||||
|
||||
export function makeRouter() {
|
||||
return createRouter({ history: createMemoryHistory(), routes })
|
||||
}
|
||||
|
||||
export function mountWithPlugins<C extends Component>(
|
||||
component: C,
|
||||
options: ComponentMountingOptions<C> & { router?: ReturnType<typeof makeRouter> } = {},
|
||||
) {
|
||||
const { router = makeRouter(), ...rest } = options
|
||||
return mount(component, {
|
||||
...rest,
|
||||
global: { plugins: [i18n, router], ...rest.global },
|
||||
} as ComponentMountingOptions<C>)
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { resetAuth } from '@/composables/useAuth'
|
||||
import { createAppRouter } from '@/router'
|
||||
|
||||
import { jsonResponse, mockFetch, USER } from './helpers'
|
||||
|
||||
beforeEach(resetAuth)
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
|
||||
async function navigate(path: string) {
|
||||
const router = createAppRouter()
|
||||
await router.push(path)
|
||||
return router.currentRoute.value
|
||||
}
|
||||
|
||||
describe('garde de navigation', () => {
|
||||
it("redirige un visiteur vers /login depuis l'évaluation", async () => {
|
||||
mockFetch(jsonResponse(403, {}))
|
||||
expect((await navigate('/')).name).toBe('login')
|
||||
})
|
||||
|
||||
it('laisse un utilisateur connecté accéder à l’évaluation', async () => {
|
||||
mockFetch(jsonResponse(200, USER))
|
||||
expect((await navigate('/')).name).toBe('assessment')
|
||||
})
|
||||
|
||||
it('renvoie un utilisateur connecté de /login vers l’évaluation', async () => {
|
||||
mockFetch(jsonResponse(200, USER))
|
||||
expect((await navigate('/login')).name).toBe('assessment')
|
||||
})
|
||||
|
||||
it('affiche la page 404 pour une route inconnue', async () => {
|
||||
mockFetch(jsonResponse(403, {}))
|
||||
const route = await navigate('/nimporte/quoi')
|
||||
expect(route.name).toBe('not-found')
|
||||
})
|
||||
|
||||
it('laisse la page 403 publique', async () => {
|
||||
mockFetch(jsonResponse(403, {}))
|
||||
expect((await navigate('/403')).name).toBe('forbidden')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,61 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { ApiError } from '@/api/client'
|
||||
import { resetAuth, useAuth } from '@/composables/useAuth'
|
||||
|
||||
import { jsonResponse, mockFetch, USER } from './helpers'
|
||||
|
||||
beforeEach(resetAuth)
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
|
||||
describe('useAuth', () => {
|
||||
it("charge l'utilisateur connecté", async () => {
|
||||
mockFetch(jsonResponse(200, USER))
|
||||
const { load, user, isAuthenticated } = useAuth()
|
||||
await load()
|
||||
expect(user.value).toEqual(USER)
|
||||
expect(isAuthenticated.value).toBe(true)
|
||||
})
|
||||
|
||||
it('considère un 403 comme « non connecté »', async () => {
|
||||
mockFetch(jsonResponse(403, { detail: 'Non authentifié.' }))
|
||||
const { load, isAuthenticated } = useAuth()
|
||||
await expect(load()).resolves.toBeNull()
|
||||
expect(isAuthenticated.value).toBe(false)
|
||||
})
|
||||
|
||||
it('propage les autres erreurs', async () => {
|
||||
mockFetch(jsonResponse(500, {}))
|
||||
await expect(useAuth().load()).rejects.toBeInstanceOf(ApiError)
|
||||
})
|
||||
|
||||
it("n'interroge l'API qu'une fois", async () => {
|
||||
const fetch = mockFetch(jsonResponse(200, USER))
|
||||
const { load } = useAuth()
|
||||
await load()
|
||||
await load()
|
||||
expect(fetch).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it("connecte puis recharge l'utilisateur (nouveau jeton CSRF)", async () => {
|
||||
const fetch = mockFetch(
|
||||
jsonResponse(200, { mfa_required: false, user: USER }),
|
||||
jsonResponse(200, USER),
|
||||
)
|
||||
const { login, user } = useAuth()
|
||||
await login('medecin@exemple.be', 'secret')
|
||||
expect(user.value).toEqual(USER)
|
||||
expect(fetch.mock.calls.map(([url]) => url)).toEqual([
|
||||
'/api/v1/auth/login/',
|
||||
'/api/v1/auth/me/',
|
||||
])
|
||||
})
|
||||
|
||||
it('déconnecte même si la requête échoue', async () => {
|
||||
mockFetch(jsonResponse(200, USER), jsonResponse(500, {}), jsonResponse(403, {}))
|
||||
const { load, logout, user } = useAuth()
|
||||
await load()
|
||||
await logout().catch(() => {})
|
||||
expect(user.value).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,151 @@
|
||||
import { flushPromises } from '@vue/test-utils'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { resetAuth, useAuth } from '@/composables/useAuth'
|
||||
import AssessmentView from '@/views/AssessmentView.vue'
|
||||
import ErrorView from '@/views/ErrorView.vue'
|
||||
import LoginView from '@/views/LoginView.vue'
|
||||
|
||||
import { ASSESSMENT, jsonResponse, makeRouter, mockFetch, mountWithPlugins, USER } from './helpers'
|
||||
|
||||
const stubs = { ResultMap: { template: '<div class="map-stub" />', props: ['location'] } }
|
||||
|
||||
beforeEach(resetAuth)
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
|
||||
async function analyse(
|
||||
wrapper: ReturnType<typeof mountWithPlugins>,
|
||||
address = 'Place de l’Université 1',
|
||||
) {
|
||||
await wrapper.find('#address').setValue(address)
|
||||
await wrapper.find('form').trigger('submit')
|
||||
await flushPromises()
|
||||
}
|
||||
|
||||
describe('AssessmentView', () => {
|
||||
it('affiche l’adresse reconnue et une carte par facteur', async () => {
|
||||
mockFetch(jsonResponse(200, ASSESSMENT))
|
||||
const wrapper = mountWithPlugins(AssessmentView, { global: { stubs } })
|
||||
|
||||
await analyse(wrapper)
|
||||
|
||||
expect(wrapper.find('[role="status"]').text()).toBe(
|
||||
'Adresse reconnue : Place de l’Université 1 — Région wallonne',
|
||||
)
|
||||
expect(wrapper.findAll('.factor-card')).toHaveLength(2)
|
||||
})
|
||||
|
||||
it.each([
|
||||
[404, { code: 'address_not_found' }, 'Adresse introuvable'],
|
||||
[422, { code: 'out_of_coverage' }, 'hors couverture'],
|
||||
[503, { code: 'geocoding_unavailable' }, 'géocodage est indisponible'],
|
||||
[429, { detail: 'Throttled' }, "Trop d'analyses"],
|
||||
[500, {}, "L'analyse a échoué"],
|
||||
])('erreur %i → message adapté', async (status, body, message) => {
|
||||
mockFetch(jsonResponse(status, body))
|
||||
const wrapper = mountWithPlugins(AssessmentView, { global: { stubs } })
|
||||
|
||||
await analyse(wrapper)
|
||||
|
||||
expect(wrapper.find('[role="alert"]').text()).toContain(message)
|
||||
expect(wrapper.findAll('.factor-card')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('« Réessayer » relance l’analyse de la même adresse', async () => {
|
||||
const fetch = mockFetch(jsonResponse(200, ASSESSMENT), jsonResponse(200, ASSESSMENT))
|
||||
const wrapper = mountWithPlugins(AssessmentView, { global: { stubs } })
|
||||
await analyse(wrapper, 'Rue de la Loi 16, 1000 Bruxelles')
|
||||
|
||||
await wrapper.find('.factor-card.unavailable button').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(fetch).toHaveBeenCalledTimes(2)
|
||||
expect(JSON.parse(fetch.mock.calls[1]![1]!.body as string)).toEqual({
|
||||
address: 'Rue de la Loi 16, 1000 Bruxelles',
|
||||
})
|
||||
})
|
||||
|
||||
it('session expirée : retour à la connexion', async () => {
|
||||
mockFetch(jsonResponse(403, {}), jsonResponse(204), jsonResponse(403, {}))
|
||||
const router = makeRouter()
|
||||
const push = vi.spyOn(router, 'push')
|
||||
const wrapper = mountWithPlugins(AssessmentView, { router, global: { stubs } })
|
||||
|
||||
await analyse(wrapper)
|
||||
|
||||
expect(push).toHaveBeenCalledWith({ name: 'login' })
|
||||
})
|
||||
|
||||
it("ne place pas l'adresse dans l'URL ni dans le stockage du navigateur", async () => {
|
||||
mockFetch(jsonResponse(200, ASSESSMENT))
|
||||
const router = makeRouter()
|
||||
const wrapper = mountWithPlugins(AssessmentView, { router, global: { stubs } })
|
||||
|
||||
await analyse(wrapper, 'Rue Secrète 1, 1348 Louvain-la-Neuve')
|
||||
|
||||
expect(router.currentRoute.value.fullPath).not.toContain('Secr')
|
||||
expect(JSON.stringify({ ...localStorage, ...sessionStorage })).not.toContain('Secr')
|
||||
})
|
||||
})
|
||||
|
||||
describe('LoginView', () => {
|
||||
it("affiche le message d'erreur du serveur", async () => {
|
||||
mockFetch(jsonResponse(400, { detail: 'E-mail ou mot de passe incorrect.' }))
|
||||
const wrapper = mountWithPlugins(LoginView)
|
||||
|
||||
await wrapper.find('#email').setValue('medecin@exemple.be')
|
||||
await wrapper.find('#password').setValue('mauvais')
|
||||
await wrapper.find('form').trigger('submit')
|
||||
await flushPromises()
|
||||
|
||||
expect(wrapper.find('[role="alert"]').text()).toBe('E-mail ou mot de passe incorrect.')
|
||||
})
|
||||
|
||||
it('redirige vers l’évaluation après connexion', async () => {
|
||||
mockFetch(jsonResponse(200, { mfa_required: false, user: USER }), jsonResponse(200, USER))
|
||||
const router = makeRouter()
|
||||
const push = vi.spyOn(router, 'push').mockResolvedValue(undefined)
|
||||
const wrapper = mountWithPlugins(LoginView, { router })
|
||||
|
||||
await wrapper.find('#email').setValue('medecin@exemple.be')
|
||||
await wrapper.find('#password').setValue('un-mot-de-passe-solide')
|
||||
await wrapper.find('form').trigger('submit')
|
||||
await flushPromises()
|
||||
|
||||
expect(useAuth().user.value).toEqual(USER)
|
||||
expect(push).toHaveBeenCalledWith({ name: 'assessment' })
|
||||
})
|
||||
|
||||
it('suit le paramètre next interne et ignore une URL externe', async () => {
|
||||
for (const [next, expected] of [
|
||||
['/403', '/403'],
|
||||
['https://evil.example', { name: 'assessment' }],
|
||||
] as const) {
|
||||
resetAuth()
|
||||
mockFetch(jsonResponse(200, { mfa_required: false, user: USER }), jsonResponse(200, USER))
|
||||
const router = makeRouter()
|
||||
await router.push({ name: 'login', query: { next } }).catch(() => {})
|
||||
const push = vi.spyOn(router, 'push').mockResolvedValue(undefined)
|
||||
const wrapper = mountWithPlugins(LoginView, { router })
|
||||
|
||||
await wrapper.find('#email').setValue('medecin@exemple.be')
|
||||
await wrapper.find('#password').setValue('x')
|
||||
await wrapper.find('form').trigger('submit')
|
||||
await flushPromises()
|
||||
|
||||
expect(push).toHaveBeenCalledWith(expected)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('ErrorView', () => {
|
||||
it.each([
|
||||
[404, 'Page introuvable'],
|
||||
[403, 'Accès refusé'],
|
||||
] as const)('%i', (code, title) => {
|
||||
const wrapper = mountWithPlugins(ErrorView, { props: { code } })
|
||||
expect(wrapper.find('.error-code').text()).toBe(String(code))
|
||||
expect(wrapper.find('h1').text()).toBe(title)
|
||||
expect(wrapper.find('a').attributes('href')).toBe('/')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* Client HTTP de l'API Django (sessions + CSRF).
|
||||
*
|
||||
* Le cookie CSRF est déposé par GET /auth/me/ ; il est renvoyé dans l'en-tête X-CSRFToken
|
||||
* pour toutes les requêtes qui modifient l'état.
|
||||
*/
|
||||
|
||||
import type { Assessment, User } from './types'
|
||||
|
||||
const BASE = '/api/v1'
|
||||
|
||||
export class ApiError extends Error {
|
||||
readonly status: number
|
||||
readonly body: Record<string, unknown>
|
||||
|
||||
constructor(status: number, body: Record<string, unknown>) {
|
||||
super(typeof body.detail === 'string' ? body.detail : `HTTP ${status}`)
|
||||
this.status = status
|
||||
this.body = body
|
||||
}
|
||||
|
||||
get code(): string | undefined {
|
||||
return typeof this.body.code === 'string' ? this.body.code : undefined
|
||||
}
|
||||
}
|
||||
|
||||
export function csrfToken(): string {
|
||||
const match = document.cookie.match(/(?:^|;\s*)csrftoken=([^;]+)/)
|
||||
return match?.[1] ? decodeURIComponent(match[1]) : ''
|
||||
}
|
||||
|
||||
async function request<T>(method: string, path: string, body?: unknown): Promise<T> {
|
||||
const headers: Record<string, string> = { Accept: 'application/json' }
|
||||
if (method !== 'GET') {
|
||||
headers['X-CSRFToken'] = csrfToken()
|
||||
}
|
||||
if (body !== undefined) {
|
||||
headers['Content-Type'] = 'application/json'
|
||||
}
|
||||
const response = await fetch(`${BASE}${path}`, {
|
||||
method,
|
||||
headers,
|
||||
credentials: 'same-origin',
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
})
|
||||
if (response.status === 204) {
|
||||
return undefined as T
|
||||
}
|
||||
const data = await response.json().catch(() => ({}))
|
||||
if (!response.ok) {
|
||||
throw new ApiError(response.status, data)
|
||||
}
|
||||
return data as T
|
||||
}
|
||||
|
||||
export const api = {
|
||||
me: () => request<User>('GET', '/auth/me/'),
|
||||
login: (email: string, password: string) =>
|
||||
request<{ mfa_required: boolean; user: User }>('POST', '/auth/login/', { email, password }),
|
||||
logout: () => request<void>('POST', '/auth/logout/'),
|
||||
assess: (address: string) => request<Assessment>('POST', '/assessments/', { address }),
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
export type FactorStatus = 'ok' | 'no_data' | 'unavailable'
|
||||
export type LevelColor = 'green' | 'yellow' | 'orange' | 'red'
|
||||
export type Region = 'WAL' | 'BXL'
|
||||
|
||||
export interface User {
|
||||
email: string
|
||||
first_name: string
|
||||
last_name: string
|
||||
roles: string[]
|
||||
is_staff: boolean
|
||||
}
|
||||
|
||||
export interface Detail {
|
||||
label: string
|
||||
value: string
|
||||
status?: 'ok' | 'exceeded'
|
||||
}
|
||||
|
||||
export interface ScaleItem {
|
||||
level: number
|
||||
color: LevelColor
|
||||
label: string
|
||||
}
|
||||
|
||||
export interface Legend {
|
||||
source: string
|
||||
text: string
|
||||
scale: ScaleItem[]
|
||||
}
|
||||
|
||||
export interface Reference {
|
||||
n: number
|
||||
title: string
|
||||
url: string
|
||||
}
|
||||
|
||||
export interface FactorResult {
|
||||
code: string
|
||||
label: string
|
||||
status: FactorStatus
|
||||
level: number | null
|
||||
color: LevelColor | null
|
||||
summary: string
|
||||
details: Detail[]
|
||||
tabs: {
|
||||
health_effects: string
|
||||
actions: string
|
||||
legend: Legend
|
||||
}
|
||||
references: Reference[]
|
||||
}
|
||||
|
||||
export interface Assessment {
|
||||
location: { lat: number; lon: number; region: Region }
|
||||
factors: FactorResult[]
|
||||
}
|
||||
|
||||
export type AssessmentErrorCode = 'address_not_found' | 'out_of_coverage' | 'geocoding_unavailable'
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 9.4 KiB |
@@ -0,0 +1,55 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
|
||||
defineProps<{ loading: boolean }>()
|
||||
const emit = defineEmits<{ submit: [address: string] }>()
|
||||
|
||||
const address = ref('')
|
||||
|
||||
function onSubmit() {
|
||||
const value = address.value.trim()
|
||||
if (value) emit('submit', value)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<form class="address-form prism-card" @submit.prevent="onSubmit">
|
||||
<label for="address" class="form-label">{{ $t('assessment.addressLabel') }}</label>
|
||||
<div class="d-flex flex-column flex-md-row gap-3">
|
||||
<input
|
||||
id="address"
|
||||
v-model="address"
|
||||
type="text"
|
||||
class="form-control"
|
||||
autocomplete="off"
|
||||
maxlength="300"
|
||||
required
|
||||
:placeholder="$t('assessment.addressPlaceholder')"
|
||||
/>
|
||||
<button type="submit" class="btn btn-primary submit" :disabled="loading || !address.trim()">
|
||||
<span
|
||||
v-if="loading"
|
||||
class="spinner-border spinner-border-sm me-2"
|
||||
aria-hidden="true"
|
||||
></span>
|
||||
{{ loading ? $t('assessment.submitting') : $t('assessment.submit') }}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.address-form {
|
||||
padding: 22px 28px 22px;
|
||||
}
|
||||
|
||||
@media (max-width: 767.98px) {
|
||||
.address-form {
|
||||
padding: 18px;
|
||||
}
|
||||
}
|
||||
|
||||
.submit {
|
||||
min-width: 160px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,13 @@
|
||||
<script setup lang="ts">
|
||||
defineProps<{ variant: 'info' | 'error' }>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
:class="variant === 'info' ? 'prism-alert-info' : 'alert alert-danger mb-0'"
|
||||
:role="variant === 'error' ? 'alert' : 'status'"
|
||||
>
|
||||
<i v-if="variant === 'error'" class="bi bi-exclamation-triangle me-2" aria-hidden="true"></i>
|
||||
<slot />
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,31 @@
|
||||
<template>
|
||||
<footer class="app-footer">
|
||||
<div class="container-xxl d-flex flex-column flex-md-row justify-content-between gap-2 py-4">
|
||||
<span>{{ $t('app.disclaimer') }}</span>
|
||||
<span class="footer-copyright">{{ $t('app.copyright') }}</span>
|
||||
</div>
|
||||
</footer>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.app-footer {
|
||||
background: var(--prism-navy);
|
||||
color: #fff;
|
||||
font-size: 0.8125rem;
|
||||
}
|
||||
|
||||
.container-xxl {
|
||||
max-width: 1440px;
|
||||
padding-inline: 48px;
|
||||
}
|
||||
|
||||
@media (max-width: 767.98px) {
|
||||
.container-xxl {
|
||||
padding-inline: 16px;
|
||||
}
|
||||
}
|
||||
|
||||
.footer-copyright {
|
||||
color: var(--prism-footer-link);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,143 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
|
||||
import logo from '@/assets/logo-ssmg.png'
|
||||
import { useAuth } from '@/composables/useAuth'
|
||||
|
||||
const { user, logout } = useAuth()
|
||||
const router = useRouter()
|
||||
const menuOpen = ref(false)
|
||||
|
||||
async function onLogout() {
|
||||
menuOpen.value = false
|
||||
await logout()
|
||||
await router.push({ name: 'login' })
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<header class="app-header">
|
||||
<div class="container-xxl d-flex align-items-center justify-content-between gap-3">
|
||||
<RouterLink to="/" class="brand text-decoration-none">
|
||||
<img :src="logo" :alt="$t('app.logoAlt')" width="103" height="52" />
|
||||
<span class="brand-text">
|
||||
<span class="brand-name">{{ $t('app.name') }}</span>
|
||||
<span class="brand-tagline d-none d-sm-block">{{ $t('app.tagline') }}</span>
|
||||
</span>
|
||||
</RouterLink>
|
||||
|
||||
<template v-if="user">
|
||||
<nav class="d-none d-md-flex align-items-center gap-4">
|
||||
<span class="text-muted-prism">{{ $t('nav.doctor', { name: user.last_name }) }}</span>
|
||||
<button type="button" class="btn btn-link nav-logout p-0" @click="onLogout">
|
||||
{{ $t('nav.logout') }}
|
||||
</button>
|
||||
</nav>
|
||||
|
||||
<div class="d-md-none position-relative">
|
||||
<button
|
||||
type="button"
|
||||
class="btn menu-toggle"
|
||||
:aria-label="$t('nav.menu')"
|
||||
:aria-expanded="menuOpen"
|
||||
@click="menuOpen = !menuOpen"
|
||||
>
|
||||
<i class="bi bi-list fs-4" aria-hidden="true"></i>
|
||||
</button>
|
||||
<div v-if="menuOpen" class="menu-overlay prism-card">
|
||||
<p class="mb-2 text-muted-prism">{{ $t('nav.doctor', { name: user.last_name }) }}</p>
|
||||
<button type="button" class="btn btn-link nav-logout p-0" @click="onLogout">
|
||||
{{ $t('nav.logout') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</header>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.app-header {
|
||||
background: var(--prism-surface);
|
||||
border-top: 4px solid var(--prism-orange);
|
||||
padding: 0.6rem 0;
|
||||
}
|
||||
|
||||
.container-xxl {
|
||||
max-width: 1440px;
|
||||
padding-inline: 48px;
|
||||
}
|
||||
|
||||
@media (max-width: 767.98px) {
|
||||
.container-xxl {
|
||||
padding-inline: 16px;
|
||||
}
|
||||
}
|
||||
|
||||
.brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
.brand img {
|
||||
height: 52px;
|
||||
width: auto;
|
||||
}
|
||||
|
||||
.brand-text {
|
||||
border-left: 1px solid var(--prism-border);
|
||||
padding-left: 20px;
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
@media (max-width: 575.98px) {
|
||||
.brand img {
|
||||
height: 40px;
|
||||
}
|
||||
.brand-text {
|
||||
border-left: 0;
|
||||
padding-left: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.brand-name {
|
||||
display: block;
|
||||
color: var(--prism-navy);
|
||||
font-size: 1.375rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.brand-tagline {
|
||||
color: var(--prism-muted);
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.text-muted-prism {
|
||||
color: var(--prism-text);
|
||||
}
|
||||
|
||||
.nav-logout {
|
||||
color: var(--prism-orange);
|
||||
font-weight: 500;
|
||||
font-size: 0.875rem;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.menu-toggle {
|
||||
border: 1px solid var(--prism-border);
|
||||
border-radius: 6px;
|
||||
padding: 0.35rem 0.6rem;
|
||||
}
|
||||
|
||||
.menu-overlay {
|
||||
position: absolute;
|
||||
right: 0;
|
||||
top: calc(100% + 8px);
|
||||
min-width: 220px;
|
||||
padding: 1rem 1.25rem;
|
||||
z-index: 1000;
|
||||
box-shadow: 0 8px 24px rgb(9 41 51 / 12%);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,46 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
import type { FactorStatus } from '@/api/types'
|
||||
|
||||
const props = defineProps<{ level: number | null; status: FactorStatus }>()
|
||||
const { t } = useI18n()
|
||||
|
||||
const levelClass = computed(() =>
|
||||
props.status === 'ok' && props.level ? `level-${props.level}` : 'level-none',
|
||||
)
|
||||
|
||||
const text = computed(() => {
|
||||
if (props.status === 'unavailable') return t('factor.unavailableBadge')
|
||||
if (props.status === 'no_data') return t('factor.noDataBadge')
|
||||
return t(`factor.levels.${props.level ?? 'none'}`)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span class="color-badge" :class="[levelClass, { muted: status !== 'ok' || !level }]">
|
||||
{{ text }}
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.color-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
height: 28px;
|
||||
padding: 0 14px;
|
||||
border-radius: 14px;
|
||||
background: var(--level-color);
|
||||
color: #fff;
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 500;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.color-badge.muted {
|
||||
background: var(--prism-bg);
|
||||
border: 1px solid var(--prism-border);
|
||||
color: var(--prism-text);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,59 @@
|
||||
<script setup lang="ts">
|
||||
import type { Detail } from '@/api/types'
|
||||
|
||||
defineProps<{ details: Detail[] }>()
|
||||
|
||||
function dotClass(detail: Detail): string {
|
||||
return detail.status === 'exceeded' ? 'level-4' : 'level-1'
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<dl v-if="details.length" class="detail-list">
|
||||
<div v-for="detail in details" :key="detail.label" class="detail-row">
|
||||
<dt>{{ detail.label }}</dt>
|
||||
<dd>
|
||||
<span v-if="detail.status" class="dot" :class="dotClass(detail)" aria-hidden="true"></span>
|
||||
<span>{{ detail.value }}</span>
|
||||
<span v-if="detail.status === 'exceeded'" class="visually-hidden"> (dépassé)</span>
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.detail-list {
|
||||
background: var(--prism-bg);
|
||||
border-radius: 8px;
|
||||
padding: 6px 16px;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.detail-row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
min-height: 36px;
|
||||
padding: 0.4rem 16px;
|
||||
}
|
||||
|
||||
.detail-row + .detail-row {
|
||||
border-top: 1px solid var(--prism-border);
|
||||
}
|
||||
|
||||
dt {
|
||||
font-weight: 400;
|
||||
color: var(--prism-text);
|
||||
}
|
||||
|
||||
dd {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin: 0;
|
||||
color: var(--prism-navy);
|
||||
font-weight: 500;
|
||||
text-align: right;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,99 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
|
||||
import type { FactorResult } from '@/api/types'
|
||||
|
||||
import ColorBadge from './ColorBadge.vue'
|
||||
import DetailList from './DetailList.vue'
|
||||
import InfoTabs from './InfoTabs.vue'
|
||||
import ReferenceList from './ReferenceList.vue'
|
||||
|
||||
const props = defineProps<{ factor: FactorResult }>()
|
||||
defineEmits<{ retry: [] }>()
|
||||
|
||||
const levelClass = computed(() =>
|
||||
props.factor.status === 'ok' && props.factor.level ? `level-${props.factor.level}` : 'level-none',
|
||||
)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<article
|
||||
class="factor-card prism-card"
|
||||
:class="{ unavailable: factor.status !== 'ok' }"
|
||||
:aria-labelledby="`factor-${factor.code}`"
|
||||
>
|
||||
<header class="factor-header">
|
||||
<span class="factor-dot" :class="levelClass" aria-hidden="true"></span>
|
||||
<h2 :id="`factor-${factor.code}`" class="factor-title">{{ factor.label }}</h2>
|
||||
<ColorBadge class="ms-sm-auto" :level="factor.level" :status="factor.status" />
|
||||
</header>
|
||||
|
||||
<template v-if="factor.status === 'ok'">
|
||||
<p v-if="factor.summary" class="summary">{{ factor.summary }}</p>
|
||||
<DetailList :details="factor.details" />
|
||||
<InfoTabs :tabs="factor.tabs" />
|
||||
<ReferenceList :references="factor.references" />
|
||||
</template>
|
||||
|
||||
<template v-else>
|
||||
<p class="summary">
|
||||
{{
|
||||
factor.status === 'unavailable'
|
||||
? $t('factor.unavailable', { label: factor.label.toLowerCase() })
|
||||
: $t('factor.noData')
|
||||
}}
|
||||
</p>
|
||||
<div v-if="factor.status === 'unavailable'">
|
||||
<button type="button" class="btn btn-outline-primary" @click="$emit('retry')">
|
||||
{{ $t('factor.retry') }}
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
</article>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.factor-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
padding: 22px 24px;
|
||||
}
|
||||
|
||||
.factor-card.unavailable {
|
||||
border: 1px dashed var(--prism-level-none);
|
||||
}
|
||||
|
||||
.factor-header {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
@media (max-width: 575.98px) {
|
||||
.factor-header :deep(.color-badge) {
|
||||
order: 3;
|
||||
}
|
||||
}
|
||||
|
||||
.factor-dot {
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
border-radius: 50%;
|
||||
background: var(--level-color);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.factor-title {
|
||||
font-size: 1.25rem;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.summary {
|
||||
color: var(--prism-navy);
|
||||
font-size: 0.9375rem;
|
||||
font-weight: 500;
|
||||
margin: 0;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,135 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, useId } from 'vue'
|
||||
|
||||
import type { FactorResult } from '@/api/types'
|
||||
|
||||
const props = defineProps<{ tabs: FactorResult['tabs'] }>()
|
||||
|
||||
type TabKey = 'health_effects' | 'actions' | 'legend'
|
||||
const keys: TabKey[] = ['health_effects', 'actions', 'legend']
|
||||
const active = ref<TabKey>('health_effects')
|
||||
const id = useId()
|
||||
|
||||
/** Les textes de la SSMG sont rédigés une idée par ligne : rendus en liste à puces. */
|
||||
function lines(text: string): string[] {
|
||||
return text
|
||||
.split('\n')
|
||||
.map((line) => line.replace(/^[-•]\s*/, '').trim())
|
||||
.filter(Boolean)
|
||||
}
|
||||
|
||||
const content = computed(() =>
|
||||
active.value === 'legend' ? lines(props.tabs.legend.text) : lines(props.tabs[active.value]),
|
||||
)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<div class="tab-list" role="tablist">
|
||||
<button
|
||||
v-for="key in keys"
|
||||
:id="`${id}-tab-${key}`"
|
||||
:key="key"
|
||||
type="button"
|
||||
role="tab"
|
||||
class="tab"
|
||||
:class="{ active: active === key }"
|
||||
:aria-selected="active === key"
|
||||
:aria-controls="`${id}-panel`"
|
||||
@click="active = key"
|
||||
>
|
||||
{{ $t(`factor.tabs.${key}`) }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
:id="`${id}-panel`"
|
||||
role="tabpanel"
|
||||
:aria-labelledby="`${id}-tab-${active}`"
|
||||
class="tab-panel"
|
||||
>
|
||||
<template v-if="active === 'legend'">
|
||||
<ul v-if="tabs.legend.scale.length" class="list-unstyled scale">
|
||||
<li v-for="item in tabs.legend.scale" :key="item.level + item.label">
|
||||
<span class="dot" :class="`level-${item.level}`" aria-hidden="true"></span>
|
||||
{{ item.label }}
|
||||
</li>
|
||||
</ul>
|
||||
<p v-if="tabs.legend.source" class="source">
|
||||
{{ $t('factor.source', { source: tabs.legend.source }) }}
|
||||
</p>
|
||||
</template>
|
||||
<ul v-if="content.length" class="bullets">
|
||||
<li v-for="line in content" :key="line">{{ line }}</li>
|
||||
</ul>
|
||||
<p v-else-if="active !== 'legend' || !tabs.legend.scale.length" class="empty">
|
||||
{{ $t('factor.emptyTab') }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.tab-list {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.tab {
|
||||
height: 32px;
|
||||
padding: 0 14px;
|
||||
border-radius: 14px;
|
||||
border: 1px solid var(--prism-border);
|
||||
background: var(--prism-surface);
|
||||
color: var(--prism-text);
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.tab.active {
|
||||
background: var(--prism-navy);
|
||||
border-color: var(--prism-navy);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.tab:focus-visible {
|
||||
outline: 2px solid var(--prism-orange);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.tab-panel {
|
||||
padding-top: 14px;
|
||||
}
|
||||
|
||||
.bullets {
|
||||
margin: 0;
|
||||
padding-left: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.bullets li {
|
||||
position: relative;
|
||||
padding-left: 12px;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.bullets li::before {
|
||||
content: '•';
|
||||
position: absolute;
|
||||
left: 0;
|
||||
}
|
||||
|
||||
.scale li {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.source,
|
||||
.empty {
|
||||
color: var(--prism-muted);
|
||||
margin-bottom: 0;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,32 @@
|
||||
<script setup lang="ts">
|
||||
import type { Reference } from '@/api/types'
|
||||
|
||||
defineProps<{ references: Reference[] }>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<p v-if="references.length" class="references">
|
||||
{{ $t('factor.references') }}
|
||||
<template v-for="ref in references" :key="ref.n">
|
||||
<a v-if="ref.url" :href="ref.url" target="_blank" rel="noopener noreferrer">
|
||||
{{ ref.n }}. {{ ref.title }}</a
|
||||
><span v-else>{{ ref.n }}. {{ ref.title }}</span>
|
||||
</template>
|
||||
</p>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.references {
|
||||
border-top: 1px solid var(--prism-border);
|
||||
padding-top: 14px;
|
||||
margin: 0;
|
||||
font-size: 0.75rem;
|
||||
color: var(--prism-muted);
|
||||
}
|
||||
|
||||
.references a,
|
||||
.references span {
|
||||
margin-left: 0.5rem;
|
||||
color: var(--prism-muted);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,233 @@
|
||||
<script setup lang="ts">
|
||||
import { Map as MapLibreMap, Marker, NavigationControl, ScaleControl } from 'maplibre-gl'
|
||||
import { onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
|
||||
import type { Assessment } from '@/api/types'
|
||||
|
||||
const props = defineProps<{ location: Assessment['location'] | null }>()
|
||||
|
||||
const WALONMAP_WMS = 'https://geoservices.wallonie.be/arcgis/services'
|
||||
// Fond OpenStreetMap : les serveurs publics ne sont pas prévus pour la production
|
||||
// (specs, risque 12). À remplacer par un fournisseur de tuiles avant la mise en production.
|
||||
const OSM_TILES = 'https://tile.openstreetmap.org/{z}/{x}/{y}.png'
|
||||
const BELGIUM: [number, number] = [4.47, 50.5]
|
||||
|
||||
function wms(service: string, layers: string): string {
|
||||
const params = new URLSearchParams({
|
||||
service: 'WMS',
|
||||
request: 'GetMap',
|
||||
version: '1.3.0',
|
||||
layers,
|
||||
styles: '',
|
||||
format: 'image/png',
|
||||
transparent: 'true',
|
||||
crs: 'EPSG:3857',
|
||||
width: '256',
|
||||
height: '256',
|
||||
})
|
||||
return `${WALONMAP_WMS}/${service}/MapServer/WMSServer?${params}&bbox={bbox-epsg-3857}`
|
||||
}
|
||||
|
||||
const overlays = [
|
||||
{ id: 'flood', url: wms('EAU/ALEA_INOND', '2'), color: '#00b0f0' },
|
||||
{ id: 'noise', url: wms('INDUSTRIES_SERVICES/BRUIT_MROAD_2017', '1'), color: '#e85b25' },
|
||||
] as const
|
||||
|
||||
type OverlayId = (typeof overlays)[number]['id']
|
||||
|
||||
const container = ref<HTMLDivElement>()
|
||||
const layersPanel = ref<HTMLFieldSetElement>()
|
||||
const visible = ref<Record<OverlayId, boolean>>({ flood: true, noise: false })
|
||||
let map: MapLibreMap | null = null
|
||||
let marker: Marker | null = null
|
||||
|
||||
onMounted(() => {
|
||||
const instance = new MapLibreMap({
|
||||
container: container.value!,
|
||||
center: BELGIUM,
|
||||
zoom: 7,
|
||||
attributionControl: { compact: false },
|
||||
style: {
|
||||
version: 8,
|
||||
sources: {
|
||||
osm: {
|
||||
type: 'raster',
|
||||
tiles: [OSM_TILES],
|
||||
tileSize: 256,
|
||||
maxzoom: 19,
|
||||
attribution: '© OpenStreetMap contributors',
|
||||
},
|
||||
...Object.fromEntries(
|
||||
overlays.map((o) => [
|
||||
o.id,
|
||||
{ type: 'raster', tiles: [o.url], tileSize: 256, attribution: '© SPW – WalOnMap' },
|
||||
]),
|
||||
),
|
||||
},
|
||||
layers: [
|
||||
{ id: 'osm', type: 'raster', source: 'osm' },
|
||||
...overlays.map((o) => ({
|
||||
id: o.id,
|
||||
type: 'raster' as const,
|
||||
source: o.id,
|
||||
paint: { 'raster-opacity': 0.6 },
|
||||
layout: { visibility: visible.value[o.id] ? ('visible' as const) : ('none' as const) },
|
||||
})),
|
||||
],
|
||||
},
|
||||
})
|
||||
instance.addControl(new NavigationControl({ showCompass: false }), 'top-right')
|
||||
instance.addControl(new ScaleControl({ unit: 'metric' }), 'bottom-left')
|
||||
map = instance
|
||||
showLocation()
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
map?.remove()
|
||||
map = null
|
||||
})
|
||||
|
||||
function showLocation() {
|
||||
if (!map || !props.location) return
|
||||
const lngLat: [number, number] = [props.location.lon, props.location.lat]
|
||||
marker?.remove()
|
||||
marker = new Marker({ color: '#e85b25' }).setLngLat(lngLat).addTo(map)
|
||||
// La mise en page peut avoir changé depuis la création de la carte.
|
||||
map.resize()
|
||||
// Décale le centre sous le panneau des couches pour que le marqueur reste visible.
|
||||
const top = (layersPanel.value?.offsetHeight ?? 0) + 12
|
||||
map.jumpTo({ center: lngLat, zoom: 15, padding: { top, bottom: 0, left: 0, right: 0 } })
|
||||
}
|
||||
|
||||
function toggle(id: OverlayId) {
|
||||
visible.value[id] = !visible.value[id]
|
||||
map?.setLayoutProperty(id, 'visibility', visible.value[id] ? 'visible' : 'none')
|
||||
}
|
||||
|
||||
watch(() => props.location, showLocation, { flush: 'post' })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="result-map prism-card">
|
||||
<div ref="container" class="map" role="region" :aria-label="$t('map.label')"></div>
|
||||
|
||||
<fieldset ref="layersPanel" class="map-panel layers">
|
||||
<legend>{{ $t('map.layers') }}</legend>
|
||||
<div class="form-check">
|
||||
<input id="layer-osm" class="form-check-input" type="checkbox" checked disabled />
|
||||
<label class="form-check-label" for="layer-osm">{{ $t('map.basemap') }}</label>
|
||||
</div>
|
||||
<div v-for="overlay in overlays" :key="overlay.id" class="form-check">
|
||||
<input
|
||||
:id="`layer-${overlay.id}`"
|
||||
class="form-check-input"
|
||||
type="checkbox"
|
||||
:checked="visible[overlay.id]"
|
||||
@change="toggle(overlay.id)"
|
||||
/>
|
||||
<label class="form-check-label" :for="`layer-${overlay.id}`">
|
||||
{{ $t(`map.${overlay.id}`) }}
|
||||
</label>
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<div class="map-panel legend">
|
||||
<strong>{{ $t('map.legend') }}</strong>
|
||||
<div>
|
||||
<span class="swatch round" style="background: #e85b25"></span>{{ $t('map.patient') }}
|
||||
</div>
|
||||
<template v-for="overlay in overlays" :key="overlay.id">
|
||||
<div v-if="visible[overlay.id]">
|
||||
<span class="swatch" :style="{ background: overlay.color }"></span>
|
||||
{{ $t(`map.${overlay.id}`) }}
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.result-map {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
height: 720px;
|
||||
}
|
||||
|
||||
@media (min-width: 992px) {
|
||||
.result-map {
|
||||
position: sticky;
|
||||
top: 24px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 991.98px) {
|
||||
.result-map {
|
||||
height: 240px;
|
||||
}
|
||||
.legend {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
.map {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
}
|
||||
|
||||
.map-panel {
|
||||
position: absolute;
|
||||
left: 12px;
|
||||
z-index: 2;
|
||||
background: var(--prism-surface);
|
||||
border: 1px solid var(--prism-border);
|
||||
border-radius: 8px;
|
||||
padding: 10px 12px;
|
||||
font-size: 0.6875rem;
|
||||
box-shadow: 0 2px 8px rgb(9 41 51 / 10%);
|
||||
}
|
||||
|
||||
.layers {
|
||||
top: 12px;
|
||||
}
|
||||
|
||||
.layers legend {
|
||||
float: none;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 700;
|
||||
color: var(--prism-navy);
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.form-check {
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
|
||||
.form-check-input:checked {
|
||||
background-color: var(--prism-orange);
|
||||
border-color: var(--prism-orange);
|
||||
}
|
||||
|
||||
.legend {
|
||||
bottom: 40px;
|
||||
}
|
||||
|
||||
.legend strong {
|
||||
display: block;
|
||||
font-size: 0.75rem;
|
||||
color: var(--prism-navy);
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.swatch {
|
||||
display: inline-block;
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
margin-right: 8px;
|
||||
border-radius: 2px;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.swatch.round {
|
||||
border-radius: 50%;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,59 @@
|
||||
import { computed, ref } from 'vue'
|
||||
|
||||
import { api, ApiError } from '@/api/client'
|
||||
import type { User } from '@/api/types'
|
||||
|
||||
// État partagé : un simple ref suffit (pas de Pinia, specs §3).
|
||||
const user = ref<User | null>(null)
|
||||
const loaded = ref(false)
|
||||
|
||||
export function useAuth() {
|
||||
/** Charge l'utilisateur courant une seule fois ; dépose aussi le cookie CSRF. */
|
||||
async function load(force = false): Promise<User | null> {
|
||||
if (loaded.value && !force) {
|
||||
return user.value
|
||||
}
|
||||
try {
|
||||
user.value = await api.me()
|
||||
} catch (error) {
|
||||
if (!(error instanceof ApiError) || error.status !== 403) {
|
||||
throw error
|
||||
}
|
||||
user.value = null
|
||||
} finally {
|
||||
loaded.value = true
|
||||
}
|
||||
return user.value
|
||||
}
|
||||
|
||||
async function login(email: string, password: string): Promise<User> {
|
||||
const result = await api.login(email, password)
|
||||
user.value = result.user
|
||||
// Django renouvelle le jeton CSRF à la connexion : on le recharge.
|
||||
await load(true)
|
||||
return result.user
|
||||
}
|
||||
|
||||
async function logout(): Promise<void> {
|
||||
try {
|
||||
await api.logout()
|
||||
} finally {
|
||||
user.value = null
|
||||
await load(true)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
user,
|
||||
isAuthenticated: computed(() => user.value !== null),
|
||||
load,
|
||||
login,
|
||||
logout,
|
||||
}
|
||||
}
|
||||
|
||||
/** Réinitialise l'état (tests). */
|
||||
export function resetAuth() {
|
||||
user.value = null
|
||||
loaded.value = false
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { createI18n } from 'vue-i18n'
|
||||
|
||||
import fr from './locales/fr.json'
|
||||
|
||||
export default createI18n({
|
||||
legacy: false,
|
||||
locale: 'fr',
|
||||
fallbackLocale: 'fr',
|
||||
messages: { fr },
|
||||
})
|
||||
@@ -0,0 +1,85 @@
|
||||
{
|
||||
"app": {
|
||||
"name": "PRISM",
|
||||
"tagline": "Environnement et santé",
|
||||
"disclaimer": "Outil complémentaire d'aide à la consultation : il ne remplace pas un diagnostic.",
|
||||
"copyright": "© SSMG – Société Scientifique de Médecine Générale",
|
||||
"logoAlt": "SSMG – Société Scientifique de Médecine Générale"
|
||||
},
|
||||
"nav": {
|
||||
"doctor": "Dr {name}",
|
||||
"logout": "Déconnexion",
|
||||
"menu": "Menu"
|
||||
},
|
||||
"login": {
|
||||
"title": "Connexion",
|
||||
"intro": "Accédez à l'évaluation de l'exposome environnemental de vos patients.",
|
||||
"email": "Adresse e-mail",
|
||||
"emailPlaceholder": "prenom.nom{'@'}exemple.be",
|
||||
"password": "Mot de passe",
|
||||
"submit": "Se connecter",
|
||||
"submitting": "Connexion…",
|
||||
"error": "Connexion impossible. Réessayez dans un instant."
|
||||
},
|
||||
"assessment": {
|
||||
"addressLabel": "Adresse du patient",
|
||||
"addressPlaceholder": "Rue, numéro, code postal, commune",
|
||||
"submit": "Analyser",
|
||||
"submitting": "Analyse…",
|
||||
"recognized": "Adresse reconnue : {address} — {region}",
|
||||
"regions": {
|
||||
"WAL": "Région wallonne",
|
||||
"BXL": "Région de Bruxelles-Capitale"
|
||||
},
|
||||
"errors": {
|
||||
"address_not_found": "Adresse introuvable. Vérifiez la rue, le numéro et le code postal.",
|
||||
"out_of_coverage": "Cette adresse est hors couverture : PRISM couvre la Wallonie et Bruxelles.",
|
||||
"geocoding_unavailable": "Le service de géocodage est indisponible. Réessayez dans un instant.",
|
||||
"throttled": "Trop d'analyses en peu de temps. Réessayez plus tard.",
|
||||
"generic": "L'analyse a échoué. Réessayez dans un instant."
|
||||
}
|
||||
},
|
||||
"factor": {
|
||||
"levels": {
|
||||
"1": "Impact faible",
|
||||
"2": "Impact modéré",
|
||||
"3": "Impact élevé",
|
||||
"4": "Impact très élevé",
|
||||
"none": "Niveau non défini"
|
||||
},
|
||||
"unavailableBadge": "Donnée indisponible",
|
||||
"noDataBadge": "Donnée absente",
|
||||
"unavailable": "Le service de données « {label} » ne répond pas pour le moment.",
|
||||
"noData": "Aucune donnée n'est disponible pour cette adresse.",
|
||||
"retry": "Réessayer",
|
||||
"loading": "Chargement…",
|
||||
"tabs": {
|
||||
"health_effects": "Effets sur la santé",
|
||||
"actions": "Pistes d'action",
|
||||
"legend": "Légende"
|
||||
},
|
||||
"emptyTab": "Contenu en cours de validation par la cellule Environnement de la SSMG.",
|
||||
"source": "Source : {source}",
|
||||
"references": "Références :"
|
||||
},
|
||||
"map": {
|
||||
"layers": "Couches",
|
||||
"basemap": "Fond de carte (OpenStreetMap)",
|
||||
"flood": "Aléa d'inondation (WalOnMap)",
|
||||
"noise": "Bruit routier – Lden (WalOnMap)",
|
||||
"legend": "Légende",
|
||||
"patient": "Adresse du patient",
|
||||
"label": "Carte de l'adresse du patient"
|
||||
},
|
||||
"errors": {
|
||||
"404": {
|
||||
"title": "Page introuvable",
|
||||
"text": "La page demandée n'existe pas ou a été déplacée."
|
||||
},
|
||||
"403": {
|
||||
"title": "Accès refusé",
|
||||
"text": "Vous n'avez pas les droits nécessaires pour accéder à cette page."
|
||||
},
|
||||
"back": "Retour à l'évaluation"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import 'bootstrap/dist/css/bootstrap.min.css'
|
||||
import 'bootstrap-icons/font/bootstrap-icons.min.css'
|
||||
import 'maplibre-gl/dist/maplibre-gl.css'
|
||||
import '@fontsource/roboto/300.css'
|
||||
import '@fontsource/roboto/400.css'
|
||||
import '@fontsource/roboto/500.css'
|
||||
import '@fontsource/roboto/700.css'
|
||||
import './styles/main.css'
|
||||
|
||||
import { createApp } from 'vue'
|
||||
|
||||
import App from './App.vue'
|
||||
import i18n from './i18n'
|
||||
import router from './router'
|
||||
|
||||
createApp(App).use(i18n).use(router).mount('#app')
|
||||
@@ -0,0 +1,61 @@
|
||||
import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
|
||||
|
||||
import { useAuth } from '@/composables/useAuth'
|
||||
|
||||
declare module 'vue-router' {
|
||||
interface RouteMeta {
|
||||
/** Page réservée aux utilisateurs connectés. */
|
||||
requiresAuth?: boolean
|
||||
/** Page d'accès : redirige vers l'évaluation si l'utilisateur est déjà connecté. */
|
||||
guestOnly?: boolean
|
||||
}
|
||||
}
|
||||
|
||||
export const routes: RouteRecordRaw[] = [
|
||||
{
|
||||
path: '/',
|
||||
name: 'assessment',
|
||||
component: () => import('@/views/AssessmentView.vue'),
|
||||
meta: { requiresAuth: true },
|
||||
},
|
||||
{
|
||||
path: '/login',
|
||||
name: 'login',
|
||||
component: () => import('@/views/LoginView.vue'),
|
||||
meta: { guestOnly: true },
|
||||
},
|
||||
{
|
||||
path: '/403',
|
||||
name: 'forbidden',
|
||||
component: () => import('@/views/ErrorView.vue'),
|
||||
props: { code: 403 },
|
||||
},
|
||||
{
|
||||
path: '/:pathMatch(.*)*',
|
||||
name: 'not-found',
|
||||
component: () => import('@/views/ErrorView.vue'),
|
||||
props: { code: 404 },
|
||||
},
|
||||
]
|
||||
|
||||
export function createAppRouter() {
|
||||
const router = createRouter({
|
||||
history: createWebHistory(import.meta.env.BASE_URL),
|
||||
routes,
|
||||
})
|
||||
|
||||
router.beforeEach(async (to) => {
|
||||
const { load } = useAuth()
|
||||
const user = await load()
|
||||
if (to.meta.requiresAuth && !user) {
|
||||
return { name: 'login', query: to.fullPath === '/' ? {} : { next: to.fullPath } }
|
||||
}
|
||||
if (to.meta.guestOnly && user) {
|
||||
return { name: 'assessment' }
|
||||
}
|
||||
})
|
||||
|
||||
return router
|
||||
}
|
||||
|
||||
export default createAppRouter()
|
||||
@@ -0,0 +1,139 @@
|
||||
/*
|
||||
* Charte PRISM (maquettes Penpot, charte ssmg.be).
|
||||
* Bootstrap 5 est utilisé en CSS seul ; ses variables sont surchargées ici.
|
||||
*/
|
||||
|
||||
:root {
|
||||
--prism-orange: #e85b25;
|
||||
--prism-navy: #092933;
|
||||
--prism-text: #464d5f;
|
||||
--prism-muted: #6b7280;
|
||||
--prism-border: #d9d4d0;
|
||||
--prism-bg: #f6f4f2;
|
||||
--prism-surface: #ffffff;
|
||||
--prism-info-bg: #e6f6fd;
|
||||
--prism-footer-link: #74c5da;
|
||||
|
||||
--prism-level-1: #3e9b4f;
|
||||
--prism-level-2: #e0b400; /* jaune : absent des maquettes, à valider */
|
||||
--prism-level-3: #f2994a;
|
||||
--prism-level-4: #d64545;
|
||||
--prism-level-none: #9aa0a6;
|
||||
|
||||
--bs-body-font-family: 'Roboto', system-ui, sans-serif;
|
||||
--bs-body-color: var(--prism-text);
|
||||
--bs-body-bg: var(--prism-bg);
|
||||
--bs-heading-color: var(--prism-navy);
|
||||
--bs-border-color: var(--prism-border);
|
||||
--bs-link-color: var(--prism-orange);
|
||||
--bs-link-color-rgb: 232, 91, 37;
|
||||
--bs-link-hover-color: #c74a1b;
|
||||
--bs-link-hover-color-rgb: 199, 74, 27;
|
||||
--bs-primary: var(--prism-orange);
|
||||
--bs-primary-rgb: 232, 91, 37;
|
||||
--bs-focus-ring-color: rgba(232, 91, 37, 0.25);
|
||||
}
|
||||
|
||||
body {
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
h1,
|
||||
h2,
|
||||
h3 {
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
/* Boutons --------------------------------------------------------------- */
|
||||
|
||||
.btn {
|
||||
--bs-btn-font-weight: 500;
|
||||
--bs-btn-border-radius: 6px;
|
||||
--bs-btn-padding-y: 0.65rem;
|
||||
--bs-btn-padding-x: 1.25rem;
|
||||
--bs-btn-font-size: 0.9375rem;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
--bs-btn-bg: var(--prism-orange);
|
||||
--bs-btn-border-color: var(--prism-orange);
|
||||
--bs-btn-hover-bg: #c74a1b;
|
||||
--bs-btn-hover-border-color: #c74a1b;
|
||||
--bs-btn-active-bg: #b14218;
|
||||
--bs-btn-active-border-color: #b14218;
|
||||
--bs-btn-disabled-bg: var(--prism-orange);
|
||||
--bs-btn-disabled-border-color: var(--prism-orange);
|
||||
}
|
||||
|
||||
.btn-outline-primary {
|
||||
--bs-btn-color: var(--prism-orange);
|
||||
--bs-btn-border-color: var(--prism-orange);
|
||||
--bs-btn-hover-bg: var(--prism-orange);
|
||||
--bs-btn-hover-border-color: var(--prism-orange);
|
||||
--bs-btn-active-bg: #c74a1b;
|
||||
--bs-btn-active-border-color: #c74a1b;
|
||||
--bs-btn-bg: var(--prism-surface);
|
||||
}
|
||||
|
||||
/* Champs ---------------------------------------------------------------- */
|
||||
|
||||
.form-label {
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 500;
|
||||
color: var(--prism-navy);
|
||||
}
|
||||
|
||||
.form-control {
|
||||
border-radius: 6px;
|
||||
padding: 0.7rem 0.875rem;
|
||||
font-size: 0.9375rem;
|
||||
color: var(--prism-navy);
|
||||
}
|
||||
|
||||
.form-control:focus {
|
||||
border-color: var(--prism-orange);
|
||||
box-shadow: 0 0 0 0.2rem var(--bs-focus-ring-color);
|
||||
}
|
||||
|
||||
/* Surfaces -------------------------------------------------------------- */
|
||||
|
||||
.prism-card {
|
||||
background: var(--prism-surface);
|
||||
border: 1px solid var(--prism-border);
|
||||
border-radius: 12px;
|
||||
}
|
||||
|
||||
.prism-alert-info {
|
||||
background: var(--prism-info-bg);
|
||||
border-radius: 8px;
|
||||
color: var(--prism-navy);
|
||||
font-weight: 500;
|
||||
padding: 0.75rem 1.25rem;
|
||||
}
|
||||
|
||||
/* Niveaux --------------------------------------------------------------- */
|
||||
|
||||
.level-1 {
|
||||
--level-color: var(--prism-level-1);
|
||||
}
|
||||
.level-2 {
|
||||
--level-color: var(--prism-level-2);
|
||||
}
|
||||
.level-3 {
|
||||
--level-color: var(--prism-level-3);
|
||||
}
|
||||
.level-4 {
|
||||
--level-color: var(--prism-level-4);
|
||||
}
|
||||
.level-none {
|
||||
--level-color: var(--prism-level-none);
|
||||
}
|
||||
|
||||
.dot {
|
||||
display: inline-block;
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
border-radius: 50%;
|
||||
background: var(--level-color);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
|
||||
import { api, ApiError } from '@/api/client'
|
||||
import type { Assessment } from '@/api/types'
|
||||
import AddressForm from '@/components/AddressForm.vue'
|
||||
import AlertBanner from '@/components/AlertBanner.vue'
|
||||
import FactorCard from '@/components/FactorCard.vue'
|
||||
import ResultMap from '@/components/ResultMap.vue'
|
||||
import { useAuth } from '@/composables/useAuth'
|
||||
|
||||
const router = useRouter()
|
||||
const { logout } = useAuth()
|
||||
|
||||
// L'adresse ne quitte pas la mémoire du composant : ni URL, ni stockage local.
|
||||
const address = ref('')
|
||||
const result = ref<Assessment | null>(null)
|
||||
const errorKey = ref('')
|
||||
const loading = ref(false)
|
||||
|
||||
const KNOWN_ERRORS = ['address_not_found', 'out_of_coverage', 'geocoding_unavailable']
|
||||
|
||||
async function analyse(value: string) {
|
||||
address.value = value
|
||||
errorKey.value = ''
|
||||
loading.value = true
|
||||
try {
|
||||
result.value = await api.assess(value)
|
||||
} catch (e) {
|
||||
result.value = null
|
||||
if (e instanceof ApiError && e.status === 403) {
|
||||
// Session expirée.
|
||||
await logout()
|
||||
await router.push({ name: 'login' })
|
||||
return
|
||||
}
|
||||
if (e instanceof ApiError && e.status === 429) {
|
||||
errorKey.value = 'assessment.errors.throttled'
|
||||
} else if (e instanceof ApiError && e.code && KNOWN_ERRORS.includes(e.code)) {
|
||||
errorKey.value = `assessment.errors.${e.code}`
|
||||
} else {
|
||||
errorKey.value = 'assessment.errors.generic'
|
||||
}
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const location = computed(() => result.value?.location ?? null)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="assessment container-xxl">
|
||||
<AddressForm :loading="loading" @submit="analyse" />
|
||||
|
||||
<AlertBanner v-if="errorKey" variant="error">{{ $t(errorKey) }}</AlertBanner>
|
||||
<AlertBanner v-else-if="result" variant="info">
|
||||
{{
|
||||
$t('assessment.recognized', {
|
||||
address,
|
||||
region: $t(`assessment.regions.${result.location.region}`),
|
||||
})
|
||||
}}
|
||||
</AlertBanner>
|
||||
|
||||
<div class="row g-4">
|
||||
<div class="col-lg-5">
|
||||
<ResultMap :location="location" />
|
||||
</div>
|
||||
<div v-if="result" class="col-lg-7 d-flex flex-column gap-4" aria-live="polite">
|
||||
<FactorCard
|
||||
v-for="factor in result.factors"
|
||||
:key="factor.code"
|
||||
:factor="factor"
|
||||
@retry="analyse(address)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.assessment {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 24px;
|
||||
max-width: 1440px;
|
||||
padding: 32px 48px 40px;
|
||||
}
|
||||
|
||||
@media (max-width: 767.98px) {
|
||||
.assessment {
|
||||
padding: 16px 16px 32px;
|
||||
gap: 16px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,50 @@
|
||||
<script setup lang="ts">
|
||||
defineProps<{ code: 403 | 404 }>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="error-page">
|
||||
<section class="error-card prism-card text-center" aria-labelledby="error-title">
|
||||
<p class="error-code" aria-hidden="true">{{ code }}</p>
|
||||
<h1 id="error-title">{{ $t(`errors.${code}.title`) }}</h1>
|
||||
<p>{{ $t(`errors.${code}.text`) }}</p>
|
||||
<RouterLink to="/" class="btn btn-primary back">{{ $t('errors.back') }}</RouterLink>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.error-page {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
padding: 120px 16px;
|
||||
}
|
||||
|
||||
@media (max-width: 575.98px) {
|
||||
.error-page {
|
||||
padding: 48px 16px;
|
||||
}
|
||||
}
|
||||
|
||||
.error-card {
|
||||
width: 100%;
|
||||
max-width: 560px;
|
||||
padding: 48px 32px;
|
||||
}
|
||||
|
||||
.error-code {
|
||||
color: var(--prism-orange);
|
||||
font-size: 4.5rem;
|
||||
font-weight: 700;
|
||||
line-height: 1;
|
||||
margin-bottom: 1.25rem;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 1.5rem;
|
||||
}
|
||||
|
||||
.back {
|
||||
min-width: 240px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,112 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
|
||||
import { ApiError } from '@/api/client'
|
||||
import AlertBanner from '@/components/AlertBanner.vue'
|
||||
import { useAuth } from '@/composables/useAuth'
|
||||
|
||||
const { login } = useAuth()
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
|
||||
const email = ref('')
|
||||
const password = ref('')
|
||||
const error = ref('')
|
||||
const loading = ref(false)
|
||||
|
||||
async function onSubmit() {
|
||||
error.value = ''
|
||||
loading.value = true
|
||||
try {
|
||||
await login(email.value, password.value)
|
||||
const next = typeof route.query.next === 'string' && route.query.next.startsWith('/')
|
||||
await router.push(next ? (route.query.next as string) : { name: 'assessment' })
|
||||
} catch (e) {
|
||||
error.value = e instanceof ApiError && e.status === 400 ? e.message : 'login.error'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="auth-page">
|
||||
<section class="auth-card prism-card" aria-labelledby="login-title">
|
||||
<h1 id="login-title">{{ $t('login.title') }}</h1>
|
||||
<p class="intro">{{ $t('login.intro') }}</p>
|
||||
|
||||
<AlertBanner v-if="error" variant="error" class="mb-3">
|
||||
{{ error === 'login.error' ? $t('login.error') : error }}
|
||||
</AlertBanner>
|
||||
|
||||
<form novalidate @submit.prevent="onSubmit">
|
||||
<div class="mb-3">
|
||||
<label for="email" class="form-label">{{ $t('login.email') }}</label>
|
||||
<input
|
||||
id="email"
|
||||
v-model="email"
|
||||
type="email"
|
||||
class="form-control"
|
||||
autocomplete="username"
|
||||
required
|
||||
:placeholder="$t('login.emailPlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
<div class="mb-4">
|
||||
<label for="password" class="form-label">{{ $t('login.password') }}</label>
|
||||
<input
|
||||
id="password"
|
||||
v-model="password"
|
||||
type="password"
|
||||
class="form-control"
|
||||
autocomplete="current-password"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
type="submit"
|
||||
class="btn btn-primary w-100"
|
||||
:disabled="loading || !email || !password"
|
||||
>
|
||||
{{ loading ? $t('login.submitting') : $t('login.submit') }}
|
||||
</button>
|
||||
</form>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.auth-page {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
padding: 100px 16px;
|
||||
}
|
||||
|
||||
@media (max-width: 575.98px) {
|
||||
.auth-page {
|
||||
padding: 32px 16px;
|
||||
}
|
||||
}
|
||||
|
||||
.auth-card {
|
||||
width: 100%;
|
||||
max-width: 460px;
|
||||
padding: 40px 39px;
|
||||
}
|
||||
|
||||
@media (max-width: 575.98px) {
|
||||
.auth-card {
|
||||
padding: 28px 20px;
|
||||
}
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 1.75rem;
|
||||
margin-bottom: 1.25rem;
|
||||
}
|
||||
|
||||
.intro {
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"extends": "@vue/tsconfig/tsconfig.dom.json",
|
||||
"include": ["env.d.ts", "src/**/*", "src/**/*.vue"],
|
||||
"exclude": ["src/**/__tests__/*"],
|
||||
"compilerOptions": {
|
||||
// Extra safety for array and object lookups, but may have false positives.
|
||||
"noUncheckedIndexedAccess": true,
|
||||
|
||||
// Path mapping for cleaner imports.
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
},
|
||||
|
||||
// `vue-tsc --build` produces a .tsbuildinfo file for incremental type-checking.
|
||||
// Specified here to keep it out of the root directory.
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.node.json"
|
||||
},
|
||||
{
|
||||
"path": "./tsconfig.app.json"
|
||||
},
|
||||
{
|
||||
"path": "./tsconfig.vitest.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
// TSConfig for modules that run in Node.js environment via either transpilation or type-stripping.
|
||||
{
|
||||
"extends": "@tsconfig/node24/tsconfig.json",
|
||||
"include": [
|
||||
"vite.config.*",
|
||||
"vitest.config.*",
|
||||
"cypress.config.*",
|
||||
"playwright.config.*",
|
||||
"eslint.config.*"
|
||||
],
|
||||
"compilerOptions": {
|
||||
// Most tools use transpilation instead of Node.js's native type-stripping.
|
||||
// Bundler mode provides a smoother developer experience.
|
||||
"module": "preserve",
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
|
||||
// Include Node.js types and avoid accidentally including other `@types/*` packages.
|
||||
"types": ["node"],
|
||||
|
||||
// Disable emitting output during `vue-tsc --build`, which is used for type-checking only.
|
||||
"noEmit": true,
|
||||
|
||||
// `vue-tsc --build` produces a .tsbuildinfo file for incremental type-checking.
|
||||
// Specified here to keep it out of the root directory.
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"extends": "./tsconfig.app.json",
|
||||
|
||||
// Override to include only test files and clear exclusions.
|
||||
// Application code imported in tests is automatically included via module resolution.
|
||||
"include": ["src/**/__tests__/*", "env.d.ts"],
|
||||
"exclude": [],
|
||||
|
||||
"compilerOptions": {
|
||||
// Vitest runs in a different environment than the application code.
|
||||
// Adjust lib and types accordingly.
|
||||
"lib": [],
|
||||
"types": ["node", "jsdom"],
|
||||
|
||||
// `vue-tsc --build` produces a .tsbuildinfo file for incremental type-checking.
|
||||
// Specified here to keep it out of the root directory.
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.vitest.tsbuildinfo"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { fileURLToPath, URL } from 'node:url'
|
||||
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
import { defineConfig } from 'vite'
|
||||
import vueDevTools from 'vite-plugin-vue-devtools'
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [vue(), vueDevTools()],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': fileURLToPath(new URL('./src', import.meta.url)),
|
||||
},
|
||||
},
|
||||
server: {
|
||||
// Même origine que l'API : les cookies de session et CSRF fonctionnent sans CORS.
|
||||
proxy: {
|
||||
'/api': process.env.API_PROXY_TARGET ?? 'http://localhost:8000',
|
||||
'/admin': process.env.API_PROXY_TARGET ?? 'http://localhost:8000',
|
||||
'/static': process.env.API_PROXY_TARGET ?? 'http://localhost:8000',
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,14 @@
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { mergeConfig, defineConfig, configDefaults } from 'vitest/config'
|
||||
import viteConfig from './vite.config.ts'
|
||||
|
||||
export default mergeConfig(
|
||||
viteConfig,
|
||||
defineConfig({
|
||||
test: {
|
||||
environment: 'jsdom',
|
||||
exclude: [...configDefaults.exclude, 'e2e/**'],
|
||||
root: fileURLToPath(new URL('./', import.meta.url)),
|
||||
},
|
||||
}),
|
||||
)
|
||||
Reference in new issue
Block a user