Spaces:
Runtime error
Runtime error
chrisaka commited on
Commit ·
c605dd5
1
Parent(s): 8dcdb21
Refactor code structure for improved readability and maintainability
Browse files- .env.example +30 -10
- README.md +1125 -287
- app/__pycache__/main.cpython-313.pyc +0 -0
- app/core/__pycache__/auth.cpython-313.pyc +0 -0
- app/core/__pycache__/config.cpython-313.pyc +0 -0
- app/core/__pycache__/permissions.cpython-313.pyc +0 -0
- app/core/__pycache__/supabase.cpython-313.pyc +0 -0
- app/core/auth.py +98 -116
- app/core/config.py +37 -2
- app/core/permissions.py +87 -46
- app/core/supabase.py +9 -13
- app/main.py +63 -24
- app/models/__pycache__/schemas.cpython-313.pyc +0 -0
- app/models/schemas.py +246 -83
- app/routers/__pycache__/audiences.cpython-313.pyc +0 -0
- app/routers/__pycache__/audit.cpython-313.pyc +0 -0
- app/routers/__pycache__/auth.cpython-313.pyc +0 -0
- app/routers/__pycache__/clients.cpython-313.pyc +0 -0
- app/routers/__pycache__/dossiers.cpython-313.pyc +0 -0
- app/routers/__pycache__/espaces.cpython-313.pyc +0 -0
- app/routers/__pycache__/fichiers.cpython-313.pyc +0 -0
- app/routers/__pycache__/flash_cr.cpython-313.pyc +0 -0
- app/routers/__pycache__/paiements.cpython-313.pyc +0 -0
- app/routers/__pycache__/utilisateurs.cpython-313.pyc +0 -0
- app/routers/audiences.py +160 -13
- app/routers/audit.py +119 -0
- app/routers/auth.py +69 -7
- app/routers/clients.py +176 -29
- app/routers/dossiers.py +181 -36
- app/routers/espaces.py +109 -53
- app/routers/fichiers.py +111 -31
- app/routers/flash_cr.py +159 -8
- app/routers/paiements.py +116 -13
- app/routers/utilisateurs.py +42 -56
- app/sql/schema.sql +438 -0
- pyproject.toml +12 -10
- requirements.txt +32 -0
- uv.lock +0 -0
.env.example
CHANGED
|
@@ -1,12 +1,32 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
STORAGE_BUCKET=dedalys-fichiers
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
-
#
|
| 8 |
-
|
| 9 |
-
DB_NAME=postgres
|
| 10 |
-
DB_USER=postgres
|
| 11 |
-
DB_PASSWORD=your-db-password
|
| 12 |
-
DB_PORT=5432
|
|
|
|
| 1 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 2 |
+
# DEDALYS BACKEND — Variables d'environnement
|
| 3 |
+
# Copier ce fichier vers .env et remplir les valeurs
|
| 4 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 5 |
+
|
| 6 |
+
# ── Supabase ─────────────────────────────────────────────────────────────────
|
| 7 |
+
SUPABASE_URL=https://xxxxxxxxxxxx.supabase.co
|
| 8 |
+
SUPABASE_ANON_KEY=eyJ... # Dashboard → Settings → API → anon public
|
| 9 |
+
SUPABASE_SERVICE_KEY=eyJ... # Dashboard → Settings → API → service_role ⚠️ SECRET
|
| 10 |
+
SUPABASE_JWT_SECRET=your-jwt-secret # Dashboard → Settings → API → JWT Secret
|
| 11 |
+
|
| 12 |
+
# ── Storage ──────────────────────────────────────────────────────────────────
|
| 13 |
STORAGE_BUCKET=dedalys-fichiers
|
| 14 |
+
STORAGE_SIGNED_URL_EXPIRY=900 # Durée signed URLs en secondes (15 min)
|
| 15 |
+
|
| 16 |
+
# ── Email (Resend) ───────────────────────────────────────────────────────────
|
| 17 |
+
RESEND_API_KEY=re_... # https://resend.com/api-keys
|
| 18 |
+
EMAIL_FROM=noreply@dedalys.ci
|
| 19 |
+
|
| 20 |
+
# ── Application ──────────────────────────────────────────────────────────────
|
| 21 |
+
APP_ENV=development # development | staging | production
|
| 22 |
+
FRONTEND_URL=http://localhost:3000
|
| 23 |
+
|
| 24 |
+
# ── CORS ─────────────────────────────────────────────────────────────────────
|
| 25 |
+
# Liste des origines autorisées, séparées par des virgules
|
| 26 |
+
# development : http://localhost:3000
|
| 27 |
+
# staging : https://staging.dedalys.ci
|
| 28 |
+
# production : https://app.dedalys.ci
|
| 29 |
+
ALLOWED_ORIGINS=http://localhost:3000
|
| 30 |
|
| 31 |
+
# ── Reset Password ───────────────────────────────────────────────────────────
|
| 32 |
+
SUPABASE_RESET_PASSWORD_REDIRECT_URL=http://localhost:3000/reset-password
|
|
|
|
|
|
|
|
|
|
|
|
README.md
CHANGED
|
@@ -1,53 +1,140 @@
|
|
| 1 |
-
# Dedalys API
|
| 2 |
|
| 3 |
-
> API REST
|
|
|
|
| 4 |
|
| 5 |
---
|
| 6 |
|
| 7 |
## Table des matières
|
| 8 |
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
---
|
| 22 |
|
| 23 |
-
## Vue d'ensemble
|
| 24 |
|
| 25 |
-
Dedalys est
|
|
|
|
| 26 |
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
|
| 32 |
-
|
|
| 33 |
-
|
|
| 34 |
-
|
|
| 35 |
-
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
---
|
| 38 |
|
| 39 |
-
## Architecture technique
|
| 40 |
|
| 41 |
-
| Composant | Technologie
|
| 42 |
-
| ----------------- | ---------------------
|
| 43 |
-
| Framework API | FastAPI (Python)
|
| 44 |
-
| Base de données |
|
| 45 |
-
| Authentification | Supabase Auth
|
| 46 |
-
| Stockage fichiers | Supabase Storage
|
| 47 |
-
|
|
| 48 |
-
|
|
|
|
|
| 49 |
|
| 50 |
-
> **Note
|
|
|
|
| 51 |
|
| 52 |
### Schéma simplifié
|
| 53 |
|
|
@@ -66,42 +153,44 @@ Application Front-End
|
|
| 66 |
└──────────────┬──────────────┘
|
| 67 |
│
|
| 68 |
▼
|
| 69 |
-
┌─────────────────────────────────────┐
|
| 70 |
-
│
|
| 71 |
-
│ ┌──────────┐
|
| 72 |
-
│ │PostgreSQL│
|
| 73 |
-
│ │
|
| 74 |
-
│ └──────────┘
|
| 75 |
-
└─────────────────────────────────────┘
|
| 76 |
```
|
| 77 |
|
| 78 |
---
|
| 79 |
|
| 80 |
-
## Structure du projet
|
| 81 |
|
| 82 |
```
|
| 83 |
dedalys-api/
|
| 84 |
├── app/
|
| 85 |
│ ├── core/
|
| 86 |
-
│ │ ├── config.py
|
| 87 |
-
│ │ ├── supabase.py
|
| 88 |
-
│ │ ├── auth.py
|
| 89 |
-
│ │
|
|
|
|
| 90 |
│ ├── models/
|
| 91 |
-
│ │ └── schemas.py
|
| 92 |
│ ├── routers/
|
| 93 |
-
│ │ ├── auth.py
|
| 94 |
-
│ │ ├── espaces.py
|
| 95 |
-
│ │ ├── utilisateurs.py
|
| 96 |
-
│ │ ├── clients.py
|
| 97 |
-
│ │ ├── dossiers.py
|
| 98 |
-
│ │ ├── audiences.py
|
| 99 |
-
│ │ ├── flash_cr.py
|
| 100 |
-
│ │ ├── paiements.py
|
| 101 |
-
│ │
|
| 102 |
-
│ └──
|
|
|
|
| 103 |
├── sql/
|
| 104 |
-
│ └── schema.sql
|
| 105 |
├── .env.example
|
| 106 |
├── requirements.txt
|
| 107 |
└── README.md
|
|
@@ -109,7 +198,7 @@ dedalys-api/
|
|
| 109 |
|
| 110 |
---
|
| 111 |
|
| 112 |
-
## Installation et démarrage
|
| 113 |
|
| 114 |
### Prérequis
|
| 115 |
|
|
@@ -123,41 +212,34 @@ dedalys-api/
|
|
| 123 |
|
| 124 |
```bash
|
| 125 |
uv add fastapi "uvicorn[standard]" supabase python-dotenv "pydantic[email]" \
|
| 126 |
-
pydantic-settings python-multipart httpx
|
| 127 |
```
|
| 128 |
|
| 129 |
> `python-jose` n'est pas nécessaire — la validation JWT est entièrement gérée par le SDK Supabase.
|
| 130 |
|
| 131 |
-
**2. Configurer
|
| 132 |
|
| 133 |
```bash
|
| 134 |
cp .env.example .env
|
|
|
|
| 135 |
```
|
| 136 |
|
| 137 |
-
Remplir avec les valeurs de **Supabase Dashboard → Settings → API** :
|
| 138 |
-
|
| 139 |
-
```env
|
| 140 |
-
SUPABASE_URL=https://xxxxxxxxxxxx.supabase.co
|
| 141 |
-
SUPABASE_ANON_KEY=eyJ... # "anon public"
|
| 142 |
-
SUPABASE_SERVICE_KEY=eyJ... # "service_role" ⚠️ ne jamais exposer
|
| 143 |
-
STORAGE_BUCKET=dedalys-fichiers
|
| 144 |
-
```
|
| 145 |
-
|
| 146 |
-
> Plus besoin de `SUPABASE_JWT_SECRET` — la vérification des tokens se fait via `auth.get_user()`.
|
| 147 |
-
|
| 148 |
**3. Initialiser la base de données**
|
| 149 |
|
| 150 |
Dans **Supabase Dashboard → SQL Editor**, exécuter le contenu de `sql/schema.sql`.
|
| 151 |
|
| 152 |
-
> Ce script
|
| 153 |
|
| 154 |
**4. Créer le bucket Storage**
|
| 155 |
|
| 156 |
Dans **Supabase Dashboard → Storage → New Bucket** :
|
| 157 |
|
| 158 |
- Nom : `dedalys-fichiers`
|
|
|
|
|
|
|
|
|
|
| 159 |
|
| 160 |
-
|
| 161 |
|
| 162 |
**6. Lancer l'API**
|
| 163 |
|
|
@@ -165,78 +247,150 @@ Dans **Supabase Dashboard → Storage → New Bucket** :
|
|
| 165 |
uv run uvicorn app.main:app --reload
|
| 166 |
```
|
| 167 |
|
| 168 |
-
| URL
|
| 169 |
-
| ---------------------------------- | ---------------
|
| 170 |
-
| `http://localhost:8000/api/docs` | Swagger UI
|
| 171 |
-
| `http://localhost:8000/api/health` | Statut de l'API
|
| 172 |
|
| 173 |
---
|
| 174 |
|
| 175 |
-
##
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
```
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
```
|
| 201 |
|
| 202 |
-
> **Règle clé**
|
| 203 |
>
|
| 204 |
-
> - `associe_gerant` → admin
|
| 205 |
-
> - `
|
| 206 |
-
> - `avocat` → membre simple
|
| 207 |
-
> - `juriste` → membre simple
|
| 208 |
|
| 209 |
### Processus d'onboarding d'un nouveau cabinet
|
| 210 |
|
| 211 |
```
|
| 212 |
1. Superadmin crée l'espace
|
| 213 |
-
POST /api/espaces
|
| 214 |
-
{ "nom": "Cabinet
|
| 215 |
|
| 216 |
2. Superadmin crée les utilisateurs
|
| 217 |
-
POST /api/espaces/{espace_id}/utilisateurs
|
| 218 |
{ "email": "...", "password": "...", "role_cabinet": "associe_gerant" }
|
| 219 |
-
(associe_gerant ou office_manager → devient admin automatiquement)
|
| 220 |
|
| 221 |
3. Les utilisateurs se connectent
|
| 222 |
-
POST /api/auth/login
|
| 223 |
-
→
|
| 224 |
```
|
| 225 |
|
| 226 |
---
|
| 227 |
|
| 228 |
-
## Authentification
|
| 229 |
|
| 230 |
-
Pas d'auto-inscription. Les comptes sont **créés par les superadmins**.
|
| 231 |
|
| 232 |
### Se connecter
|
| 233 |
|
| 234 |
```http
|
| 235 |
-
POST /api/auth/login
|
| 236 |
Content-Type: application/json
|
| 237 |
|
| 238 |
{
|
| 239 |
-
"email": "avocat@cabinet.
|
| 240 |
"password": "motdepasse"
|
| 241 |
}
|
| 242 |
```
|
|
@@ -250,8 +404,8 @@ Content-Type: application/json
|
|
| 250 |
"token_type": "bearer",
|
| 251 |
"user": {
|
| 252 |
"id": "uuid",
|
| 253 |
-
"email": "avocat@cabinet.
|
| 254 |
-
"nom": "
|
| 255 |
"prenom": "Jean",
|
| 256 |
"role_cabinet": "avocat",
|
| 257 |
"espace_id": "uuid-de-lespace",
|
|
@@ -268,167 +422,562 @@ Authorization: Bearer eyJ...
|
|
| 268 |
|
| 269 |
L'espace est automatiquement déduit du profil — **aucun header `X-Espace-ID` n'est requis**.
|
| 270 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 271 |
### Durée de vie des tokens
|
| 272 |
|
| 273 |
-
| Token | Durée | À l'expiration
|
| 274 |
-
| --------------- | ------- | -------------------------------- |
|
| 275 |
-
| `access_token` | 1 heure | Appeler `POST /api/auth/refresh` |
|
| 276 |
-
| `refresh_token` | 7 jours | Redemander un login
|
| 277 |
|
| 278 |
### Renouveler le token
|
| 279 |
|
| 280 |
```http
|
| 281 |
-
POST /api/auth/refresh
|
| 282 |
Content-Type: application/json
|
| 283 |
|
| 284 |
{ "refresh_token": "eyJ..." }
|
| 285 |
```
|
| 286 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 287 |
---
|
| 288 |
|
| 289 |
-
## Système de rôles et permissions
|
| 290 |
|
| 291 |
### Qui est admin de l'espace ?
|
| 292 |
|
| 293 |
-
| `role_cabinet` | Statut
|
| 294 |
-
| ---------------- | ---------
|
| 295 |
-
| `associe_gerant` | 🟠 Admin
|
| 296 |
-
| `office_manager` | 🟠 Admin
|
| 297 |
-
| `avocat` | 🟢 Membre
|
| 298 |
-
| `juriste` | 🟢 Membre
|
| 299 |
|
| 300 |
-
### Permissions métier par
|
| 301 |
|
| 302 |
| Rôle | Clients | Dossiers | Audiences | Flash CR | Paiements | Fichiers |
|
| 303 |
| ---------------- | :-----: | :------: | :-------: | :------: | :-------: | :------: |
|
| 304 |
-
| `associe_gerant` | R/W/
|
| 305 |
-
| `office_manager` | R/W/
|
| 306 |
| `avocat` | R/W | R/W | R/W | R/W | R | R/W |
|
| 307 |
| `juriste` | R/W | R/W | R/W | R/W | R | R/W |
|
| 308 |
|
| 309 |
-
_R = Lecture
|
|
|
|
|
|
|
|
|
|
|
|
|
| 310 |
|
| 311 |
-
**Note
|
| 312 |
|
| 313 |
-
|
| 314 |
-
-
|
|
|
|
|
|
|
| 315 |
|
| 316 |
---
|
| 317 |
|
| 318 |
-
## Référence des endpoints
|
| 319 |
|
| 320 |
-
> Toutes les routes (sauf `/api/auth/*`) nécessitent `Authorization: Bearer <token>`
|
| 321 |
|
| 322 |
### Authentification
|
| 323 |
|
| 324 |
-
| Méthode | Endpoint
|
| 325 |
-
| ------- | ------------------- | ------------------- |
|
| 326 |
-
| `POST` | `/api/auth/login`
|
| 327 |
-
| `POST` | `/api/auth/refresh`
|
| 328 |
-
| `POST` | `/api/auth/logout`
|
|
|
|
|
|
|
| 329 |
|
| 330 |
### Espaces — 🔴 Superadmin uniquement
|
| 331 |
|
| 332 |
-
| Méthode | Endpoint
|
| 333 |
-
| -------- | -------------------------------------- | ---------------------------------- |
|
| 334 |
-
| `POST` | `/api/espaces` | Créer un espace (cabinet) |
|
| 335 |
-
| `GET` | `/api/espaces` | Lister tous les espaces |
|
| 336 |
-
| `GET` | `/api/espaces/{id}` | Détail + membres |
|
| 337 |
-
| `PATCH` | `/api/espaces/{id}` | Renommer l'espace |
|
| 338 |
-
| `DELETE` | `/api/espaces/{id}` |
|
| 339 |
-
| `POST` | `/api/espaces/{id}/utilisateurs` | Créer un utilisateur dans l'espace |
|
| 340 |
-
| `DELETE` | `/api/espaces/{id}/utilisateurs/{uid}` | Supprimer un utilisateur |
|
| 341 |
|
| 342 |
### Utilisateurs
|
| 343 |
|
| 344 |
-
| Méthode | Endpoint
|
| 345 |
-
| ------- | ------------------------------------- | ----------------------- | --------------- |
|
| 346 |
-
| `GET` | `/api/utilisateurs/me` | Mon profil | Tous |
|
| 347 |
-
| `PATCH` | `/api/utilisateurs/me` | Modifier mon nom/prénom | Tous |
|
| 348 |
-
| `GET` | `/api/utilisateurs` | Membres de mon espace | Tous |
|
| 349 |
-
| `GET` | `/api/utilisateurs/{id}` | Profil d'un membre | Tous |
|
| 350 |
-
| `PATCH` | `/api/utilisateurs/{id}/role-cabinet` | Changer le rôle métier | 🟠 Admin espace |
|
| 351 |
|
| 352 |
### Clients
|
| 353 |
|
| 354 |
-
| Méthode
|
| 355 |
-
| -------- | ---------------------------------- | ---------------------------------------------- |
|
| 356 |
-
|
|
| 357 |
-
| `
|
| 358 |
-
| `GET`
|
| 359 |
-
| `
|
| 360 |
-
| `
|
| 361 |
-
| `
|
| 362 |
-
| `
|
| 363 |
-
| `
|
| 364 |
-
| `
|
| 365 |
-
| `
|
| 366 |
-
| `DELETE` | `/api/clients/{id}/contacts/{cid}` | Supprimer un contact |
|
| 367 |
|
| 368 |
### Dossiers
|
| 369 |
|
| 370 |
-
| Méthode
|
| 371 |
-
| -------- | ---------------------------------- | ----------------------------- |
|
| 372 |
-
|
|
| 373 |
-
| `
|
| 374 |
-
| `GET`
|
| 375 |
-
| `
|
| 376 |
-
| `
|
| 377 |
-
| `
|
| 378 |
-
| `
|
| 379 |
-
| `
|
| 380 |
-
| `
|
| 381 |
-
| `
|
| 382 |
-
| `DELETE` | `/api/dossiers/{id}/equipe/{uid}` | Retirer un membre | ASSOCIE_GERANT + OFFICE_MANAGER
|
| 383 |
|
| 384 |
### Audiences
|
| 385 |
|
| 386 |
-
| Méthode | Endpoint
|
| 387 |
-
| -------- | ----------------------------- | -------------------------------- |
|
| 388 |
-
| `POST` | `/api/audiences` | Créer une audience
|
| 389 |
-
| `GET` | `/api/audiences` | Toutes les audiences de l'espace |
|
| 390 |
-
| `GET` | `/api/audiences/dossier/{id}` | Audiences d'un dossier
|
| 391 |
-
| `GET` | `/api/audiences/avocat/{id}` | Agenda d'un avocat
|
| 392 |
-
| `GET` | `/api/audiences/{id}` | Détail
|
| 393 |
-
| `PATCH` | `/api/audiences/{id}` | Modifier
|
| 394 |
-
| `DELETE` | `/api/audiences/{id}` |
|
| 395 |
|
| 396 |
### Flash CR
|
| 397 |
|
| 398 |
-
| Méthode | Endpoint
|
| 399 |
-
| -------- | ----------------------------- | --------------------------- |
|
| 400 |
-
| `POST` | `/api/flash-cr` | Créer (1 seul par audience) |
|
| 401 |
-
| `GET` | `/api/flash-cr/audience/{id}` | Flash CR d'une audience
|
| 402 |
-
| `GET` | `/api/flash-cr/{id}` | Détail
|
| 403 |
-
| `PATCH` | `/api/flash-cr/{id}` | Modifier
|
| 404 |
-
| `DELETE` | `/api/flash-cr/{id}` |
|
| 405 |
|
| 406 |
### Paiements
|
| 407 |
|
| 408 |
-
| Méthode | Endpoint
|
| 409 |
-
| -------- | ----------------------------- | ------------------------------ |
|
| 410 |
-
| `POST` | `/api/paiements` | Enregistrer un paiement
|
| 411 |
-
| `GET` | `/api/paiements` | Tous les paiements de l'espace |
|
| 412 |
-
| `GET` | `/api/paiements/dossier/{id}` | Par dossier
|
| 413 |
-
| `GET` | `/api/paiements/client/{id}` | Par client
|
| 414 |
-
| `GET` | `/api/paiements/{id}` | Détail
|
| 415 |
-
| `PATCH` | `/api/paiements/{id}` | Modifier
|
| 416 |
-
| `DELETE` | `/api/paiements/{id}` |
|
| 417 |
|
| 418 |
### Fichiers
|
| 419 |
|
| 420 |
-
| Méthode | Endpoint
|
| 421 |
-
| -------- | ---------------------------- | -------------------------------- |
|
| 422 |
-
| `POST` | `/api/fichiers/dossier/{id}` | Uploader (`multipart/form-data`) |
|
| 423 |
-
| `GET` | `/api/fichiers/dossier/{id}` | Lister les fichiers d'un dossier
|
| 424 |
-
| `GET` | `/api/fichiers/{id}` | Détail + URL
|
| 425 |
-
| `DELETE` | `/api/fichiers/{id}` |
|
| 426 |
|
| 427 |
**Contraintes fichiers :** max 10 MB · 50 fichiers/dossier · Formats : PDF, DOC, DOCX, JPEG, PNG
|
| 428 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 429 |
---
|
| 430 |
|
| 431 |
-
##
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 432 |
|
| 433 |
### Client HTTP (Axios)
|
| 434 |
|
|
@@ -436,9 +985,13 @@ _R = Lecture, W = Écriture/Création, D = Suppression_
|
|
| 436 |
// lib/api.ts
|
| 437 |
import axios from "axios";
|
| 438 |
|
| 439 |
-
const api = axios.create({
|
|
|
|
|
|
|
| 440 |
|
| 441 |
// Injecter le token automatiquement
|
|
|
|
|
|
|
| 442 |
api.interceptors.request.use((config) => {
|
| 443 |
const token = localStorage.getItem("access_token");
|
| 444 |
if (token) config.headers["Authorization"] = `Bearer ${token}`;
|
|
@@ -452,15 +1005,15 @@ api.interceptors.response.use(
|
|
| 452 |
if (error.response?.status === 401) {
|
| 453 |
try {
|
| 454 |
const refresh = localStorage.getItem("refresh_token");
|
| 455 |
-
const { data } = await axios.post(
|
| 456 |
-
|
| 457 |
-
|
|
|
|
| 458 |
localStorage.setItem("access_token", data.access_token);
|
| 459 |
localStorage.setItem("refresh_token", data.refresh_token);
|
| 460 |
error.config.headers["Authorization"] = `Bearer ${data.access_token}`;
|
| 461 |
return axios(error.config);
|
| 462 |
} catch {
|
| 463 |
-
// Refresh expiré → rediriger vers login
|
| 464 |
localStorage.clear();
|
| 465 |
window.location.href = "/login";
|
| 466 |
}
|
|
@@ -475,20 +1028,15 @@ export default api;
|
|
| 475 |
### Flux de connexion
|
| 476 |
|
| 477 |
```typescript
|
| 478 |
-
//
|
| 479 |
const { data } = await api.post("/auth/login", { email, password });
|
| 480 |
-
|
| 481 |
localStorage.setItem("access_token", data.access_token);
|
| 482 |
localStorage.setItem("refresh_token", data.refresh_token);
|
| 483 |
|
| 484 |
-
|
| 485 |
-
// user.espace_id
|
| 486 |
-
// user.role_cabinet
|
| 487 |
-
// user.is_superadmin
|
| 488 |
-
// Pas besoin de stocker l'espace_id séparément — l'API le déduit du token
|
| 489 |
-
|
| 490 |
-
// 2. Appels suivants — rien de spécial
|
| 491 |
-
const { data: clients } = await api.get("/clients");
|
| 492 |
```
|
| 493 |
|
| 494 |
### Détecter le statut admin côté front
|
|
@@ -496,8 +1044,8 @@ const { data: clients } = await api.get("/clients");
|
|
| 496 |
```typescript
|
| 497 |
const ADMIN_ROLES = ["associe_gerant", "office_manager"];
|
| 498 |
|
| 499 |
-
const isEspaceAdmin = (user) => ADMIN_ROLES.includes(user.role_cabinet);
|
| 500 |
-
const isSuperAdmin = (user) => user.is_superadmin === true;
|
| 501 |
```
|
| 502 |
|
| 503 |
### Upload de fichier
|
|
@@ -511,22 +1059,24 @@ const uploadFichier = async (dossierId: string, file: File) => {
|
|
| 511 |
headers: { "Content-Type": "multipart/form-data" },
|
| 512 |
});
|
| 513 |
|
| 514 |
-
// data.
|
|
|
|
| 515 |
return data;
|
| 516 |
};
|
| 517 |
```
|
| 518 |
|
| 519 |
### Codes d'erreur
|
| 520 |
|
| 521 |
-
| Code | Signification | Action
|
| 522 |
-
| ----- | ------------------------------------ | ----------------------------------------- |
|
| 523 |
-
| `401` | Token invalide ou expiré | L'intercepteur rafraîchit automatiquement
|
| 524 |
-
| `403` | Permission refusée | Afficher "accès refusé"
|
| 525 |
-
| `404` | Ressource introuvable | Afficher message d'erreur
|
| 526 |
-
| `409` | Conflit (ex: Flash CR déjà existant) | Afficher `error.response.data.detail`
|
| 527 |
-
| `422` | Données invalides | Afficher les erreurs de champs
|
|
|
|
| 528 |
|
| 529 |
-
Format des erreurs :
|
| 530 |
|
| 531 |
```json
|
| 532 |
{ "detail": "Message d'erreur lisible" }
|
|
@@ -534,52 +1084,16 @@ Format des erreurs :
|
|
| 534 |
|
| 535 |
---
|
| 536 |
|
| 537 |
-
##
|
| 538 |
-
|
| 539 |
-
```
|
| 540 |
-
Espace (1 par cabinet)
|
| 541 |
-
│
|
| 542 |
-
├──< Utilisateurs
|
| 543 |
-
│ role_cabinet → associe_gerant / office_manager = admin
|
| 544 |
-
│ → avocat / juriste = membre
|
| 545 |
-
│
|
| 546 |
-
├──< Clients
|
| 547 |
-
│ ├──< PointDeContact
|
| 548 |
-
│ └──< Paiements
|
| 549 |
-
│
|
| 550 |
-
└──< Dossiers
|
| 551 |
-
├──< EquipeDossier >── Utilisateur
|
| 552 |
-
├──< Audiences
|
| 553 |
-
│ └── FlashCR (1 par audience max)
|
| 554 |
-
├──< Paiements
|
| 555 |
-
└──< Fichiers
|
| 556 |
-
```
|
| 557 |
-
|
| 558 |
-
### Valeurs acceptées
|
| 559 |
-
|
| 560 |
-
| Champ | Valeurs |
|
| 561 |
-
| ------------------------ | ------------------------------------------------------------- |
|
| 562 |
-
| `statut` Client | `PP`, `PM` |
|
| 563 |
-
| `type` Dossier | `pre_contentieux`, `contentieux`, `conseil`, `transactionnel` |
|
| 564 |
-
| `statut` Dossier | `ouvert`, `en_instance`, `cloture` |
|
| 565 |
-
| `preference_facturation` | `forfait`, `capped_fees` |
|
| 566 |
-
| `type` Paiement | `honoraires`, `frais` |
|
| 567 |
-
| `type_decision` Flash CR | `decision_rendue`, `renvoi`, `autre` |
|
| 568 |
-
| `role_cabinet` | `associe_gerant`, `avocat`, `juriste`, `office_manager` |
|
| 569 |
-
| `role` EquipeDossier | `responsable`, `collaborateur` |
|
| 570 |
-
|
| 571 |
-
---
|
| 572 |
-
|
| 573 |
-
## Créer le premier superadmin
|
| 574 |
|
| 575 |
-
Les superadmins ne peuvent pas s'auto-créer via l'API.
|
| 576 |
|
| 577 |
**Étape 1 — Créer le compte dans Supabase Auth**
|
| 578 |
|
| 579 |
Dans **Supabase Dashboard → Authentication → Users → Add user** :
|
| 580 |
|
| 581 |
- Email : `superadmin@dedalys.com`
|
| 582 |
-
- Password : mot de passe fort
|
| 583 |
- ✅ Cocher "Auto Confirm User"
|
| 584 |
|
| 585 |
**Étape 2 — Créer le profil en base**
|
|
@@ -595,19 +1109,343 @@ VALUES (
|
|
| 595 |
'Dedalys',
|
| 596 |
'associe_gerant',
|
| 597 |
NULL, -- pas d'espace pour les superadmins
|
| 598 |
-
TRUE
|
| 599 |
);
|
| 600 |
```
|
| 601 |
|
| 602 |
-
**Étape 3 —
|
| 603 |
|
| 604 |
```http
|
| 605 |
-
POST /api/auth/login
|
| 606 |
{ "email": "superadmin@dedalys.com", "password": "..." }
|
| 607 |
```
|
| 608 |
|
| 609 |
-
La réponse
|
| 610 |
|
| 611 |
### Créer des superadmins supplémentaires
|
| 612 |
|
| 613 |
Répéter les étapes 1 et 2 pour chaque superadmin à ajouter.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Dedalys Backend API
|
| 2 |
|
| 3 |
+
> API REST de gestion pour cabinets juridiques — Dedalys MVP v1.0
|
| 4 |
+
> Phase actuelle : **Beta privée** (5 cabinets partenaires)
|
| 5 |
|
| 6 |
---
|
| 7 |
|
| 8 |
## Table des matières
|
| 9 |
|
| 10 |
+
- [Dedalys Backend API](#dedalys-backend-api)
|
| 11 |
+
- [Table des matières](#table-des-matières)
|
| 12 |
+
- [1. Vue d'ensemble](#1-vue-densemble)
|
| 13 |
+
- [2. Architecture technique](#2-architecture-technique)
|
| 14 |
+
- [Schéma simplifié](#schéma-simplifié)
|
| 15 |
+
- [3. Structure du projet](#3-structure-du-projet)
|
| 16 |
+
- [4. Installation et démarrage](#4-installation-et-démarrage)
|
| 17 |
+
- [Prérequis](#prérequis)
|
| 18 |
+
- [Étapes](#étapes)
|
| 19 |
+
- [5. Variables d'environnement](#5-variables-denvironnement)
|
| 20 |
+
- [6. Environnements](#6-environnements)
|
| 21 |
+
- [7. CORS](#7-cors)
|
| 22 |
+
- [8. Les trois niveaux d'accès](#8-les-trois-niveaux-daccès)
|
| 23 |
+
- [Processus d'onboarding d'un nouveau cabinet](#processus-donboarding-dun-nouveau-cabinet)
|
| 24 |
+
- [9. Authentification](#9-authentification)
|
| 25 |
+
- [Se connecter](#se-connecter)
|
| 26 |
+
- [Utiliser le token](#utiliser-le-token)
|
| 27 |
+
- [Durée de vie des tokens](#durée-de-vie-des-tokens)
|
| 28 |
+
- [Renouveler le token](#renouveler-le-token)
|
| 29 |
+
- [Mot de passe oublié](#mot-de-passe-oublié)
|
| 30 |
+
- [Déconnexion](#déconnexion)
|
| 31 |
+
- [10. Système de rôles et permissions](#10-système-de-rôles-et-permissions)
|
| 32 |
+
- [Qui est admin de l'espace ?](#qui-est-admin-de-lespace-)
|
| 33 |
+
- [Permissions métier par rôle](#permissions-métier-par-rôle)
|
| 34 |
+
- [11. Référence des endpoints](#11-référence-des-endpoints)
|
| 35 |
+
- [Authentification](#authentification)
|
| 36 |
+
- [Espaces — 🔴 Superadmin uniquement](#espaces---superadmin-uniquement)
|
| 37 |
+
- [Utilisateurs](#utilisateurs)
|
| 38 |
+
- [Clients](#clients)
|
| 39 |
+
- [Dossiers](#dossiers)
|
| 40 |
+
- [Audiences](#audiences)
|
| 41 |
+
- [Flash CR](#flash-cr)
|
| 42 |
+
- [Paiements](#paiements)
|
| 43 |
+
- [Fichiers](#fichiers)
|
| 44 |
+
- [Audit Trail — `associe_gerant` uniquement](#audit-trail--associe_gerant-uniquement)
|
| 45 |
+
- [12. Pagination, filtres et recherche](#12-pagination-filtres-et-recherche)
|
| 46 |
+
- [Pagination](#pagination)
|
| 47 |
+
- [Filtres par endpoint](#filtres-par-endpoint)
|
| 48 |
+
- [13. Rappels automatiques d'audience](#13-rappels-automatiques-daudience)
|
| 49 |
+
- [14. Flash CR — Email automatique client](#14-flash-cr--email-automatique-client)
|
| 50 |
+
- [Règles métier](#règles-métier)
|
| 51 |
+
- [Valeurs acceptées pour `type_decision`](#valeurs-acceptées-pour-type_decision)
|
| 52 |
+
- [Email automatique](#email-automatique)
|
| 53 |
+
- [15. Gestion des fichiers](#15-gestion-des-fichiers)
|
| 54 |
+
- [Upload](#upload)
|
| 55 |
+
- [Accès sécurisé — Signed URLs](#accès-sécurisé--signed-urls)
|
| 56 |
+
- [16. Soft delete — conservation des données](#16-soft-delete--conservation-des-données)
|
| 57 |
+
- [Récupérer une donnée archivée par erreur (superadmin uniquement)](#récupérer-une-donnée-archivée-par-erreur-superadmin-uniquement)
|
| 58 |
+
- [17. Audit trail](#17-audit-trail)
|
| 59 |
+
- [18. Architecture multi-tenant](#18-architecture-multi-tenant)
|
| 60 |
+
- [Isolation des données — deux niveaux obligatoires](#isolation-des-données--deux-niveaux-obligatoires)
|
| 61 |
+
- [Limites par espace (MVP)](#limites-par-espace-mvp)
|
| 62 |
+
- [19. Modèle de données](#19-modèle-de-données)
|
| 63 |
+
- [Valeurs acceptées](#valeurs-acceptées)
|
| 64 |
+
- [20. Guide pour le développeur front-end](#20-guide-pour-le-développeur-front-end)
|
| 65 |
+
- [Client HTTP (Axios)](#client-http-axios)
|
| 66 |
+
- [Flux de connexion](#flux-de-connexion)
|
| 67 |
+
- [Détecter le statut admin côté front](#détecter-le-statut-admin-côté-front)
|
| 68 |
+
- [Upload de fichier](#upload-de-fichier)
|
| 69 |
+
- [Codes d'erreur](#codes-derreur)
|
| 70 |
+
- [21. Créer le premier superadmin](#21-créer-le-premier-superadmin)
|
| 71 |
+
- [Créer des superadmins supplémentaires](#créer-des-superadmins-supplémentaires)
|
| 72 |
+
- [🏛️ Dedalys Backend API](#️-dedalys-backend-api)
|
| 73 |
+
- [📋 Table des Matières](#-table-des-matières)
|
| 74 |
+
- [🚀 Démarrage Rapide](#-démarrage-rapide)
|
| 75 |
+
- [Prérequis](#prérequis-1)
|
| 76 |
+
- [Installation](#installation)
|
| 77 |
+
- [Lancement](#lancement)
|
| 78 |
+
- [Documentation API](#documentation-api)
|
| 79 |
+
- [🏗️ Architecture](#️-architecture)
|
| 80 |
+
- [📡 Endpoints API](#-endpoints-api)
|
| 81 |
+
- [Authentification](#authentification-1)
|
| 82 |
+
- [Clients](#clients-1)
|
| 83 |
+
- [Dossiers](#dossiers-1)
|
| 84 |
+
- [Audiences](#audiences-1)
|
| 85 |
+
- [Flash CR](#flash-cr-1)
|
| 86 |
+
- [Paiements](#paiements-1)
|
| 87 |
+
- [Fichiers](#fichiers-1)
|
| 88 |
+
- [🗄️ Modèle de Données](#️-modèle-de-données)
|
| 89 |
+
- [Entités principales](#entités-principales)
|
| 90 |
+
- [Soft Delete](#soft-delete)
|
| 91 |
+
- [🔐 Sécurité](#-sécurité)
|
| 92 |
+
- [Authentification](#authentification-2)
|
| 93 |
+
- [Rôles Cabinet](#rôles-cabinet)
|
| 94 |
+
- [Multi-tenant](#multi-tenant)
|
| 95 |
+
- [CORS](#cors)
|
| 96 |
+
- [🚢 Déploiement](#-déploiement)
|
| 97 |
+
- [Variables d'environnement requises](#variables-denvironnement-requises)
|
| 98 |
+
- [Cloud Run (recommandé)](#cloud-run-recommandé)
|
| 99 |
+
- [Base de données](#base-de-données)
|
| 100 |
+
- [📊 Conformité Audit v2](#-conformité-audit-v2)
|
| 101 |
+
- [📞 Support](#-support)
|
| 102 |
|
| 103 |
---
|
| 104 |
|
| 105 |
+
## 1. Vue d'ensemble
|
| 106 |
|
| 107 |
+
Dedalys est un SaaS B2B multi-tenant de gestion de cabinets d'avocats, conçu spécifiquement
|
| 108 |
+
pour le marché juridique en Afrique francophone (Côte d'Ivoire en priorité, expansion UEMOA prévue).
|
| 109 |
|
| 110 |
+
Ce dépôt contient l'API backend. Le frontend (Next.js 14+) est dans un dépôt séparé.
|
| 111 |
+
|
| 112 |
+
**Périmètre MVP — 5 modules :**
|
| 113 |
+
|
| 114 |
+
| Module | Description |
|
| 115 |
+
| -------------- | ---------------------------------------------------- |
|
| 116 |
+
| 👤 Clients | Personnes physiques ou morales, vue 360° |
|
| 117 |
+
| 📁 Dossiers | Dossiers juridiques et équipes assignées |
|
| 118 |
+
| ⚖️ Audiences | Calendrier d'audience avec rappels automatiques |
|
| 119 |
+
| 📋 Flash CR | Comptes-rendus d'audience + email automatique client |
|
| 120 |
+
| 💰 Facturation | Suivi des honoraires et frais |
|
| 121 |
|
| 122 |
---
|
| 123 |
|
| 124 |
+
## 2. Architecture technique
|
| 125 |
|
| 126 |
+
| Composant | Technologie | Justification MVP |
|
| 127 |
+
| ----------------- | -------------------------- | --------------------------------------- |
|
| 128 |
+
| Framework API | FastAPI (Python 3.11+) | Performances async, OpenAPI auto |
|
| 129 |
+
| Base de données | PostgreSQL 15 via Supabase | ACID, RLS natif, backups inclus |
|
| 130 |
+
| Authentification | Supabase Auth | Battle-tested, 0 code auth à écrire |
|
| 131 |
+
| Stockage fichiers | Supabase Storage | Signed URLs, intégration native |
|
| 132 |
+
| Tâches planifiées | APScheduler (in-process) | 0 infrastructure Redis/Celery pour MVP |
|
| 133 |
+
| Emails | Resend | API simple, bonne délivrabilité Afrique |
|
| 134 |
+
| Hébergement | Cloud Run (GCP) | Scalabilité auto, région Africa |
|
| 135 |
|
| 136 |
+
> **Note :** APScheduler est choisi pour sa simplicité (pas de Redis ni de worker séparé).
|
| 137 |
+
> Migration vers Cloud Tasks ou Celery envisageable post-PMF si le volume le justifie.
|
| 138 |
|
| 139 |
### Schéma simplifié
|
| 140 |
|
|
|
|
| 153 |
└──────────────┬──────────────┘
|
| 154 |
│
|
| 155 |
▼
|
| 156 |
+
┌──────────────────────────────────────┐
|
| 157 |
+
│ Supabase │
|
| 158 |
+
│ ┌──────────┐ ┌──────┐ ┌────────┐ │
|
| 159 |
+
│ │PostgreSQL│ │ Auth │ │Storage │ │
|
| 160 |
+
│ │ + RLS │ │(JWT) │ │(docs) │ │
|
| 161 |
+
│ └──────────┘ └──────┘ └────────┘ │
|
| 162 |
+
└──────────────────────────────────────┘
|
| 163 |
```
|
| 164 |
|
| 165 |
---
|
| 166 |
|
| 167 |
+
## 3. Structure du projet
|
| 168 |
|
| 169 |
```
|
| 170 |
dedalys-api/
|
| 171 |
├── app/
|
| 172 |
│ ├── core/
|
| 173 |
+
│ │ ├── config.py # Variables d'environnement
|
| 174 |
+
│ │ ├── supabase.py # Clients Supabase (public + admin)
|
| 175 |
+
│ │ ├── auth.py # Vérification token, dépendances
|
| 176 |
+
│ │ ├── permissions.py # Matrice des rôles
|
| 177 |
+
│ │ └── scheduler.py # APScheduler — rappels audiences
|
| 178 |
│ ├── models/
|
| 179 |
+
│ │ └── schemas.py # Tous les modèles Pydantic
|
| 180 |
│ ├── routers/
|
| 181 |
+
│ │ ├── auth.py # /api/v1/auth/*
|
| 182 |
+
│ │ ├── espaces.py # /api/v1/espaces/*
|
| 183 |
+
│ │ ├── utilisateurs.py # /api/v1/utilisateurs/*
|
| 184 |
+
│ │ ├── clients.py # /api/v1/clients/*
|
| 185 |
+
│ │ ├── dossiers.py # /api/v1/dossiers/*
|
| 186 |
+
│ │ ├── audiences.py # /api/v1/audiences/*
|
| 187 |
+
│ │ ├── flash_cr.py # /api/v1/flash-cr/*
|
| 188 |
+
│ │ ├── paiements.py # /api/v1/paiements/*
|
| 189 |
+
│ │ ├── fichiers.py # /api/v1/fichiers/*
|
| 190 |
+
│ │ └── audit.py # /api/v1/audit/*
|
| 191 |
+
│ └── main.py # Point d'entrée
|
| 192 |
├── sql/
|
| 193 |
+
│ └── schema.sql # Script SQL (tables + RLS policies)
|
| 194 |
├── .env.example
|
| 195 |
├── requirements.txt
|
| 196 |
└── README.md
|
|
|
|
| 198 |
|
| 199 |
---
|
| 200 |
|
| 201 |
+
## 4. Installation et démarrage
|
| 202 |
|
| 203 |
### Prérequis
|
| 204 |
|
|
|
|
| 212 |
|
| 213 |
```bash
|
| 214 |
uv add fastapi "uvicorn[standard]" supabase python-dotenv "pydantic[email]" \
|
| 215 |
+
pydantic-settings python-multipart httpx apscheduler resend
|
| 216 |
```
|
| 217 |
|
| 218 |
> `python-jose` n'est pas nécessaire — la validation JWT est entièrement gérée par le SDK Supabase.
|
| 219 |
|
| 220 |
+
**2. Configurer les variables d'environnement**
|
| 221 |
|
| 222 |
```bash
|
| 223 |
cp .env.example .env
|
| 224 |
+
# Remplir avec les valeurs Supabase + Resend (voir section 5)
|
| 225 |
```
|
| 226 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 227 |
**3. Initialiser la base de données**
|
| 228 |
|
| 229 |
Dans **Supabase Dashboard → SQL Editor**, exécuter le contenu de `sql/schema.sql`.
|
| 230 |
|
| 231 |
+
> Ce script crée les tables, les policies RLS et les index.
|
| 232 |
|
| 233 |
**4. Créer le bucket Storage**
|
| 234 |
|
| 235 |
Dans **Supabase Dashboard → Storage → New Bucket** :
|
| 236 |
|
| 237 |
- Nom : `dedalys-fichiers`
|
| 238 |
+
- Accès : privé (les URLs sont des signed URLs générées à la demande)
|
| 239 |
+
|
| 240 |
+
**5. Créer le premier superadmin**
|
| 241 |
|
| 242 |
+
Voir [section 21](#21-créer-le-premier-superadmin).
|
| 243 |
|
| 244 |
**6. Lancer l'API**
|
| 245 |
|
|
|
|
| 247 |
uv run uvicorn app.main:app --reload
|
| 248 |
```
|
| 249 |
|
| 250 |
+
| URL | Description |
|
| 251 |
+
| ------------------------------------- | --------------- |
|
| 252 |
+
| `http://localhost:8000/api/v1/docs` | Swagger UI |
|
| 253 |
+
| `http://localhost:8000/api/v1/health` | Statut de l'API |
|
| 254 |
|
| 255 |
---
|
| 256 |
|
| 257 |
+
## 5. Variables d'environnement
|
| 258 |
+
|
| 259 |
+
```env
|
| 260 |
+
# ── Supabase ─────────────────────────────────────────────
|
| 261 |
+
SUPABASE_URL=https://xxxxxxxxxxxx.supabase.co
|
| 262 |
+
SUPABASE_ANON_KEY=eyJ... # "anon public" — Dashboard → Settings → API
|
| 263 |
+
SUPABASE_SERVICE_KEY=eyJ... # "service_role" ⚠️ ne jamais exposer côté client
|
| 264 |
|
| 265 |
+
# ── Storage ──────────────────────────────────────────────
|
| 266 |
+
STORAGE_BUCKET=dedalys-fichiers
|
| 267 |
+
STORAGE_SIGNED_URL_EXPIRY=900 # Durée des signed URLs en secondes (15 min)
|
| 268 |
+
|
| 269 |
+
# ── Email (Resend) ────────────────────────────────────────
|
| 270 |
+
RESEND_API_KEY=re_...
|
| 271 |
+
EMAIL_FROM=noreply@dedalys.ci
|
| 272 |
+
|
| 273 |
+
# ── Application ──────────────────────────────────────────
|
| 274 |
+
APP_ENV=development # development | staging | production
|
| 275 |
+
FRONTEND_URL=http://localhost:3000
|
| 276 |
+
|
| 277 |
+
# ── CORS ─────────────────────────────────────────────────
|
| 278 |
+
ALLOWED_ORIGINS=http://localhost:3000
|
| 279 |
+
# En production : https://app.dedalys.ci
|
| 280 |
+
# En staging : https://staging.dedalys.ci
|
| 281 |
+
|
| 282 |
+
# ── Reset password ───────────────────────────────────────
|
| 283 |
+
SUPABASE_RESET_PASSWORD_REDIRECT_URL=http://localhost:3000/reset-password
|
| 284 |
```
|
| 285 |
+
|
| 286 |
+
> **Règle absolue :** `SUPABASE_SERVICE_KEY` ne doit jamais apparaître dans le code,
|
| 287 |
+
> les logs, ou être exposé à l'extérieur. C'est la clé admin complète de la base.
|
| 288 |
+
|
| 289 |
+
---
|
| 290 |
+
|
| 291 |
+
## 6. Environnements
|
| 292 |
+
|
| 293 |
+
Trois environnements distincts, chacun avec sa propre instance Supabase et son propre `.env` :
|
| 294 |
+
|
| 295 |
+
| Environnement | Backend URL | Frontend URL | Base de données |
|
| 296 |
+
| ------------- | ------------------------ | -------------------- | ---------------------------------------- |
|
| 297 |
+
| `development` | `localhost:8000` | `localhost:3000` | Supabase dev (données fictives) |
|
| 298 |
+
| `staging` | `staging-api.dedalys.ci` | `staging.dedalys.ci` | Supabase staging (données anonymisées) |
|
| 299 |
+
| `production` | `api.dedalys.ci` | `app.dedalys.ci` | Supabase prod (données réelles cabinets) |
|
| 300 |
+
|
| 301 |
+
**Règle de déploiement :** tout code passe obligatoirement par `staging` avant d'atteindre
|
| 302 |
+
`production`. Aucun déploiement direct en production.
|
| 303 |
+
|
| 304 |
+
---
|
| 305 |
+
|
| 306 |
+
## 7. CORS
|
| 307 |
+
|
| 308 |
+
Les origines autorisées sont configurées via la variable `ALLOWED_ORIGINS` dans `.env`.
|
| 309 |
+
|
| 310 |
+
```python
|
| 311 |
+
# app/main.py — configuration CORSMiddleware
|
| 312 |
+
app.add_middleware(
|
| 313 |
+
CORSMiddleware,
|
| 314 |
+
allow_origins=settings.ALLOWED_ORIGINS.split(","),
|
| 315 |
+
allow_credentials=True, # Obligatoire pour les cookies de session
|
| 316 |
+
allow_methods=["*"],
|
| 317 |
+
allow_headers=["*", "Authorization"],
|
| 318 |
+
)
|
| 319 |
+
```
|
| 320 |
+
|
| 321 |
+
| Environnement | `ALLOWED_ORIGINS` |
|
| 322 |
+
| ------------- | ---------------------------- |
|
| 323 |
+
| development | `http://localhost:3000` |
|
| 324 |
+
| staging | `https://staging.dedalys.ci` |
|
| 325 |
+
| production | `https://app.dedalys.ci` |
|
| 326 |
+
|
| 327 |
+
> Si le frontend affiche une erreur `CORS policy blocked`, vérifier que l'URL exacte
|
| 328 |
+
> (protocole + domaine + port) est bien listée dans `ALLOWED_ORIGINS`.
|
| 329 |
+
|
| 330 |
+
---
|
| 331 |
+
|
| 332 |
+
## 8. Les trois niveaux d'accès
|
| 333 |
+
|
| 334 |
+
```
|
| 335 |
+
┌──────────────────────────────────────────────────────────────┐
|
| 336 |
+
│ 🔴 SUPERADMIN (équipe Dedalys — concepteurs de la plateforme) │
|
| 337 |
+
│ • Créer / archiver des espaces (cabinets) │
|
| 338 |
+
│ • Créer / supprimer des utilisateurs │
|
| 339 |
+
│ ✗ N'a pas accès aux données métier des espaces │
|
| 340 |
+
└─────────────────────────┬────────────────────────────────────┘
|
| 341 |
+
│ crée et peuple
|
| 342 |
+
┌─────────────────────────▼────────────────────────────────────┐
|
| 343 |
+
│ 🟠 ADMIN ESPACE │
|
| 344 |
+
│ Automatiquement : associe_gerant ou office_manager │
|
| 345 |
+
│ • Modifier le rôle des membres de son espace │
|
| 346 |
+
│ • Accès aux données métier selon son rôle │
|
| 347 |
+
│ ✗ Ne peut pas ajouter ou supprimer des utilisateurs │
|
| 348 |
+
└─────────────────────────┬────────────────────────────────────┘
|
| 349 |
+
│ utilise
|
| 350 |
+
┌─────────────────────────▼────────────────────────────────────┐
|
| 351 |
+
│ 🟢 MEMBRE │
|
| 352 |
+
│ Automatiquement : avocat ou juriste │
|
| 353 |
+
│ • Accès aux données de leur espace selon leur rôle │
|
| 354 |
+
│ ✗ Ne peut pas modifier les rôles │
|
| 355 |
+
│ ✗ Ne peut pas ajouter ou supprimer des utilisateurs │
|
| 356 |
+
└──────────────────────────────────────────────────────────────┘
|
| 357 |
```
|
| 358 |
|
| 359 |
+
> **Règle clé :** le statut admin est **automatiquement déduit** du `role_cabinet`.
|
| 360 |
>
|
| 361 |
+
> - `associe_gerant` et `office_manager` → admin espace
|
| 362 |
+
> - `avocat` et `juriste` → membre simple
|
|
|
|
|
|
|
| 363 |
|
| 364 |
### Processus d'onboarding d'un nouveau cabinet
|
| 365 |
|
| 366 |
```
|
| 367 |
1. Superadmin crée l'espace
|
| 368 |
+
POST /api/v1/espaces
|
| 369 |
+
{ "nom": "Cabinet BK & Associés" }
|
| 370 |
|
| 371 |
2. Superadmin crée les utilisateurs
|
| 372 |
+
POST /api/v1/espaces/{espace_id}/utilisateurs
|
| 373 |
{ "email": "...", "password": "...", "role_cabinet": "associe_gerant" }
|
|
|
|
| 374 |
|
| 375 |
3. Les utilisateurs se connectent
|
| 376 |
+
POST /api/v1/auth/login
|
| 377 |
+
→ espace_id déduit automatiquement du profil, aucune configuration supplémentaire
|
| 378 |
```
|
| 379 |
|
| 380 |
---
|
| 381 |
|
| 382 |
+
## 9. Authentification
|
| 383 |
|
| 384 |
+
Pas d'auto-inscription. Les comptes sont **créés par les superadmins** uniquement.
|
| 385 |
|
| 386 |
### Se connecter
|
| 387 |
|
| 388 |
```http
|
| 389 |
+
POST /api/v1/auth/login
|
| 390 |
Content-Type: application/json
|
| 391 |
|
| 392 |
{
|
| 393 |
+
"email": "avocat@cabinet.ci",
|
| 394 |
"password": "motdepasse"
|
| 395 |
}
|
| 396 |
```
|
|
|
|
| 404 |
"token_type": "bearer",
|
| 405 |
"user": {
|
| 406 |
"id": "uuid",
|
| 407 |
+
"email": "avocat@cabinet.ci",
|
| 408 |
+
"nom": "Kouassi",
|
| 409 |
"prenom": "Jean",
|
| 410 |
"role_cabinet": "avocat",
|
| 411 |
"espace_id": "uuid-de-lespace",
|
|
|
|
| 422 |
|
| 423 |
L'espace est automatiquement déduit du profil — **aucun header `X-Espace-ID` n'est requis**.
|
| 424 |
|
| 425 |
+
> ⚠️ **Note sécurité MVP :** les tokens sont actuellement stockés côté client
|
| 426 |
+
> (voir guide front-end). Prévu : migration vers cookies `httpOnly + Secure + SameSite=Strict`
|
| 427 |
+
> avant le lancement commercial, conformément aux standards SaaS juridiques (Clio, Harvey).
|
| 428 |
+
|
| 429 |
### Durée de vie des tokens
|
| 430 |
|
| 431 |
+
| Token | Durée | À l'expiration |
|
| 432 |
+
| --------------- | ------- | ----------------------------------- |
|
| 433 |
+
| `access_token` | 1 heure | Appeler `POST /api/v1/auth/refresh` |
|
| 434 |
+
| `refresh_token` | 7 jours | Redemander un login |
|
| 435 |
|
| 436 |
### Renouveler le token
|
| 437 |
|
| 438 |
```http
|
| 439 |
+
POST /api/v1/auth/refresh
|
| 440 |
Content-Type: application/json
|
| 441 |
|
| 442 |
{ "refresh_token": "eyJ..." }
|
| 443 |
```
|
| 444 |
|
| 445 |
+
### Mot de passe oublié
|
| 446 |
+
|
| 447 |
+
```http
|
| 448 |
+
POST /api/v1/auth/forgot-password
|
| 449 |
+
Content-Type: application/json
|
| 450 |
+
|
| 451 |
+
{ "email": "avocat@cabinet.ci" }
|
| 452 |
+
```
|
| 453 |
+
|
| 454 |
+
Réponse : `200 OK` (même si l'email n'existe pas en base — sécurité anti-énumération).
|
| 455 |
+
|
| 456 |
+
Un email contenant un lien de réinitialisation est envoyé. Le lien est valide **1 heure**.
|
| 457 |
+
|
| 458 |
+
```http
|
| 459 |
+
POST /api/v1/auth/reset-password
|
| 460 |
+
Content-Type: application/json
|
| 461 |
+
|
| 462 |
+
{
|
| 463 |
+
"token": "token_extrait_du_lien_email",
|
| 464 |
+
"new_password": "nouveau_mot_de_passe"
|
| 465 |
+
}
|
| 466 |
+
```
|
| 467 |
+
|
| 468 |
+
> Implémentation : Supabase Auth gère ce flux nativement via `SUPABASE_RESET_PASSWORD_REDIRECT_URL`.
|
| 469 |
+
|
| 470 |
+
### Déconnexion
|
| 471 |
+
|
| 472 |
+
```http
|
| 473 |
+
POST /api/v1/auth/logout
|
| 474 |
+
Authorization: Bearer eyJ...
|
| 475 |
+
```
|
| 476 |
+
|
| 477 |
---
|
| 478 |
|
| 479 |
+
## 10. Système de rôles et permissions
|
| 480 |
|
| 481 |
### Qui est admin de l'espace ?
|
| 482 |
|
| 483 |
+
| `role_cabinet` | Statut | Peut modifier les rôles membres |
|
| 484 |
+
| ---------------- | --------- | -------------------------------- |
|
| 485 |
+
| `associe_gerant` | 🟠 Admin | ✅ Oui |
|
| 486 |
+
| `office_manager` | 🟠 Admin | ❌ Non (équipes dossier exclues) |
|
| 487 |
+
| `avocat` | 🟢 Membre | ❌ Non |
|
| 488 |
+
| `juriste` | 🟢 Membre | ❌ Non |
|
| 489 |
|
| 490 |
+
### Permissions métier par rôle
|
| 491 |
|
| 492 |
| Rôle | Clients | Dossiers | Audiences | Flash CR | Paiements | Fichiers |
|
| 493 |
| ---------------- | :-----: | :------: | :-------: | :------: | :-------: | :------: |
|
| 494 |
+
| `associe_gerant` | R/W/A | R/W/A | R/W/A | R/W/A | R/W/A | R/W/A |
|
| 495 |
+
| `office_manager` | R/W/A | R/W | R | R | R/W | R |
|
| 496 |
| `avocat` | R/W | R/W | R/W | R/W | R | R/W |
|
| 497 |
| `juriste` | R/W | R/W | R/W | R/W | R | R/W |
|
| 498 |
|
| 499 |
+
_R = Lecture · W = Écriture/Création · A = Archivage (soft delete)_
|
| 500 |
+
|
| 501 |
+
**Note — création de dossier :**
|
| 502 |
+
Les rôles `avocat` et `juriste` peuvent créer et modifier des dossiers.
|
| 503 |
+
L'archivage (suppression logique) est réservé à `associe_gerant`.
|
| 504 |
|
| 505 |
+
**Note — équipe dossier :**
|
| 506 |
|
| 507 |
+
| Action | Qui peut faire |
|
| 508 |
+
| --------------------------- | ----------------------------------- |
|
| 509 |
+
| Ajouter / retirer un membre | `associe_gerant` + `office_manager` |
|
| 510 |
+
| Changer le rôle d'un membre | `associe_gerant` uniquement |
|
| 511 |
|
| 512 |
---
|
| 513 |
|
| 514 |
+
## 11. Référence des endpoints
|
| 515 |
|
| 516 |
+
> Toutes les routes (sauf `/api/v1/auth/*`) nécessitent `Authorization: Bearer <token>`
|
| 517 |
|
| 518 |
### Authentification
|
| 519 |
|
| 520 |
+
| Méthode | Endpoint | Description |
|
| 521 |
+
| ------- | ------------------------------ | --------------------------------- |
|
| 522 |
+
| `POST` | `/api/v1/auth/login` | Se connecter |
|
| 523 |
+
| `POST` | `/api/v1/auth/refresh` | Renouveler le token |
|
| 524 |
+
| `POST` | `/api/v1/auth/logout` | Se déconnecter |
|
| 525 |
+
| `POST` | `/api/v1/auth/forgot-password` | Demander un reset de mot de passe |
|
| 526 |
+
| `POST` | `/api/v1/auth/reset-password` | Définir le nouveau mot de passe |
|
| 527 |
|
| 528 |
### Espaces — 🔴 Superadmin uniquement
|
| 529 |
|
| 530 |
+
| Méthode | Endpoint | Description |
|
| 531 |
+
| -------- | ----------------------------------------- | ---------------------------------- |
|
| 532 |
+
| `POST` | `/api/v1/espaces` | Créer un espace (cabinet) |
|
| 533 |
+
| `GET` | `/api/v1/espaces` | Lister tous les espaces |
|
| 534 |
+
| `GET` | `/api/v1/espaces/{id}` | Détail + membres |
|
| 535 |
+
| `PATCH` | `/api/v1/espaces/{id}` | Renommer l'espace |
|
| 536 |
+
| `DELETE` | `/api/v1/espaces/{id}` | Archiver l'espace (soft delete) |
|
| 537 |
+
| `POST` | `/api/v1/espaces/{id}/utilisateurs` | Créer un utilisateur dans l'espace |
|
| 538 |
+
| `DELETE` | `/api/v1/espaces/{id}/utilisateurs/{uid}` | Supprimer un utilisateur |
|
| 539 |
|
| 540 |
### Utilisateurs
|
| 541 |
|
| 542 |
+
| Méthode | Endpoint | Description | Qui |
|
| 543 |
+
| ------- | ---------------------------------------- | ----------------------- | --------------- |
|
| 544 |
+
| `GET` | `/api/v1/utilisateurs/me` | Mon profil | Tous |
|
| 545 |
+
| `PATCH` | `/api/v1/utilisateurs/me` | Modifier mon nom/prénom | Tous |
|
| 546 |
+
| `GET` | `/api/v1/utilisateurs` | Membres de mon espace | Tous |
|
| 547 |
+
| `GET` | `/api/v1/utilisateurs/{id}` | Profil d'un membre | Tous |
|
| 548 |
+
| `PATCH` | `/api/v1/utilisateurs/{id}/role-cabinet` | Changer le rôle métier | 🟠 Admin espace |
|
| 549 |
|
| 550 |
### Clients
|
| 551 |
|
| 552 |
+
| Méthode | Endpoint | Description |
|
| 553 |
+
| -------- | ------------------------------------- | ----------------------------------------------- |
|
| 554 |
+
| `POST` | `/api/v1/clients` | Créer un client |
|
| 555 |
+
| `GET` | `/api/v1/clients` | Lister les clients (paginé, filtrable) |
|
| 556 |
+
| `GET` | `/api/v1/clients/{id}` | Détail client |
|
| 557 |
+
| `PATCH` | `/api/v1/clients/{id}` | Modifier |
|
| 558 |
+
| `DELETE` | `/api/v1/clients/{id}` | Archiver (soft delete) |
|
| 559 |
+
| `GET` | `/api/v1/clients/{id}/vue360` | Vue complète (dossiers + audiences + paiements) |
|
| 560 |
+
| `POST` | `/api/v1/clients/{id}/contacts` | Ajouter un point de contact |
|
| 561 |
+
| `GET` | `/api/v1/clients/{id}/contacts` | Lister les contacts |
|
| 562 |
+
| `PATCH` | `/api/v1/clients/{id}/contacts/{cid}` | Modifier un contact |
|
| 563 |
+
| `DELETE` | `/api/v1/clients/{id}/contacts/{cid}` | Archiver un contact |
|
|
|
|
| 564 |
|
| 565 |
### Dossiers
|
| 566 |
|
| 567 |
+
| Méthode | Endpoint | Description | Restriction |
|
| 568 |
+
| -------- | ------------------------------------- | --------------------------------------- | --------------------------- |
|
| 569 |
+
| `POST` | `/api/v1/dossiers` | Créer un dossier | Tous les membres |
|
| 570 |
+
| `GET` | `/api/v1/dossiers` | Lister les dossiers (paginé, filtrable) | |
|
| 571 |
+
| `GET` | `/api/v1/dossiers/{id}` | Détail | |
|
| 572 |
+
| `PATCH` | `/api/v1/dossiers/{id}` | Modifier | Membres de l'équipe + admin |
|
| 573 |
+
| `DELETE` | `/api/v1/dossiers/{id}` | Archiver (soft delete) | `associe_gerant` |
|
| 574 |
+
| `GET` | `/api/v1/dossiers/{id}/recapitulatif` | Récapitulatif financier | |
|
| 575 |
+
| `POST` | `/api/v1/dossiers/{id}/equipe` | Ajouter un membre | Admin espace |
|
| 576 |
+
| `GET` | `/api/v1/dossiers/{id}/equipe` | Voir l'équipe | |
|
| 577 |
+
| `PATCH` | `/api/v1/dossiers/{id}/equipe/{uid}` | Changer le rôle | `associe_gerant` |
|
| 578 |
+
| `DELETE` | `/api/v1/dossiers/{id}/equipe/{uid}` | Retirer un membre | Admin espace |
|
|
|
|
| 579 |
|
| 580 |
### Audiences
|
| 581 |
|
| 582 |
+
| Méthode | Endpoint | Description |
|
| 583 |
+
| -------- | -------------------------------- | ---------------------------------------------------- |
|
| 584 |
+
| `POST` | `/api/v1/audiences` | Créer une audience ou réunion |
|
| 585 |
+
| `GET` | `/api/v1/audiences` | Toutes les audiences de l'espace (paginé, filtrable) |
|
| 586 |
+
| `GET` | `/api/v1/audiences/dossier/{id}` | Audiences d'un dossier |
|
| 587 |
+
| `GET` | `/api/v1/audiences/avocat/{id}` | Agenda d'un avocat |
|
| 588 |
+
| `GET` | `/api/v1/audiences/{id}` | Détail |
|
| 589 |
+
| `PATCH` | `/api/v1/audiences/{id}` | Modifier |
|
| 590 |
+
| `DELETE` | `/api/v1/audiences/{id}` | Archiver (soft delete) |
|
| 591 |
|
| 592 |
### Flash CR
|
| 593 |
|
| 594 |
+
| Méthode | Endpoint | Description |
|
| 595 |
+
| -------- | -------------------------------- | --------------------------------------- |
|
| 596 |
+
| `POST` | `/api/v1/flash-cr` | Créer un Flash CR (1 seul par audience) |
|
| 597 |
+
| `GET` | `/api/v1/flash-cr/audience/{id}` | Flash CR d'une audience |
|
| 598 |
+
| `GET` | `/api/v1/flash-cr/{id}` | Détail |
|
| 599 |
+
| `PATCH` | `/api/v1/flash-cr/{id}` | Modifier |
|
| 600 |
+
| `DELETE` | `/api/v1/flash-cr/{id}` | Archiver (soft delete) |
|
| 601 |
|
| 602 |
### Paiements
|
| 603 |
|
| 604 |
+
| Méthode | Endpoint | Description |
|
| 605 |
+
| -------- | -------------------------------- | -------------------------------------------------- |
|
| 606 |
+
| `POST` | `/api/v1/paiements` | Enregistrer un paiement |
|
| 607 |
+
| `GET` | `/api/v1/paiements` | Tous les paiements de l'espace (paginé, filtrable) |
|
| 608 |
+
| `GET` | `/api/v1/paiements/dossier/{id}` | Par dossier |
|
| 609 |
+
| `GET` | `/api/v1/paiements/client/{id}` | Par client |
|
| 610 |
+
| `GET` | `/api/v1/paiements/{id}` | Détail |
|
| 611 |
+
| `PATCH` | `/api/v1/paiements/{id}` | Modifier |
|
| 612 |
+
| `DELETE` | `/api/v1/paiements/{id}` | Archiver (soft delete) |
|
| 613 |
|
| 614 |
### Fichiers
|
| 615 |
|
| 616 |
+
| Méthode | Endpoint | Description |
|
| 617 |
+
| -------- | ------------------------------- | ------------------------------------------- |
|
| 618 |
+
| `POST` | `/api/v1/fichiers/dossier/{id}` | Uploader un fichier (`multipart/form-data`) |
|
| 619 |
+
| `GET` | `/api/v1/fichiers/dossier/{id}` | Lister les fichiers d'un dossier |
|
| 620 |
+
| `GET` | `/api/v1/fichiers/{id}` | Détail + signed URL (valide 15 min) |
|
| 621 |
+
| `DELETE` | `/api/v1/fichiers/{id}` | Archiver (soft delete) |
|
| 622 |
|
| 623 |
**Contraintes fichiers :** max 10 MB · 50 fichiers/dossier · Formats : PDF, DOC, DOCX, JPEG, PNG
|
| 624 |
|
| 625 |
+
### Audit Trail — `associe_gerant` uniquement
|
| 626 |
+
|
| 627 |
+
| Méthode | Endpoint | Description |
|
| 628 |
+
| ------- | --------------- | ---------------------------- |
|
| 629 |
+
| `GET` | `/api/v1/audit` | Logs des actions de l'espace |
|
| 630 |
+
|
| 631 |
---
|
| 632 |
|
| 633 |
+
## 12. Pagination, filtres et recherche
|
| 634 |
+
|
| 635 |
+
### Pagination
|
| 636 |
+
|
| 637 |
+
Tous les endpoints de liste supportent la pagination via query params :
|
| 638 |
+
|
| 639 |
+
```
|
| 640 |
+
?page=1 Page demandée (commence à 1, défaut : 1)
|
| 641 |
+
?limit=20 Éléments par page (défaut : 20, max : 100)
|
| 642 |
+
```
|
| 643 |
+
|
| 644 |
+
**Structure de réponse standardisée :**
|
| 645 |
+
|
| 646 |
+
```json
|
| 647 |
+
{
|
| 648 |
+
"data": [...],
|
| 649 |
+
"total": 87,
|
| 650 |
+
"page": 2,
|
| 651 |
+
"limit": 20,
|
| 652 |
+
"pages": 5
|
| 653 |
+
}
|
| 654 |
+
```
|
| 655 |
+
|
| 656 |
+
### Filtres par endpoint
|
| 657 |
+
|
| 658 |
+
**GET /api/v1/clients**
|
| 659 |
+
|
| 660 |
+
```
|
| 661 |
+
?search=SOTRA Recherche sur nom, email, téléphone
|
| 662 |
+
?type=PM PP | PM
|
| 663 |
+
?page=1&limit=20
|
| 664 |
+
```
|
| 665 |
+
|
| 666 |
+
**GET /api/v1/dossiers**
|
| 667 |
+
|
| 668 |
+
```
|
| 669 |
+
?search=licenciement Recherche sur titre, description
|
| 670 |
+
?statut=ouvert ouvert | en_instance | cloture
|
| 671 |
+
?type=contentieux pre_contentieux | contentieux | conseil | transactionnel
|
| 672 |
+
?client_id=uuid
|
| 673 |
+
?avocat_id=uuid
|
| 674 |
+
?page=1&limit=20
|
| 675 |
+
```
|
| 676 |
+
|
| 677 |
+
**GET /api/v1/audiences**
|
| 678 |
+
|
| 679 |
+
```
|
| 680 |
+
?type=audience audience | reunion
|
| 681 |
+
?avocat_id=uuid
|
| 682 |
+
?dossier_id=uuid
|
| 683 |
+
?date_debut=2026-03-01
|
| 684 |
+
?date_fin=2026-03-31
|
| 685 |
+
?page=1&limit=20
|
| 686 |
+
```
|
| 687 |
+
|
| 688 |
+
**GET /api/v1/paiements**
|
| 689 |
+
|
| 690 |
+
```
|
| 691 |
+
?client_id=uuid
|
| 692 |
+
?dossier_id=uuid
|
| 693 |
+
?type=honoraires honoraires | frais
|
| 694 |
+
?date_debut=2026-01-01
|
| 695 |
+
?date_fin=2026-03-31
|
| 696 |
+
?page=1&limit=20
|
| 697 |
+
```
|
| 698 |
+
|
| 699 |
+
**GET /api/v1/audit**
|
| 700 |
+
|
| 701 |
+
```
|
| 702 |
+
?ressource=paiement clients | dossiers | audiences | flash_cr | paiements | fichiers
|
| 703 |
+
?action=modification
|
| 704 |
+
?user_id=uuid
|
| 705 |
+
?date_debut=2026-01-01
|
| 706 |
+
?date_fin=2026-03-31
|
| 707 |
+
?page=1&limit=50
|
| 708 |
+
```
|
| 709 |
+
|
| 710 |
+
---
|
| 711 |
+
|
| 712 |
+
## 13. Rappels automatiques d'audience
|
| 713 |
+
|
| 714 |
+
Trois emails sont automatiquement envoyés avant chaque audience de type `audience`
|
| 715 |
+
(pas les réunions) :
|
| 716 |
+
|
| 717 |
+
| Délai | Objet de l'email |
|
| 718 |
+
| ----- | ------------------------------------------------- |
|
| 719 |
+
| J-7 | `[Dedalys] Audience dans 7 jours — [Nom dossier]` |
|
| 720 |
+
| J-3 | `[Dedalys] Audience dans 3 jours — [Nom dossier]` |
|
| 721 |
+
| J-1 | `[Dedalys] Audience demain — [Nom dossier]` |
|
| 722 |
+
|
| 723 |
+
**Contenu de l'email :**
|
| 724 |
+
|
| 725 |
+
- Titre du dossier
|
| 726 |
+
- Date et heure de l'audience
|
| 727 |
+
- Juridiction
|
| 728 |
+
- Lien direct vers l'audience dans Dedalys
|
| 729 |
+
|
| 730 |
+
**Destinataire :** l'avocat assigné à l'audience (`avocat_assigne_id`).
|
| 731 |
+
|
| 732 |
+
**Implémentation :** APScheduler exécute un job toutes les heures qui interroge les audiences
|
| 733 |
+
à venir et envoie les rappels manquants. Chaque rappel envoyé est marqué en base
|
| 734 |
+
(`rappel_j7_envoye`, `rappel_j3_envoye`, `rappel_j1_envoye`) pour éviter les doublons.
|
| 735 |
+
|
| 736 |
+
**Variables d'environnement requises :**
|
| 737 |
+
|
| 738 |
+
```env
|
| 739 |
+
RESEND_API_KEY=re_...
|
| 740 |
+
EMAIL_FROM=noreply@dedalys.ci
|
| 741 |
+
```
|
| 742 |
+
|
| 743 |
+
---
|
| 744 |
+
|
| 745 |
+
## 14. Flash CR — Email automatique client
|
| 746 |
+
|
| 747 |
+
Le Flash CR est la **killer feature** de Dedalys : après une audience, l'avocat saisit
|
| 748 |
+
le résultat en moins de 2 minutes et le client reçoit automatiquement un email.
|
| 749 |
+
|
| 750 |
+
### Règles métier
|
| 751 |
+
|
| 752 |
+
- Un Flash CR ne peut être créé que pour une audience dont la date est **passée** (< aujourd'hui).
|
| 753 |
+
- **Un seul Flash CR par audience** — si un CR existe déjà, l'API retourne `HTTP 409`.
|
| 754 |
+
- Si `envoyer_email = true` (valeur par défaut), l'email est envoyé immédiatement à la création.
|
| 755 |
+
|
| 756 |
+
### Valeurs acceptées pour `type_decision`
|
| 757 |
+
|
| 758 |
+
| Valeur | Description | Prochaine date requise |
|
| 759 |
+
| ------------------ | --------------------------------------- | ---------------------- |
|
| 760 |
+
| `decision_rendue` | Le juge a rendu sa décision | Non |
|
| 761 |
+
| `mise_en_delibere` | Décision reportée à une date ultérieure | **Oui** |
|
| 762 |
+
| `renvoi` | Affaire renvoyée | **Oui** |
|
| 763 |
+
| `autre` | Autre résultat (préciser dans `notes`) | Non |
|
| 764 |
+
|
| 765 |
+
### Email automatique
|
| 766 |
+
|
| 767 |
+
**Destinataires :** email principal du client lié au dossier + points de contact du dossier.
|
| 768 |
+
|
| 769 |
+
**Template :**
|
| 770 |
+
|
| 771 |
+
```
|
| 772 |
+
Objet : Compte-rendu d'audience — [Titre dossier] — [Date]
|
| 773 |
+
|
| 774 |
+
Corps : [Salutation personnalisée],
|
| 775 |
+
Suite à l'audience du [date] devant [juridiction],
|
| 776 |
+
[résumé de la décision].
|
| 777 |
+
[Si mise_en_delibere ou renvoi : Prochaine audience fixée au [date].]
|
| 778 |
+
[Notes complémentaires si renseignées.]
|
| 779 |
+
|
| 780 |
+
Cordialement,
|
| 781 |
+
[Nom du cabinet]
|
| 782 |
+
```
|
| 783 |
+
|
| 784 |
+
---
|
| 785 |
+
|
| 786 |
+
## 15. Gestion des fichiers
|
| 787 |
+
|
| 788 |
+
### Upload
|
| 789 |
+
|
| 790 |
+
```http
|
| 791 |
+
POST /api/v1/fichiers/dossier/{id}
|
| 792 |
+
Content-Type: multipart/form-data
|
| 793 |
+
Authorization: Bearer eyJ...
|
| 794 |
+
|
| 795 |
+
file: <fichier>
|
| 796 |
+
```
|
| 797 |
+
|
| 798 |
+
### Accès sécurisé — Signed URLs
|
| 799 |
+
|
| 800 |
+
`GET /api/v1/fichiers/{id}` retourne une **signed URL temporaire** (valide **15 minutes**),
|
| 801 |
+
pas une URL publique permanente.
|
| 802 |
+
|
| 803 |
+
```json
|
| 804 |
+
{
|
| 805 |
+
"id": "uuid",
|
| 806 |
+
"nom": "jugement_sotra.pdf",
|
| 807 |
+
"taille": 204800,
|
| 808 |
+
"type_mime": "application/pdf",
|
| 809 |
+
"url": "https://xxx.supabase.co/storage/v1/object/sign/...?token=...&expires=900",
|
| 810 |
+
"url_expire_dans": 900
|
| 811 |
+
}
|
| 812 |
+
```
|
| 813 |
+
|
| 814 |
+
> Le frontend doit demander une nouvelle URL à chaque téléchargement — ne pas mettre
|
| 815 |
+
> l'URL en cache.
|
| 816 |
+
|
| 817 |
+
**Contraintes :** max 10 MB par fichier · 50 fichiers max par dossier · Formats : PDF, DOC, DOCX, JPEG, PNG
|
| 818 |
+
|
| 819 |
+
---
|
| 820 |
+
|
| 821 |
+
## 16. Soft delete — conservation des données
|
| 822 |
+
|
| 823 |
+
**Aucune donnée n'est supprimée physiquement de la base.**
|
| 824 |
+
|
| 825 |
+
Tous les endpoints `DELETE` appliquent un **soft delete** :
|
| 826 |
+
|
| 827 |
+
```
|
| 828 |
+
is_archived = true + archived_at = timestamp_actuel
|
| 829 |
+
```
|
| 830 |
+
|
| 831 |
+
Les données archivées sont **automatiquement exclues** de toutes les réponses API.
|
| 832 |
+
Elles restent récupérables par le superadmin en cas d'erreur.
|
| 833 |
+
|
| 834 |
+
**Entités concernées :** Client · Dossier · Audience · Flash CR · Paiement · Fichier · Contact
|
| 835 |
+
|
| 836 |
+
**Justification :** les cabinets d'avocats ont des obligations déontologiques de conservation
|
| 837 |
+
des dossiers clients. Une suppression accidentelle d'un dossier avec son historique complet
|
| 838 |
+
serait irréversible et pourrait engager la responsabilité professionnelle du cabinet.
|
| 839 |
+
|
| 840 |
+
### Récupérer une donnée archivée par erreur (superadmin uniquement)
|
| 841 |
+
|
| 842 |
+
```http
|
| 843 |
+
PATCH /api/v1/{ressource}/{id}
|
| 844 |
+
Authorization: Bearer <token_superadmin>
|
| 845 |
+
|
| 846 |
+
{ "is_archived": false }
|
| 847 |
+
```
|
| 848 |
+
|
| 849 |
+
---
|
| 850 |
+
|
| 851 |
+
## 17. Audit trail
|
| 852 |
+
|
| 853 |
+
Toutes les actions sensibles sont automatiquement enregistrées dans la table `audit_logs`.
|
| 854 |
+
|
| 855 |
+
**Actions tracées :**
|
| 856 |
+
|
| 857 |
+
| Ressource | Actions enregistrées |
|
| 858 |
+
| ----------- | ------------------------------------------------------ |
|
| 859 |
+
| Paiement | Création · Modification · Archivage |
|
| 860 |
+
| Dossier | Changement de statut · Archivage · Modification équipe |
|
| 861 |
+
| Utilisateur | Changement de rôle |
|
| 862 |
+
| Fichier | Upload · Archivage |
|
| 863 |
+
|
| 864 |
+
**Structure d'un log :**
|
| 865 |
+
|
| 866 |
+
```json
|
| 867 |
+
{
|
| 868 |
+
"id": "uuid",
|
| 869 |
+
"action": "modification",
|
| 870 |
+
"ressource": "paiement",
|
| 871 |
+
"ressource_id": "uuid",
|
| 872 |
+
"user_id": "uuid",
|
| 873 |
+
"espace_id": "uuid",
|
| 874 |
+
"valeur_avant": { "montant": 500000 },
|
| 875 |
+
"valeur_apres": { "montant": 750000 },
|
| 876 |
+
"timestamp": "2026-03-15T14:32:00Z"
|
| 877 |
+
}
|
| 878 |
+
```
|
| 879 |
+
|
| 880 |
+
**Consultation :**
|
| 881 |
+
|
| 882 |
+
```http
|
| 883 |
+
GET /api/v1/audit?ressource=paiement&date_debut=2026-03-01
|
| 884 |
+
Authorization: Bearer <token_associe_gerant>
|
| 885 |
+
```
|
| 886 |
+
|
| 887 |
+
> Accès réservé au rôle `associe_gerant`.
|
| 888 |
+
|
| 889 |
+
---
|
| 890 |
+
|
| 891 |
+
## 18. Architecture multi-tenant
|
| 892 |
+
|
| 893 |
+
Chaque cabinet est un **espace** (tenant) isolé. Un utilisateur appartient à un
|
| 894 |
+
et un seul espace.
|
| 895 |
+
|
| 896 |
+
### Isolation des données — deux niveaux obligatoires
|
| 897 |
+
|
| 898 |
+
**Niveau 1 — Code (FastAPI) :**
|
| 899 |
+
|
| 900 |
+
L'`espace_id` est **toujours extrait du token JWT** via `get_current_user()`.
|
| 901 |
+
Il est systématiquement injecté dans chaque requête SQL. Il ne doit **jamais**
|
| 902 |
+
provenir des paramètres de la requête.
|
| 903 |
+
|
| 904 |
+
```python
|
| 905 |
+
# ✅ Correct
|
| 906 |
+
async def get_dossiers(current_user: User = Depends(get_current_user)):
|
| 907 |
+
return db.query(Dossier).filter(
|
| 908 |
+
Dossier.espace_id == current_user.espace_id,
|
| 909 |
+
Dossier.is_archived == False
|
| 910 |
+
).all()
|
| 911 |
+
|
| 912 |
+
# ❌ INTERDIT — ne jamais faire ça
|
| 913 |
+
async def get_dossiers(espace_id: str):
|
| 914 |
+
...
|
| 915 |
+
```
|
| 916 |
+
|
| 917 |
+
**Niveau 2 — Base de données (Supabase RLS) :**
|
| 918 |
+
|
| 919 |
+
Row Level Security est activé sur toutes les tables métier. Une requête sans
|
| 920 |
+
`espace_id` valide retourne 0 résultats, même si le filtre est oublié dans le code.
|
| 921 |
+
|
| 922 |
+
```sql
|
| 923 |
+
-- Policy appliquée sur toutes les tables (exemple : dossiers)
|
| 924 |
+
CREATE POLICY "isolation_par_espace" ON dossiers
|
| 925 |
+
USING (espace_id = auth.jwt() ->> 'espace_id');
|
| 926 |
+
```
|
| 927 |
+
|
| 928 |
+
**Règle pour chaque nouvel endpoint :**
|
| 929 |
+
Toujours utiliser `get_current_user()` comme dépendance.
|
| 930 |
+
Ne jamais faire confiance aux paramètres de requête pour identifier le tenant.
|
| 931 |
+
|
| 932 |
+
### Limites par espace (MVP)
|
| 933 |
+
|
| 934 |
+
Pour la phase beta, aucune limite stricte n'est appliquée. À implémenter avant le
|
| 935 |
+
lancement commercial :
|
| 936 |
+
|
| 937 |
+
- Nombre maximum de dossiers actifs par espace
|
| 938 |
+
- Quota de stockage fichiers par espace
|
| 939 |
+
- Nombre maximum de membres par espace
|
| 940 |
+
|
| 941 |
+
---
|
| 942 |
+
|
| 943 |
+
## 19. Modèle de données
|
| 944 |
+
|
| 945 |
+
```
|
| 946 |
+
Espace (1 par cabinet)
|
| 947 |
+
│
|
| 948 |
+
├──< Utilisateurs
|
| 949 |
+
│ role_cabinet → associe_gerant / office_manager = admin
|
| 950 |
+
│ → avocat / juriste = membre
|
| 951 |
+
│
|
| 952 |
+
├──< Clients
|
| 953 |
+
│ ├──< PointsDeContact
|
| 954 |
+
│ └──< Paiements
|
| 955 |
+
│ │
|
| 956 |
+
└──< Dossiers
|
| 957 |
+
├──< EquipeDossier >── Utilisateur
|
| 958 |
+
├──< Audiences
|
| 959 |
+
│ └── FlashCR (1 par audience max)
|
| 960 |
+
├──< Paiements
|
| 961 |
+
└──< Fichiers
|
| 962 |
+
```
|
| 963 |
+
|
| 964 |
+
### Valeurs acceptées
|
| 965 |
+
|
| 966 |
+
| Champ | Valeurs |
|
| 967 |
+
| ------------------------ | ------------------------------------------------------------- |
|
| 968 |
+
| `statut` Client | `PP`, `PM` |
|
| 969 |
+
| `type` Dossier | `pre_contentieux`, `contentieux`, `conseil`, `transactionnel` |
|
| 970 |
+
| `statut` Dossier | `ouvert`, `en_instance`, `cloture` |
|
| 971 |
+
| `preference_facturation` | `forfait`, `capped_fees` |
|
| 972 |
+
| `type` Paiement | `honoraires`, `frais` |
|
| 973 |
+
| `type` Audience | `audience`, `reunion` |
|
| 974 |
+
| `type_decision` Flash CR | `decision_rendue`, `mise_en_delibere`, `renvoi`, `autre` |
|
| 975 |
+
| `role_cabinet` | `associe_gerant`, `avocat`, `juriste`, `office_manager` |
|
| 976 |
+
| `role` EquipeDossier | `responsable`, `collaborateur` |
|
| 977 |
+
|
| 978 |
+
---
|
| 979 |
+
|
| 980 |
+
## 20. Guide pour le développeur front-end
|
| 981 |
|
| 982 |
### Client HTTP (Axios)
|
| 983 |
|
|
|
|
| 985 |
// lib/api.ts
|
| 986 |
import axios from "axios";
|
| 987 |
|
| 988 |
+
const api = axios.create({
|
| 989 |
+
baseURL: process.env.NEXT_PUBLIC_API_URL, // ex: http://localhost:8000/api/v1
|
| 990 |
+
});
|
| 991 |
|
| 992 |
// Injecter le token automatiquement
|
| 993 |
+
// ⚠️ NOTE MVP : localStorage utilisé pour simplifier l'implémentation beta.
|
| 994 |
+
// Migration prévue vers cookies httpOnly avant le lancement commercial.
|
| 995 |
api.interceptors.request.use((config) => {
|
| 996 |
const token = localStorage.getItem("access_token");
|
| 997 |
if (token) config.headers["Authorization"] = `Bearer ${token}`;
|
|
|
|
| 1005 |
if (error.response?.status === 401) {
|
| 1006 |
try {
|
| 1007 |
const refresh = localStorage.getItem("refresh_token");
|
| 1008 |
+
const { data } = await axios.post(
|
| 1009 |
+
`${process.env.NEXT_PUBLIC_API_URL}/auth/refresh`,
|
| 1010 |
+
{ refresh_token: refresh },
|
| 1011 |
+
);
|
| 1012 |
localStorage.setItem("access_token", data.access_token);
|
| 1013 |
localStorage.setItem("refresh_token", data.refresh_token);
|
| 1014 |
error.config.headers["Authorization"] = `Bearer ${data.access_token}`;
|
| 1015 |
return axios(error.config);
|
| 1016 |
} catch {
|
|
|
|
| 1017 |
localStorage.clear();
|
| 1018 |
window.location.href = "/login";
|
| 1019 |
}
|
|
|
|
| 1028 |
### Flux de connexion
|
| 1029 |
|
| 1030 |
```typescript
|
| 1031 |
+
// Login
|
| 1032 |
const { data } = await api.post("/auth/login", { email, password });
|
|
|
|
| 1033 |
localStorage.setItem("access_token", data.access_token);
|
| 1034 |
localStorage.setItem("refresh_token", data.refresh_token);
|
| 1035 |
|
| 1036 |
+
// data.user contient :
|
| 1037 |
+
// user.espace_id → UUID du cabinet (automatiquement dans toutes les requêtes)
|
| 1038 |
+
// user.role_cabinet → "associe_gerant" | "avocat" | "juriste" | "office_manager"
|
| 1039 |
+
// user.is_superadmin → true | false
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1040 |
```
|
| 1041 |
|
| 1042 |
### Détecter le statut admin côté front
|
|
|
|
| 1044 |
```typescript
|
| 1045 |
const ADMIN_ROLES = ["associe_gerant", "office_manager"];
|
| 1046 |
|
| 1047 |
+
const isEspaceAdmin = (user: User) => ADMIN_ROLES.includes(user.role_cabinet);
|
| 1048 |
+
const isSuperAdmin = (user: User) => user.is_superadmin === true;
|
| 1049 |
```
|
| 1050 |
|
| 1051 |
### Upload de fichier
|
|
|
|
| 1059 |
headers: { "Content-Type": "multipart/form-data" },
|
| 1060 |
});
|
| 1061 |
|
| 1062 |
+
// data.url → signed URL temporaire, valide 15 minutes
|
| 1063 |
+
// Ne pas mettre cette URL en cache côté client
|
| 1064 |
return data;
|
| 1065 |
};
|
| 1066 |
```
|
| 1067 |
|
| 1068 |
### Codes d'erreur
|
| 1069 |
|
| 1070 |
+
| Code | Signification | Action côté front |
|
| 1071 |
+
| ----- | ------------------------------------ | -------------------------------------------- |
|
| 1072 |
+
| `401` | Token invalide ou expiré | L'intercepteur rafraîchit automatiquement |
|
| 1073 |
+
| `403` | Permission refusée | Afficher "accès refusé" |
|
| 1074 |
+
| `404` | Ressource introuvable | Afficher message d'erreur |
|
| 1075 |
+
| `409` | Conflit (ex: Flash CR déjà existant) | Afficher `error.response.data.detail` |
|
| 1076 |
+
| `422` | Données invalides | Afficher les erreurs de champs |
|
| 1077 |
+
| `429` | Trop de requêtes | Réessayer après délai (header `Retry-After`) |
|
| 1078 |
|
| 1079 |
+
**Format des erreurs :**
|
| 1080 |
|
| 1081 |
```json
|
| 1082 |
{ "detail": "Message d'erreur lisible" }
|
|
|
|
| 1084 |
|
| 1085 |
---
|
| 1086 |
|
| 1087 |
+
## 21. Créer le premier superadmin
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1088 |
|
| 1089 |
+
Les superadmins ne peuvent pas s'auto-créer via l'API. Procédure manuelle, **à faire une seule fois**.
|
| 1090 |
|
| 1091 |
**Étape 1 — Créer le compte dans Supabase Auth**
|
| 1092 |
|
| 1093 |
Dans **Supabase Dashboard → Authentication → Users → Add user** :
|
| 1094 |
|
| 1095 |
- Email : `superadmin@dedalys.com`
|
| 1096 |
+
- Password : mot de passe fort (20+ caractères)
|
| 1097 |
- ✅ Cocher "Auto Confirm User"
|
| 1098 |
|
| 1099 |
**Étape 2 — Créer le profil en base**
|
|
|
|
| 1109 |
'Dedalys',
|
| 1110 |
'associe_gerant',
|
| 1111 |
NULL, -- pas d'espace pour les superadmins
|
| 1112 |
+
TRUE
|
| 1113 |
);
|
| 1114 |
```
|
| 1115 |
|
| 1116 |
+
**Étape 3 — Vérifier**
|
| 1117 |
|
| 1118 |
```http
|
| 1119 |
+
POST /api/v1/auth/login
|
| 1120 |
{ "email": "superadmin@dedalys.com", "password": "..." }
|
| 1121 |
```
|
| 1122 |
|
| 1123 |
+
La réponse doit contenir `"is_superadmin": true`.
|
| 1124 |
|
| 1125 |
### Créer des superadmins supplémentaires
|
| 1126 |
|
| 1127 |
Répéter les étapes 1 et 2 pour chaque superadmin à ajouter.
|
| 1128 |
+
|
| 1129 |
+
---
|
| 1130 |
+
|
| 1131 |
+
_Dedalys Backend API · MVP v1.0 · Confidentiel — Usage interne uniquement_
|
| 1132 |
+
|
| 1133 |
+
---
|
| 1134 |
+
|
| 1135 |
+
# 🏛️ Dedalys Backend API
|
| 1136 |
+
|
| 1137 |
+
> Solution de gestion pour cabinets d'avocats et directions juridiques en Afrique francophone.
|
| 1138 |
+
|
| 1139 |
+
**Version:** 1.0.0
|
| 1140 |
+
**Stack:** FastAPI + Supabase + PostgreSQL
|
| 1141 |
+
**Conformité:** Audit Backend v2 (17/17 points traités)
|
| 1142 |
+
|
| 1143 |
+
---
|
| 1144 |
+
|
| 1145 |
+
## 📋 Table des Matières
|
| 1146 |
+
|
| 1147 |
+
- [Démarrage Rapide](#-démarrage-rapide)
|
| 1148 |
+
- [Architecture](#-architecture)
|
| 1149 |
+
- [Endpoints API](#-endpoints-api)
|
| 1150 |
+
- [Modèle de Données](#-modèle-de-données)
|
| 1151 |
+
- [Sécurité](#-sécurité)
|
| 1152 |
+
- [Déploiement](#-déploiement)
|
| 1153 |
+
|
| 1154 |
+
---
|
| 1155 |
+
|
| 1156 |
+
## 🚀 Démarrage Rapide
|
| 1157 |
+
|
| 1158 |
+
### Prérequis
|
| 1159 |
+
|
| 1160 |
+
- Python 3.11+
|
| 1161 |
+
- Compte Supabase (projet créé)
|
| 1162 |
+
- Variables d'environnement configurées
|
| 1163 |
+
|
| 1164 |
+
### Installation
|
| 1165 |
+
|
| 1166 |
+
```bash
|
| 1167 |
+
# Cloner le repo
|
| 1168 |
+
git clone https://gitlab.com/dedalys/backend.git
|
| 1169 |
+
cd backend
|
| 1170 |
+
|
| 1171 |
+
# Créer l'environnement virtuel
|
| 1172 |
+
python -m venv venv
|
| 1173 |
+
source venv/bin/activate # Linux/Mac
|
| 1174 |
+
# ou: venv\Scripts\activate # Windows
|
| 1175 |
+
|
| 1176 |
+
# Installer les dépendances
|
| 1177 |
+
pip install -r requirements.txt
|
| 1178 |
+
|
| 1179 |
+
# Configurer l'environnement
|
| 1180 |
+
cp .env.example .env
|
| 1181 |
+
# Éditer .env avec vos valeurs Supabase
|
| 1182 |
+
```
|
| 1183 |
+
|
| 1184 |
+
### Lancement
|
| 1185 |
+
|
| 1186 |
+
```bash
|
| 1187 |
+
# Développement
|
| 1188 |
+
uvicorn app.main:app --reload --port 8000
|
| 1189 |
+
|
| 1190 |
+
# Production
|
| 1191 |
+
uvicorn app.main:app --host 0.0.0.0 --port 8080
|
| 1192 |
+
```
|
| 1193 |
+
|
| 1194 |
+
### Documentation API
|
| 1195 |
+
|
| 1196 |
+
- Swagger UI: http://localhost:8000/api/v1/docs
|
| 1197 |
+
- ReDoc: http://localhost:8000/api/v1/redoc
|
| 1198 |
+
|
| 1199 |
+
---
|
| 1200 |
+
|
| 1201 |
+
## 🏗️ Architecture
|
| 1202 |
+
|
| 1203 |
+
```
|
| 1204 |
+
dedalys-backend/
|
| 1205 |
+
├── app/
|
| 1206 |
+
│ ├── __init__.py
|
| 1207 |
+
│ ├── main.py # Point d'entrée FastAPI
|
| 1208 |
+
│ ├── core/
|
| 1209 |
+
│ │ ├── __init__.py
|
| 1210 |
+
│ │ ├── config.py # Variables d'environnement
|
| 1211 |
+
│ │ ├── supabase.py # Clients Supabase
|
| 1212 |
+
│ │ ├── auth.py # Authentification & dépendances
|
| 1213 |
+
│ │ └── permissions.py # Matrice des rôles
|
| 1214 |
+
│ ├── models/
|
| 1215 |
+
│ │ ├── __init__.py
|
| 1216 |
+
│ │ └── schemas.py # Schémas Pydantic
|
| 1217 |
+
│ └── routers/
|
| 1218 |
+
│ ├── __init__.py
|
| 1219 |
+
│ ├── auth.py # Login, refresh, reset password
|
| 1220 |
+
│ ├── espaces.py # CRUD espaces (superadmin)
|
| 1221 |
+
│ ├── utilisateurs.py # Profil & gestion utilisateurs
|
| 1222 |
+
│ ├── clients.py # CRUD clients + Vue 360°
|
| 1223 |
+
│ ├── dossiers.py # CRUD dossiers + équipe
|
| 1224 |
+
│ ├── audiences.py # CRUD audiences/réunions
|
| 1225 |
+
│ ├── flash_cr.py # Comptes-rendus d'audience
|
| 1226 |
+
│ ├── paiements.py # Suivi facturation
|
| 1227 |
+
│ ├── fichiers.py # Upload & téléchargement
|
| 1228 |
+
│ └── audit.py # Consultation audit trail
|
| 1229 |
+
├── sql/
|
| 1230 |
+
│ └── schema.sql # Schéma BDD + RLS policies
|
| 1231 |
+
├── .env.example
|
| 1232 |
+
├── requirements.txt
|
| 1233 |
+
└── README.md
|
| 1234 |
+
```
|
| 1235 |
+
|
| 1236 |
+
---
|
| 1237 |
+
|
| 1238 |
+
## 📡 Endpoints API
|
| 1239 |
+
|
| 1240 |
+
Tous les endpoints sont sous `/api/v1/`.
|
| 1241 |
+
|
| 1242 |
+
### Authentification
|
| 1243 |
+
|
| 1244 |
+
| Méthode | Endpoint | Description |
|
| 1245 |
+
| ------- | ----------------------- | ------------------------ |
|
| 1246 |
+
| POST | `/auth/login` | Connexion email/password |
|
| 1247 |
+
| POST | `/auth/refresh` | Renouvellement token |
|
| 1248 |
+
| POST | `/auth/logout` | Déconnexion |
|
| 1249 |
+
| POST | `/auth/forgot-password` | Demande reset password |
|
| 1250 |
+
| POST | `/auth/reset-password` | Nouveau mot de passe |
|
| 1251 |
+
|
| 1252 |
+
### Clients
|
| 1253 |
+
|
| 1254 |
+
| Méthode | Endpoint | Description |
|
| 1255 |
+
| ------- | ------------------------ | -------------------------- |
|
| 1256 |
+
| GET | `/clients` | Liste paginée avec filtres |
|
| 1257 |
+
| POST | `/clients` | Créer un client |
|
| 1258 |
+
| GET | `/clients/{id}` | Détail client |
|
| 1259 |
+
| PATCH | `/clients/{id}` | Modifier client |
|
| 1260 |
+
| DELETE | `/clients/{id}` | Archiver (soft delete) |
|
| 1261 |
+
| GET | `/clients/{id}/vue360` | Vue 360° complète |
|
| 1262 |
+
| POST | `/clients/{id}/contacts` | Ajouter point de contact |
|
| 1263 |
+
|
| 1264 |
+
### Dossiers
|
| 1265 |
+
|
| 1266 |
+
| Méthode | Endpoint | Description |
|
| 1267 |
+
| ------- | ------------------------------ | --------------------- |
|
| 1268 |
+
| GET | `/dossiers` | Liste avec filtres |
|
| 1269 |
+
| POST | `/dossiers` | Créer un dossier |
|
| 1270 |
+
| GET | `/dossiers/{id}` | Détail dossier |
|
| 1271 |
+
| PATCH | `/dossiers/{id}` | Modifier dossier |
|
| 1272 |
+
| DELETE | `/dossiers/{id}` | Archiver |
|
| 1273 |
+
| GET | `/dossiers/{id}/recapitulatif` | Récap financier |
|
| 1274 |
+
| POST | `/dossiers/{id}/equipe` | Ajouter membre équipe |
|
| 1275 |
+
|
| 1276 |
+
### Audiences
|
| 1277 |
+
|
| 1278 |
+
| Méthode | Endpoint | Description |
|
| 1279 |
+
| ------- | -------------------- | ---------------------- |
|
| 1280 |
+
| GET | `/audiences` | Liste avec filtres |
|
| 1281 |
+
| POST | `/audiences` | Créer audience/réunion |
|
| 1282 |
+
| GET | `/audiences/a-venir` | Audiences à venir |
|
| 1283 |
+
| GET | `/audiences/{id}` | Détail audience |
|
| 1284 |
+
| DELETE | `/audiences/{id}` | Archiver |
|
| 1285 |
+
|
| 1286 |
+
### Flash CR
|
| 1287 |
+
|
| 1288 |
+
| Méthode | Endpoint | Description |
|
| 1289 |
+
| ------- | ------------------------- | ------------------ |
|
| 1290 |
+
| POST | `/flash-cr` | Créer compte-rendu |
|
| 1291 |
+
| GET | `/flash-cr/audience/{id}` | CR d'une audience |
|
| 1292 |
+
| GET | `/flash-cr/dossier/{id}` | CRs d'un dossier |
|
| 1293 |
+
|
| 1294 |
+
### Paiements
|
| 1295 |
+
|
| 1296 |
+
| Méthode | Endpoint | Description |
|
| 1297 |
+
| ------- | ------------------------- | ---------------------- |
|
| 1298 |
+
| GET | `/paiements` | Liste paginée |
|
| 1299 |
+
| POST | `/paiements` | Enregistrer paiement |
|
| 1300 |
+
| GET | `/paiements/dossier/{id}` | Paiements d'un dossier |
|
| 1301 |
+
|
| 1302 |
+
### Fichiers
|
| 1303 |
+
|
| 1304 |
+
| Méthode | Endpoint | Description |
|
| 1305 |
+
| ------- | ------------------------ | ------------------------ |
|
| 1306 |
+
| POST | `/fichiers/dossier/{id}` | Upload fichier |
|
| 1307 |
+
| GET | `/fichiers/dossier/{id}` | Liste fichiers |
|
| 1308 |
+
| GET | `/fichiers/{id}` | Télécharger (signed URL) |
|
| 1309 |
+
|
| 1310 |
+
---
|
| 1311 |
+
|
| 1312 |
+
## 🗄️ Modèle de Données
|
| 1313 |
+
|
| 1314 |
+
### Entités principales
|
| 1315 |
+
|
| 1316 |
+
```
|
| 1317 |
+
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
|
| 1318 |
+
│ Espace │────<│ Utilisateur│ │ Client │
|
| 1319 |
+
└─────────────┘ └─────────────┘ └──────┬──────┘
|
| 1320 |
+
│ │ │
|
| 1321 |
+
│ │ │
|
| 1322 |
+
▼ ▼ ▼
|
| 1323 |
+
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
|
| 1324 |
+
│ Dossier │<────│EquipeDossier│ │ Paiement │
|
| 1325 |
+
└──────┬──────┘ └─────────────┘ └─────────────┘
|
| 1326 |
+
│
|
| 1327 |
+
├─────────────────┬─────────────────┐
|
| 1328 |
+
▼ ▼ ▼
|
| 1329 |
+
┌─────────────┐ ┌─────────────┐ ┌────────────��┐
|
| 1330 |
+
│ Audience │ │ Fichier │ │ Flash CR │
|
| 1331 |
+
└─────────────┘ └─────────────┘ └─────────────┘
|
| 1332 |
+
```
|
| 1333 |
+
|
| 1334 |
+
### Soft Delete
|
| 1335 |
+
|
| 1336 |
+
Toutes les entités métier incluent :
|
| 1337 |
+
|
| 1338 |
+
- `is_archived: BOOLEAN DEFAULT FALSE`
|
| 1339 |
+
- `archived_at: TIMESTAMPTZ`
|
| 1340 |
+
|
| 1341 |
+
Les requêtes filtrent automatiquement `is_archived = FALSE`.
|
| 1342 |
+
|
| 1343 |
+
---
|
| 1344 |
+
|
| 1345 |
+
## 🔐 Sécurité
|
| 1346 |
+
|
| 1347 |
+
### Authentification
|
| 1348 |
+
|
| 1349 |
+
- JWT via Supabase Auth
|
| 1350 |
+
- Access token : 1 heure
|
| 1351 |
+
- Refresh token : 7 jours
|
| 1352 |
+
|
| 1353 |
+
### Rôles Cabinet
|
| 1354 |
+
|
| 1355 |
+
| Rôle | Permissions |
|
| 1356 |
+
| ---------------- | ------------------------------------------ |
|
| 1357 |
+
| `associe_gerant` | Accès complet + audit |
|
| 1358 |
+
| `avocat` | CRUD dossiers/audiences, lecture paiements |
|
| 1359 |
+
| `juriste` | CRUD dossiers/audiences, lecture paiements |
|
| 1360 |
+
| `office_manager` | CRUD clients/paiements, lecture dossiers |
|
| 1361 |
+
|
| 1362 |
+
### Multi-tenant
|
| 1363 |
+
|
| 1364 |
+
- Isolation par `espace_id` sur toutes les requêtes
|
| 1365 |
+
- RLS PostgreSQL comme couche supplémentaire
|
| 1366 |
+
- Service role pour l'API (bypass RLS contrôlé)
|
| 1367 |
+
|
| 1368 |
+
### CORS
|
| 1369 |
+
|
| 1370 |
+
Configurable via `ALLOWED_ORIGINS` dans `.env`.
|
| 1371 |
+
|
| 1372 |
+
---
|
| 1373 |
+
|
| 1374 |
+
## 🚢 Déploiement
|
| 1375 |
+
|
| 1376 |
+
### Variables d'environnement requises
|
| 1377 |
+
|
| 1378 |
+
```env
|
| 1379 |
+
# Supabase
|
| 1380 |
+
SUPABASE_URL=https://xxx.supabase.co
|
| 1381 |
+
SUPABASE_ANON_KEY=eyJ...
|
| 1382 |
+
SUPABASE_SERVICE_KEY=eyJ...
|
| 1383 |
+
SUPABASE_JWT_SECRET=xxx
|
| 1384 |
+
|
| 1385 |
+
# Application
|
| 1386 |
+
APP_ENV=production
|
| 1387 |
+
ALLOWED_ORIGINS=https://app.dedalys.ci
|
| 1388 |
+
FRONTEND_URL=https://app.dedalys.ci
|
| 1389 |
+
|
| 1390 |
+
# Storage
|
| 1391 |
+
STORAGE_BUCKET=dedalys-fichiers
|
| 1392 |
+
STORAGE_SIGNED_URL_EXPIRY=900
|
| 1393 |
+
|
| 1394 |
+
# Reset Password
|
| 1395 |
+
SUPABASE_RESET_PASSWORD_REDIRECT_URL=https://app.dedalys.ci/reset-password
|
| 1396 |
+
```
|
| 1397 |
+
|
| 1398 |
+
### Cloud Run (recommandé)
|
| 1399 |
+
|
| 1400 |
+
```bash
|
| 1401 |
+
# Build
|
| 1402 |
+
docker build -t dedalys-api .
|
| 1403 |
+
|
| 1404 |
+
# Deploy
|
| 1405 |
+
gcloud run deploy dedalys-api \
|
| 1406 |
+
--image gcr.io/PROJECT/dedalys-api \
|
| 1407 |
+
--platform managed \
|
| 1408 |
+
--region europe-west1 \
|
| 1409 |
+
--allow-unauthenticated
|
| 1410 |
+
```
|
| 1411 |
+
|
| 1412 |
+
### Base de données
|
| 1413 |
+
|
| 1414 |
+
1. Créer un projet Supabase
|
| 1415 |
+
2. Exécuter `sql/schema.sql` dans l'éditeur SQL
|
| 1416 |
+
3. Créer le bucket Storage `dedalys-fichiers` (privé)
|
| 1417 |
+
|
| 1418 |
+
---
|
| 1419 |
+
|
| 1420 |
+
## 📊 Conformité Audit v2
|
| 1421 |
+
|
| 1422 |
+
| # | Point d'audit | Statut |
|
| 1423 |
+
| --- | ------------------------------- | ------------ |
|
| 1424 |
+
| 1 | API versioning `/api/v1/` | ✅ |
|
| 1425 |
+
| 2 | CORS depuis `.env` | ✅ |
|
| 1426 |
+
| 3 | Soft delete sur toutes entités | ✅ |
|
| 1427 |
+
| 4 | Reset password endpoints | ✅ |
|
| 1428 |
+
| 5 | Permissions `dossier:write` | ✅ |
|
| 1429 |
+
| 6 | Isolation multi-tenant | ✅ |
|
| 1430 |
+
| 7 | Variables `.env` complètes | ✅ |
|
| 1431 |
+
| 8 | Pagination standardisée | ✅ |
|
| 1432 |
+
| 9 | Flash CR `mise_en_delibere` | ✅ |
|
| 1433 |
+
| 10 | Audience `type` + flags rappels | ✅ |
|
| 1434 |
+
| 11 | Signed URLs fichiers | ✅ |
|
| 1435 |
+
| 12 | Filtres et recherche | ✅ |
|
| 1436 |
+
| 13 | Audit trail table + endpoint | ✅ |
|
| 1437 |
+
| 14 | Schéma SQL complet + RLS | ✅ |
|
| 1438 |
+
| 15 | httpOnly cookies | ⚠️ Frontend |
|
| 1439 |
+
| 16 | Rate limiting | ⚠️ Cloud Run |
|
| 1440 |
+
| 17 | APScheduler + Resend | ⚠️ Post-beta |
|
| 1441 |
+
|
| 1442 |
+
---
|
| 1443 |
+
|
| 1444 |
+
## 📞 Support
|
| 1445 |
+
|
| 1446 |
+
- **Email:** tech@dedalys.ci
|
| 1447 |
+
- **Documentation:** https://docs.dedalys.ci
|
| 1448 |
+
|
| 1449 |
+
---
|
| 1450 |
+
|
| 1451 |
+
_Dedalys — Le système d'exploitation des cabinets d'avocats en Afrique francophone_
|
app/__pycache__/main.cpython-313.pyc
CHANGED
|
Binary files a/app/__pycache__/main.cpython-313.pyc and b/app/__pycache__/main.cpython-313.pyc differ
|
|
|
app/core/__pycache__/auth.cpython-313.pyc
CHANGED
|
Binary files a/app/core/__pycache__/auth.cpython-313.pyc and b/app/core/__pycache__/auth.cpython-313.pyc differ
|
|
|
app/core/__pycache__/config.cpython-313.pyc
CHANGED
|
Binary files a/app/core/__pycache__/config.cpython-313.pyc and b/app/core/__pycache__/config.cpython-313.pyc differ
|
|
|
app/core/__pycache__/permissions.cpython-313.pyc
CHANGED
|
Binary files a/app/core/__pycache__/permissions.cpython-313.pyc and b/app/core/__pycache__/permissions.cpython-313.pyc differ
|
|
|
app/core/__pycache__/supabase.cpython-313.pyc
CHANGED
|
Binary files a/app/core/__pycache__/supabase.cpython-313.pyc and b/app/core/__pycache__/supabase.cpython-313.pyc differ
|
|
|
app/core/auth.py
CHANGED
|
@@ -1,174 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from typing import Optional
|
|
|
|
|
|
|
| 2 |
from fastapi import Depends, HTTPException, status
|
| 3 |
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
| 4 |
-
from app.core.permissions import RoleCabinet, is_espace_admin, has_permission
|
| 5 |
-
from app.core.supabase import supabase_admin
|
| 6 |
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
|
|
|
|
| 10 |
class CurrentUser:
|
| 11 |
-
"""
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
|
|
|
|
|
|
| 17 |
|
| 18 |
-
def __init__(
|
| 19 |
-
self,
|
| 20 |
-
id: str,
|
| 21 |
-
email: str,
|
| 22 |
-
role_cabinet: RoleCabinet,
|
| 23 |
-
espace_id: Optional[str],
|
| 24 |
-
is_superadmin: bool,
|
| 25 |
-
):
|
| 26 |
-
self.id = id
|
| 27 |
-
self.email = email
|
| 28 |
-
self.role_cabinet = role_cabinet
|
| 29 |
-
self.espace_id = espace_id
|
| 30 |
-
self.is_superadmin = is_superadmin
|
| 31 |
-
|
| 32 |
-
@property
|
| 33 |
-
def is_espace_admin(self) -> bool:
|
| 34 |
-
return is_espace_admin(self.role_cabinet)
|
| 35 |
-
|
| 36 |
-
@property
|
| 37 |
-
def role(self) -> RoleCabinet:
|
| 38 |
-
return self.role_cabinet
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
# ─────────────────────────────────────────────
|
| 42 |
-
# Dépendance 1 : JWT → CurrentUser
|
| 43 |
-
# ─────────────────────────────────────────────
|
| 44 |
|
| 45 |
async def get_current_user(
|
| 46 |
-
credentials: HTTPAuthorizationCredentials = Depends(
|
| 47 |
) -> CurrentUser:
|
| 48 |
"""
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
dans Supabase (HS256 ou ES256) — c'est Supabase qui valide.
|
| 52 |
"""
|
| 53 |
token = credentials.credentials
|
| 54 |
|
| 55 |
try:
|
| 56 |
-
#
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
)
|
| 64 |
|
| 65 |
-
|
| 66 |
-
raise HTTPException(
|
| 67 |
-
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 68 |
-
detail="Token invalide ou expiré",
|
| 69 |
-
headers={"WWW-Authenticate": "Bearer"},
|
| 70 |
-
)
|
| 71 |
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
.single()
|
| 80 |
-
.execute()
|
| 81 |
-
)
|
| 82 |
-
if not response.data:
|
| 83 |
-
raise HTTPException(
|
| 84 |
-
status_code=status.HTTP_403_FORBIDDEN,
|
| 85 |
-
detail="Profil utilisateur introuvable — contactez un administrateur",
|
| 86 |
)
|
| 87 |
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
|
| 103 |
-
# ─────────────────────────────────────────────
|
| 104 |
-
# Dépendance 2 : superadmin uniquement
|
| 105 |
-
# ─────────────────────────────────────────────
|
| 106 |
|
| 107 |
async def require_superadmin(
|
| 108 |
current_user: CurrentUser = Depends(get_current_user),
|
| 109 |
) -> CurrentUser:
|
| 110 |
-
"""
|
| 111 |
if not current_user.is_superadmin:
|
| 112 |
raise HTTPException(
|
| 113 |
status_code=status.HTTP_403_FORBIDDEN,
|
| 114 |
-
detail="Accès réservé aux superadmins
|
| 115 |
)
|
| 116 |
return current_user
|
| 117 |
|
| 118 |
|
| 119 |
-
# ─────────────────────────────────────────────
|
| 120 |
-
# Dépendance 3 : membre d'un espace
|
| 121 |
-
# ─────────────────────────────────────────────
|
| 122 |
-
|
| 123 |
async def get_espace_user(
|
| 124 |
current_user: CurrentUser = Depends(get_current_user),
|
| 125 |
) -> CurrentUser:
|
| 126 |
-
"""
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
detail="Les superadmins utilisent les routes /api/espaces/*",
|
| 131 |
-
)
|
| 132 |
if not current_user.espace_id:
|
| 133 |
raise HTTPException(
|
| 134 |
-
status_code=
|
| 135 |
-
detail="
|
| 136 |
)
|
| 137 |
return current_user
|
| 138 |
|
| 139 |
|
| 140 |
-
# ─────────────────────────────────────────────
|
| 141 |
-
# Dépendance 4 : admin de l'espace
|
| 142 |
-
# ─────────────────────────────────────────────
|
| 143 |
-
|
| 144 |
async def require_espace_admin(
|
| 145 |
current_user: CurrentUser = Depends(get_espace_user),
|
| 146 |
) -> CurrentUser:
|
| 147 |
-
"""
|
| 148 |
-
|
| 149 |
-
Usage : modifier le role_cabinet des autres membres.
|
| 150 |
-
"""
|
| 151 |
-
if not current_user.is_espace_admin:
|
| 152 |
raise HTTPException(
|
| 153 |
-
status_code=
|
| 154 |
-
detail="
|
| 155 |
)
|
| 156 |
return current_user
|
| 157 |
|
| 158 |
|
| 159 |
-
# ─────────────────────────────────────────────
|
| 160 |
-
# Dépendance 5 : permission métier
|
| 161 |
-
# ─────────────────────────────────────────────
|
| 162 |
-
|
| 163 |
def require_permission(permission: str):
|
| 164 |
-
"""
|
| 165 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
current_user: CurrentUser = Depends(get_espace_user),
|
| 167 |
) -> CurrentUser:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
if not has_permission(current_user.role_cabinet, permission):
|
| 169 |
raise HTTPException(
|
| 170 |
-
status_code=
|
| 171 |
-
detail=f"Permission
|
| 172 |
)
|
|
|
|
| 173 |
return current_user
|
| 174 |
-
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Dedalys Backend — Authentification
|
| 3 |
+
Dépendances FastAPI pour la gestion des utilisateurs et permissions.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
from typing import Optional
|
| 7 |
+
from uuid import UUID
|
| 8 |
+
from dataclasses import dataclass
|
| 9 |
from fastapi import Depends, HTTPException, status
|
| 10 |
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
|
|
|
|
|
|
| 11 |
|
| 12 |
+
from app.core.supabase import supabase, supabase_admin
|
| 13 |
+
from app.core.permissions import RoleCabinet, has_permission, ESPACE_ADMIN_ROLES
|
| 14 |
+
|
| 15 |
+
security = HTTPBearer()
|
| 16 |
|
| 17 |
|
| 18 |
+
@dataclass
|
| 19 |
class CurrentUser:
|
| 20 |
+
"""Représentation de l'utilisateur authentifié."""
|
| 21 |
+
id: str
|
| 22 |
+
email: str
|
| 23 |
+
nom: str
|
| 24 |
+
prenom: str
|
| 25 |
+
espace_id: str
|
| 26 |
+
role_cabinet: RoleCabinet
|
| 27 |
+
is_superadmin: bool = False
|
| 28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
async def get_current_user(
|
| 31 |
+
credentials: HTTPAuthorizationCredentials = Depends(security),
|
| 32 |
) -> CurrentUser:
|
| 33 |
"""
|
| 34 |
+
Extrait et valide l'utilisateur depuis le token JWT.
|
| 35 |
+
Retourne les informations de l'utilisateur connecté.
|
|
|
|
| 36 |
"""
|
| 37 |
token = credentials.credentials
|
| 38 |
|
| 39 |
try:
|
| 40 |
+
# Valider le token via Supabase Auth
|
| 41 |
+
user_response = supabase.auth.get_user(token)
|
| 42 |
+
if not user_response or not user_response.user:
|
| 43 |
+
raise HTTPException(
|
| 44 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 45 |
+
detail="Token invalide ou expiré",
|
| 46 |
+
)
|
|
|
|
| 47 |
|
| 48 |
+
supabase_user = user_response.user
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
+
# Récupérer le profil utilisateur depuis la table utilisateurs
|
| 51 |
+
profile_response = (
|
| 52 |
+
supabase_admin.table("utilisateurs")
|
| 53 |
+
.select("*")
|
| 54 |
+
.eq("id", supabase_user.id)
|
| 55 |
+
.single()
|
| 56 |
+
.execute()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
)
|
| 58 |
|
| 59 |
+
if not profile_response.data:
|
| 60 |
+
raise HTTPException(
|
| 61 |
+
status_code=status.HTTP_404_NOT_FOUND,
|
| 62 |
+
detail="Profil utilisateur introuvable",
|
| 63 |
+
)
|
| 64 |
|
| 65 |
+
profile = profile_response.data
|
| 66 |
+
|
| 67 |
+
return CurrentUser(
|
| 68 |
+
id=profile["id"],
|
| 69 |
+
email=profile["email"],
|
| 70 |
+
nom=profile["nom"],
|
| 71 |
+
prenom=profile["prenom"],
|
| 72 |
+
espace_id=profile["espace_id"],
|
| 73 |
+
role_cabinet=RoleCabinet(profile["role_cabinet"]),
|
| 74 |
+
is_superadmin=profile.get("is_superadmin", False),
|
| 75 |
+
)
|
| 76 |
|
| 77 |
+
except HTTPException:
|
| 78 |
+
raise
|
| 79 |
+
except Exception as e:
|
| 80 |
+
raise HTTPException(
|
| 81 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 82 |
+
detail="Erreur d'authentification",
|
| 83 |
+
)
|
| 84 |
|
|
|
|
|
|
|
|
|
|
| 85 |
|
| 86 |
async def require_superadmin(
|
| 87 |
current_user: CurrentUser = Depends(get_current_user),
|
| 88 |
) -> CurrentUser:
|
| 89 |
+
"""Vérifie que l'utilisateur est superadmin."""
|
| 90 |
if not current_user.is_superadmin:
|
| 91 |
raise HTTPException(
|
| 92 |
status_code=status.HTTP_403_FORBIDDEN,
|
| 93 |
+
detail="Accès réservé aux superadmins",
|
| 94 |
)
|
| 95 |
return current_user
|
| 96 |
|
| 97 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
async def get_espace_user(
|
| 99 |
current_user: CurrentUser = Depends(get_current_user),
|
| 100 |
) -> CurrentUser:
|
| 101 |
+
"""
|
| 102 |
+
Vérifie que l'utilisateur appartient à un espace.
|
| 103 |
+
Alias de get_current_user avec vérification explicite.
|
| 104 |
+
"""
|
|
|
|
|
|
|
| 105 |
if not current_user.espace_id:
|
| 106 |
raise HTTPException(
|
| 107 |
+
status_code=status.HTTP_403_FORBIDDEN,
|
| 108 |
+
detail="Utilisateur non rattaché à un espace",
|
| 109 |
)
|
| 110 |
return current_user
|
| 111 |
|
| 112 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
async def require_espace_admin(
|
| 114 |
current_user: CurrentUser = Depends(get_espace_user),
|
| 115 |
) -> CurrentUser:
|
| 116 |
+
"""Vérifie que l'utilisateur est admin de son espace (associé gérant ou office manager)."""
|
| 117 |
+
if current_user.role_cabinet not in ESPACE_ADMIN_ROLES:
|
|
|
|
|
|
|
|
|
|
| 118 |
raise HTTPException(
|
| 119 |
+
status_code=status.HTTP_403_FORBIDDEN,
|
| 120 |
+
detail="Accès réservé aux administrateurs de l'espace",
|
| 121 |
)
|
| 122 |
return current_user
|
| 123 |
|
| 124 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
def require_permission(permission: str):
|
| 126 |
+
"""
|
| 127 |
+
Factory pour créer une dépendance de vérification de permission.
|
| 128 |
+
|
| 129 |
+
Usage:
|
| 130 |
+
@router.get("/", dependencies=[Depends(require_permission("client:read"))])
|
| 131 |
+
async def list_clients(...):
|
| 132 |
+
...
|
| 133 |
+
|
| 134 |
+
Ou:
|
| 135 |
+
@router.get("/")
|
| 136 |
+
async def list_clients(
|
| 137 |
+
espace_user: CurrentUser = Depends(require_permission("client:read")),
|
| 138 |
+
):
|
| 139 |
+
...
|
| 140 |
+
"""
|
| 141 |
+
async def _check_permission(
|
| 142 |
current_user: CurrentUser = Depends(get_espace_user),
|
| 143 |
) -> CurrentUser:
|
| 144 |
+
# Les superadmins ont toutes les permissions
|
| 145 |
+
if current_user.is_superadmin:
|
| 146 |
+
return current_user
|
| 147 |
+
|
| 148 |
if not has_permission(current_user.role_cabinet, permission):
|
| 149 |
raise HTTPException(
|
| 150 |
+
status_code=status.HTTP_403_FORBIDDEN,
|
| 151 |
+
detail=f"Permission '{permission}' requise",
|
| 152 |
)
|
| 153 |
+
|
| 154 |
return current_user
|
| 155 |
+
|
| 156 |
+
return _check_permission
|
app/core/config.py
CHANGED
|
@@ -1,21 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from pydantic_settings import BaseSettings
|
| 2 |
from dotenv import load_dotenv
|
| 3 |
|
| 4 |
-
# Charge explicitement le fichier .env avant l'initialisation des settings
|
| 5 |
load_dotenv()
|
| 6 |
|
| 7 |
|
| 8 |
class Settings(BaseSettings):
|
|
|
|
|
|
|
|
|
|
| 9 |
SUPABASE_URL: str
|
| 10 |
SUPABASE_ANON_KEY: str
|
| 11 |
SUPABASE_SERVICE_KEY: str
|
| 12 |
-
SUPABASE_JWT_SECRET: str
|
|
|
|
|
|
|
| 13 |
STORAGE_BUCKET: str = "dedalys-fichiers"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
class Config:
|
| 16 |
env_file = ".env"
|
| 17 |
env_file_encoding = "utf-8"
|
| 18 |
extra = "ignore"
|
| 19 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
settings = Settings()
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Dedalys Backend — Configuration
|
| 3 |
+
Gestion centralisée des variables d'environnement.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from typing import List
|
| 7 |
from pydantic_settings import BaseSettings
|
| 8 |
from dotenv import load_dotenv
|
| 9 |
|
|
|
|
| 10 |
load_dotenv()
|
| 11 |
|
| 12 |
|
| 13 |
class Settings(BaseSettings):
|
| 14 |
+
"""Configuration de l'application Dedalys."""
|
| 15 |
+
|
| 16 |
+
# ── Supabase ─────────────────────────────────────────────
|
| 17 |
SUPABASE_URL: str
|
| 18 |
SUPABASE_ANON_KEY: str
|
| 19 |
SUPABASE_SERVICE_KEY: str
|
| 20 |
+
SUPABASE_JWT_SECRET: str # MVP — conservé pour compatibilité, non utilisé directement
|
| 21 |
+
|
| 22 |
+
# ── Storage ──────────────────────────────────────────────
|
| 23 |
STORAGE_BUCKET: str = "dedalys-fichiers"
|
| 24 |
+
STORAGE_SIGNED_URL_EXPIRY: int = 900 # 15 minutes par défaut
|
| 25 |
+
|
| 26 |
+
# ── Email (Resend) ───────────────────────────────────────
|
| 27 |
+
# MVP — à configurer avant activation des rappels
|
| 28 |
+
RESEND_API_KEY: str = ""
|
| 29 |
+
EMAIL_FROM: str = "noreply@dedalys.ci"
|
| 30 |
+
|
| 31 |
+
# ── Application ──────────────────────────────────────────
|
| 32 |
+
APP_ENV: str = "development" # development | staging | production
|
| 33 |
+
ALLOWED_ORIGINS: str = "http://localhost:3000"
|
| 34 |
+
FRONTEND_URL: str = "http://localhost:3000"
|
| 35 |
+
SUPABASE_RESET_PASSWORD_REDIRECT_URL: str = "http://localhost:3000/reset-password"
|
| 36 |
|
| 37 |
class Config:
|
| 38 |
env_file = ".env"
|
| 39 |
env_file_encoding = "utf-8"
|
| 40 |
extra = "ignore"
|
| 41 |
|
| 42 |
+
@property
|
| 43 |
+
def is_production(self) -> bool:
|
| 44 |
+
return self.APP_ENV == "production"
|
| 45 |
+
|
| 46 |
+
@property
|
| 47 |
+
def is_development(self) -> bool:
|
| 48 |
+
return self.APP_ENV == "development"
|
| 49 |
+
|
| 50 |
+
@property
|
| 51 |
+
def cors_origins(self) -> List[str]:
|
| 52 |
+
"""Parse ALLOWED_ORIGINS en liste."""
|
| 53 |
+
return [origin.strip() for origin in self.ALLOWED_ORIGINS.split(",") if origin.strip()]
|
| 54 |
+
|
| 55 |
|
| 56 |
settings = Settings()
|
app/core/permissions.py
CHANGED
|
@@ -1,82 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from enum import Enum
|
| 2 |
-
from typing import Set
|
| 3 |
|
| 4 |
|
| 5 |
class RoleCabinet(str, Enum):
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
|
|
|
| 10 |
|
| 11 |
|
| 12 |
class RoleDossier(str, Enum):
|
| 13 |
-
|
| 14 |
-
|
|
|
|
| 15 |
|
| 16 |
|
| 17 |
-
#
|
| 18 |
-
# Rôles qui ont les droits admin dans l'espace
|
| 19 |
-
# Pas besoin d'un champ role_espace séparé —
|
| 20 |
-
# le statut admin est déduit du role_cabinet.
|
| 21 |
-
# ─────────────────────────────────────────────
|
| 22 |
ESPACE_ADMIN_ROLES: Set[RoleCabinet] = {
|
| 23 |
-
RoleCabinet.
|
| 24 |
-
RoleCabinet.
|
| 25 |
}
|
| 26 |
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
return role in ESPACE_ADMIN_ROLES
|
| 34 |
-
|
| 35 |
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
#
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
"
|
| 42 |
-
|
| 43 |
"audience:read", "audience:write", "audience:delete",
|
|
|
|
| 44 |
"flash_cr:read", "flash_cr:write", "flash_cr:delete",
|
|
|
|
| 45 |
"paiement:read", "paiement:write", "paiement:delete",
|
| 46 |
-
|
| 47 |
-
"
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
| 49 |
},
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
"audience:read", "audience:write",
|
|
|
|
| 54 |
"flash_cr:read", "flash_cr:write",
|
|
|
|
| 55 |
"paiement:read",
|
| 56 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
"utilisateur:read",
|
| 58 |
},
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
"audience:read", "audience:write",
|
|
|
|
| 63 |
"flash_cr:read", "flash_cr:write",
|
|
|
|
| 64 |
"paiement:read",
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
"utilisateur:read",
|
| 67 |
},
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
"audience:read",
|
|
|
|
| 72 |
"flash_cr:read",
|
| 73 |
-
|
| 74 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
"utilisateur:read",
|
| 76 |
-
"equipe_dossier:write",
|
| 77 |
},
|
| 78 |
}
|
| 79 |
|
| 80 |
|
| 81 |
def has_permission(role: RoleCabinet, permission: str) -> bool:
|
| 82 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Dedalys Backend — Permissions
|
| 3 |
+
Définition des rôles et matrice de permissions.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
from enum import Enum
|
| 7 |
+
from typing import Set, Dict
|
| 8 |
|
| 9 |
|
| 10 |
class RoleCabinet(str, Enum):
|
| 11 |
+
"""Rôles au niveau du cabinet (espace)."""
|
| 12 |
+
associe_gerant = "associe_gerant"
|
| 13 |
+
avocat = "avocat"
|
| 14 |
+
juriste = "juriste"
|
| 15 |
+
office_manager = "office_manager"
|
| 16 |
|
| 17 |
|
| 18 |
class RoleDossier(str, Enum):
|
| 19 |
+
"""Rôles au niveau d'un dossier spécifique."""
|
| 20 |
+
responsable = "responsable"
|
| 21 |
+
collaborateur = "collaborateur"
|
| 22 |
|
| 23 |
|
| 24 |
+
# Rôles considérés comme administrateurs de l'espace
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
ESPACE_ADMIN_ROLES: Set[RoleCabinet] = {
|
| 26 |
+
RoleCabinet.associe_gerant,
|
| 27 |
+
RoleCabinet.office_manager,
|
| 28 |
}
|
| 29 |
|
| 30 |
|
| 31 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 32 |
+
# MATRICE DE PERMISSIONS PAR RÔLE
|
| 33 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 34 |
+
# R = Read, W = Write (create/update), A = Archive (soft delete)
|
| 35 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
|
|
|
|
|
|
| 36 |
|
| 37 |
+
PERMISSIONS_MATRIX: Dict[RoleCabinet, Set[str]] = {
|
| 38 |
+
RoleCabinet.associe_gerant: {
|
| 39 |
+
# Clients
|
| 40 |
+
"client:read", "client:write", "client:delete",
|
| 41 |
+
# Dossiers
|
| 42 |
+
"dossier:read", "dossier:write", "dossier:delete",
|
| 43 |
+
# Audiences
|
| 44 |
"audience:read", "audience:write", "audience:delete",
|
| 45 |
+
# Flash CR
|
| 46 |
"flash_cr:read", "flash_cr:write", "flash_cr:delete",
|
| 47 |
+
# Paiements
|
| 48 |
"paiement:read", "paiement:write", "paiement:delete",
|
| 49 |
+
# Fichiers
|
| 50 |
+
"fichier:read", "fichier:write", "fichier:delete",
|
| 51 |
+
# Équipe dossier
|
| 52 |
+
"equipe_dossier:read", "equipe_dossier:write",
|
| 53 |
+
# Utilisateurs
|
| 54 |
+
"utilisateur:read", "utilisateur:write",
|
| 55 |
},
|
| 56 |
+
|
| 57 |
+
RoleCabinet.avocat: {
|
| 58 |
+
# Clients
|
| 59 |
+
"client:read", "client:write",
|
| 60 |
+
# Dossiers — avocats peuvent créer et modifier
|
| 61 |
+
"dossier:read", "dossier:write",
|
| 62 |
+
# Audiences
|
| 63 |
"audience:read", "audience:write",
|
| 64 |
+
# Flash CR
|
| 65 |
"flash_cr:read", "flash_cr:write",
|
| 66 |
+
# Paiements — lecture seule
|
| 67 |
"paiement:read",
|
| 68 |
+
# Fichiers
|
| 69 |
+
"fichier:read", "fichier:write",
|
| 70 |
+
# Équipe dossier — lecture seule
|
| 71 |
+
"equipe_dossier:read",
|
| 72 |
+
# Utilisateurs — lecture seule
|
| 73 |
"utilisateur:read",
|
| 74 |
},
|
| 75 |
+
|
| 76 |
+
RoleCabinet.juriste: {
|
| 77 |
+
# Clients
|
| 78 |
+
"client:read", "client:write",
|
| 79 |
+
# Dossiers — juristes peuvent créer et modifier
|
| 80 |
+
"dossier:read", "dossier:write",
|
| 81 |
+
# Audiences
|
| 82 |
"audience:read", "audience:write",
|
| 83 |
+
# Flash CR
|
| 84 |
"flash_cr:read", "flash_cr:write",
|
| 85 |
+
# Paiements — lecture seule
|
| 86 |
"paiement:read",
|
| 87 |
+
# Fichiers
|
| 88 |
+
"fichier:read", "fichier:write",
|
| 89 |
+
# Équipe dossier — lecture seule
|
| 90 |
+
"equipe_dossier:read",
|
| 91 |
+
# Utilisateurs — lecture seule
|
| 92 |
"utilisateur:read",
|
| 93 |
},
|
| 94 |
+
|
| 95 |
+
RoleCabinet.office_manager: {
|
| 96 |
+
# Clients — accès complet
|
| 97 |
+
"client:read", "client:write", "client:delete",
|
| 98 |
+
# Dossiers — lecture + écriture
|
| 99 |
+
"dossier:read", "dossier:write",
|
| 100 |
+
# Audiences — lecture seule
|
| 101 |
"audience:read",
|
| 102 |
+
# Flash CR — lecture seule
|
| 103 |
"flash_cr:read",
|
| 104 |
+
# Paiements — accès complet (gestion financière)
|
| 105 |
+
"paiement:read", "paiement:write", "paiement:delete",
|
| 106 |
+
# Fichiers
|
| 107 |
+
"fichier:read", "fichier:write",
|
| 108 |
+
# Équipe dossier — lecture seule
|
| 109 |
+
"equipe_dossier:read",
|
| 110 |
+
# Utilisateurs — lecture seule
|
| 111 |
"utilisateur:read",
|
|
|
|
| 112 |
},
|
| 113 |
}
|
| 114 |
|
| 115 |
|
| 116 |
def has_permission(role: RoleCabinet, permission: str) -> bool:
|
| 117 |
+
"""Vérifie si un rôle possède une permission donnée."""
|
| 118 |
+
return permission in PERMISSIONS_MATRIX.get(role, set())
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def get_permissions(role: RoleCabinet) -> Set[str]:
|
| 122 |
+
"""Retourne toutes les permissions d'un rôle."""
|
| 123 |
+
return PERMISSIONS_MATRIX.get(role, set())
|
app/core/supabase.py
CHANGED
|
@@ -1,23 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from supabase import create_client, Client
|
| 2 |
from app.core.config import settings
|
| 3 |
|
| 4 |
-
#
|
| 5 |
-
# Client ANON — authentification utilisateur
|
| 6 |
-
# ─────────────────────────────────────────────
|
| 7 |
-
# Clé publique (anon key) — respecte les politiques RLS.
|
| 8 |
-
# Utilisé uniquement pour : sign_in, sign_out, refresh_session.
|
| 9 |
supabase: Client = create_client(
|
| 10 |
settings.SUPABASE_URL,
|
| 11 |
-
settings.SUPABASE_ANON_KEY
|
| 12 |
)
|
| 13 |
|
| 14 |
-
#
|
| 15 |
-
# Client ADMIN — opérations serveur
|
| 16 |
-
# ─────────────────────────────────────────────
|
| 17 |
-
# Clé service_role — contourne RLS, accès total.
|
| 18 |
-
# Utilisé pour tout le CRUD, Storage et admin Auth.
|
| 19 |
-
# ⚠️ Ne jamais exposer côté client.
|
| 20 |
supabase_admin: Client = create_client(
|
| 21 |
settings.SUPABASE_URL,
|
| 22 |
-
settings.SUPABASE_SERVICE_KEY
|
| 23 |
)
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Dedalys Backend — Clients Supabase
|
| 3 |
+
Initialisation des clients pour l'API et l'admin.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
from supabase import create_client, Client
|
| 7 |
from app.core.config import settings
|
| 8 |
|
| 9 |
+
# Client avec anon key — pour les opérations authentifiées utilisateur
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
supabase: Client = create_client(
|
| 11 |
settings.SUPABASE_URL,
|
| 12 |
+
settings.SUPABASE_ANON_KEY
|
| 13 |
)
|
| 14 |
|
| 15 |
+
# Client avec service_role key — pour les opérations admin (bypass RLS)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
supabase_admin: Client = create_client(
|
| 17 |
settings.SUPABASE_URL,
|
| 18 |
+
settings.SUPABASE_SERVICE_KEY
|
| 19 |
)
|
app/main.py
CHANGED
|
@@ -1,42 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from fastapi import FastAPI
|
| 2 |
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
|
| 4 |
-
from app.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
app = FastAPI(
|
| 7 |
title="Dedalys API",
|
| 8 |
-
description=""
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
- 🔴 **Superadmin** : gestion des espaces et utilisateurs (nous, les concepteurs)
|
| 14 |
-
- 🟠 **Admin espace** : gestion des permissions des membres de son espace
|
| 15 |
-
- 🟢 **Membre** : accès aux données métier selon son rôle cabinet
|
| 16 |
-
""",
|
| 17 |
-
version="2.0.0",
|
| 18 |
-
docs_url="/api/docs",
|
| 19 |
-
redoc_url="/api/redoc",
|
| 20 |
-
openapi_url="/api/openapi.json",
|
| 21 |
)
|
| 22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
app.add_middleware(
|
| 24 |
CORSMiddleware,
|
| 25 |
-
allow_origins=
|
| 26 |
allow_credentials=True,
|
| 27 |
allow_methods=["*"],
|
| 28 |
-
allow_headers=["*"],
|
| 29 |
)
|
| 30 |
|
| 31 |
-
api_prefix = "/api"
|
| 32 |
|
| 33 |
-
#
|
| 34 |
-
|
|
|
|
| 35 |
|
| 36 |
-
|
| 37 |
-
app.include_router(espaces.router, prefix=api_prefix)
|
| 38 |
|
| 39 |
-
|
|
|
|
| 40 |
app.include_router(utilisateurs.router, prefix=api_prefix)
|
| 41 |
app.include_router(clients.router, prefix=api_prefix)
|
| 42 |
app.include_router(dossiers.router, prefix=api_prefix)
|
|
@@ -44,8 +62,29 @@ app.include_router(audiences.router, prefix=api_prefix)
|
|
| 44 |
app.include_router(flash_cr.router, prefix=api_prefix)
|
| 45 |
app.include_router(paiements.router, prefix=api_prefix)
|
| 46 |
app.include_router(fichiers.router, prefix=api_prefix)
|
|
|
|
| 47 |
|
| 48 |
|
| 49 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
async def health_check():
|
| 51 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Dedalys Backend — Point d'entrée FastAPI
|
| 3 |
+
Solution de gestion pour cabinets et directions juridiques.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
from fastapi import FastAPI
|
| 7 |
from fastapi.middleware.cors import CORSMiddleware
|
| 8 |
|
| 9 |
+
from app.core.config import settings
|
| 10 |
+
from app.routers import (
|
| 11 |
+
auth,
|
| 12 |
+
espaces,
|
| 13 |
+
utilisateurs,
|
| 14 |
+
clients,
|
| 15 |
+
dossiers,
|
| 16 |
+
audiences,
|
| 17 |
+
flash_cr,
|
| 18 |
+
paiements,
|
| 19 |
+
fichiers,
|
| 20 |
+
audit,
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 25 |
+
# APPLICATION
|
| 26 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 27 |
|
| 28 |
app = FastAPI(
|
| 29 |
title="Dedalys API",
|
| 30 |
+
description="API pour la gestion des cabinets d'avocats et directions juridiques en Afrique francophone.",
|
| 31 |
+
version="1.0.0",
|
| 32 |
+
docs_url="/api/v1/docs" if settings.is_development else None,
|
| 33 |
+
redoc_url="/api/v1/redoc" if settings.is_development else None,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
)
|
| 35 |
|
| 36 |
+
|
| 37 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 38 |
+
# MIDDLEWARE CORS
|
| 39 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 40 |
+
|
| 41 |
app.add_middleware(
|
| 42 |
CORSMiddleware,
|
| 43 |
+
allow_origins=settings.cors_origins,
|
| 44 |
allow_credentials=True,
|
| 45 |
allow_methods=["*"],
|
| 46 |
+
allow_headers=["*", "Authorization"],
|
| 47 |
)
|
| 48 |
|
|
|
|
| 49 |
|
| 50 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 51 |
+
# ROUTERS — TOUS SOUS /api/v1
|
| 52 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 53 |
|
| 54 |
+
api_prefix = "/api/v1"
|
|
|
|
| 55 |
|
| 56 |
+
app.include_router(auth.router, prefix=api_prefix)
|
| 57 |
+
app.include_router(espaces.router, prefix=api_prefix)
|
| 58 |
app.include_router(utilisateurs.router, prefix=api_prefix)
|
| 59 |
app.include_router(clients.router, prefix=api_prefix)
|
| 60 |
app.include_router(dossiers.router, prefix=api_prefix)
|
|
|
|
| 62 |
app.include_router(flash_cr.router, prefix=api_prefix)
|
| 63 |
app.include_router(paiements.router, prefix=api_prefix)
|
| 64 |
app.include_router(fichiers.router, prefix=api_prefix)
|
| 65 |
+
app.include_router(audit.router, prefix=api_prefix)
|
| 66 |
|
| 67 |
|
| 68 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 69 |
+
# HEALTH CHECK
|
| 70 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 71 |
+
|
| 72 |
+
@app.get("/api/v1/health", tags=["Système"])
|
| 73 |
async def health_check():
|
| 74 |
+
"""Endpoint de vérification de l'état de l'API."""
|
| 75 |
+
return {
|
| 76 |
+
"status": "ok",
|
| 77 |
+
"service": "Dedalys API",
|
| 78 |
+
"version": "1.0.0",
|
| 79 |
+
"environment": settings.APP_ENV,
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
@app.get("/", tags=["Système"])
|
| 84 |
+
async def root():
|
| 85 |
+
"""Redirection vers la documentation."""
|
| 86 |
+
return {
|
| 87 |
+
"message": "Bienvenue sur l'API Dedalys",
|
| 88 |
+
"documentation": "/api/v1/docs",
|
| 89 |
+
"health": "/api/v1/health",
|
| 90 |
+
}
|
app/models/__pycache__/schemas.cpython-313.pyc
CHANGED
|
Binary files a/app/models/__pycache__/schemas.cpython-313.pyc and b/app/models/__pycache__/schemas.cpython-313.pyc differ
|
|
|
app/models/schemas.py
CHANGED
|
@@ -1,51 +1,105 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
from datetime import date, time, datetime
|
| 3 |
-
from typing import Optional, List
|
| 4 |
from uuid import UUID
|
| 5 |
from pydantic import BaseModel, EmailStr, Field
|
|
|
|
| 6 |
from app.core.permissions import RoleCabinet, RoleDossier
|
| 7 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
-
|
|
|
|
| 10 |
# UTILISATEUR
|
| 11 |
-
#
|
| 12 |
|
| 13 |
class UtilisateurBase(BaseModel):
|
|
|
|
| 14 |
email: EmailStr
|
| 15 |
nom: str = Field(..., min_length=1, max_length=100)
|
| 16 |
prenom: str = Field(..., min_length=1, max_length=100)
|
| 17 |
-
role_cabinet: RoleCabinet
|
| 18 |
|
| 19 |
|
| 20 |
class UtilisateurCreate(UtilisateurBase):
|
| 21 |
-
"""
|
| 22 |
-
Utilisé par les superadmins pour créer un utilisateur dans un espace.
|
| 23 |
-
Le statut admin est automatiquement déduit du role_cabinet :
|
| 24 |
-
associe_gerant / office_manager → admin
|
| 25 |
-
avocat / juriste → membre simple
|
| 26 |
-
"""
|
| 27 |
password: str = Field(..., min_length=8)
|
| 28 |
-
|
|
|
|
| 29 |
|
| 30 |
|
| 31 |
class UtilisateurUpdate(BaseModel):
|
| 32 |
-
"""Mise à jour
|
| 33 |
nom: Optional[str] = Field(None, min_length=1, max_length=100)
|
| 34 |
prenom: Optional[str] = Field(None, min_length=1, max_length=100)
|
| 35 |
|
| 36 |
|
| 37 |
class UtilisateurUpdateRoleCabinet(BaseModel):
|
| 38 |
-
"""
|
| 39 |
-
Réservé aux admins de l'espace (associe_gerant, office_manager).
|
| 40 |
-
Change le role_cabinet d'un membre — ce qui peut aussi changer son statut admin.
|
| 41 |
-
Ex : passer un avocat en office_manager lui donne les droits admin.
|
| 42 |
-
"""
|
| 43 |
role_cabinet: RoleCabinet
|
| 44 |
|
| 45 |
|
| 46 |
class UtilisateurResponse(UtilisateurBase):
|
|
|
|
| 47 |
id: UUID
|
| 48 |
espace_id: Optional[UUID] = None
|
|
|
|
| 49 |
is_superadmin: bool = False
|
| 50 |
created_at: datetime
|
| 51 |
|
|
@@ -53,41 +107,26 @@ class UtilisateurResponse(UtilisateurBase):
|
|
| 53 |
from_attributes = True
|
| 54 |
|
| 55 |
|
| 56 |
-
#
|
| 57 |
-
#
|
| 58 |
-
#
|
| 59 |
-
|
| 60 |
-
class LoginRequest(BaseModel):
|
| 61 |
-
email: EmailStr
|
| 62 |
-
password: str
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
class TokenResponse(BaseModel):
|
| 66 |
-
access_token: str
|
| 67 |
-
refresh_token: str
|
| 68 |
-
token_type: str = "bearer"
|
| 69 |
-
user: UtilisateurResponse
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
class RefreshRequest(BaseModel):
|
| 73 |
-
refresh_token: str
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
# ─────────────────────────────────────────────
|
| 77 |
-
# ESPACE
|
| 78 |
-
# ─────────────────────────────────────────────
|
| 79 |
|
| 80 |
class EspaceCreate(BaseModel):
|
|
|
|
| 81 |
nom: str = Field(..., min_length=1, max_length=255)
|
| 82 |
|
| 83 |
|
| 84 |
class EspaceUpdate(BaseModel):
|
| 85 |
-
|
|
|
|
| 86 |
|
| 87 |
|
| 88 |
class EspaceResponse(BaseModel):
|
|
|
|
| 89 |
id: UUID
|
| 90 |
nom: str
|
|
|
|
|
|
|
| 91 |
created_at: datetime
|
| 92 |
|
| 93 |
class Config:
|
|
@@ -95,28 +134,35 @@ class EspaceResponse(BaseModel):
|
|
| 95 |
|
| 96 |
|
| 97 |
class EspaceDetailResponse(EspaceResponse):
|
| 98 |
-
|
|
|
|
| 99 |
|
| 100 |
|
| 101 |
-
#
|
| 102 |
# CLIENT
|
| 103 |
-
#
|
| 104 |
|
| 105 |
class ClientBase(BaseModel):
|
|
|
|
| 106 |
raison_sociale: str = Field(..., min_length=1, max_length=255)
|
| 107 |
email_principal: EmailStr
|
| 108 |
telephone: str = Field(..., min_length=8, max_length=20)
|
| 109 |
-
statut: str = Field(..., pattern="^(PP|PM)$"
|
| 110 |
-
|
| 111 |
-
|
|
|
|
|
|
|
|
|
|
| 112 |
revenu_attendu_total: Optional[float] = Field(None, ge=0)
|
| 113 |
|
| 114 |
|
| 115 |
class ClientCreate(ClientBase):
|
|
|
|
| 116 |
pass
|
| 117 |
|
| 118 |
|
| 119 |
class ClientUpdate(BaseModel):
|
|
|
|
| 120 |
raison_sociale: Optional[str] = Field(None, min_length=1, max_length=255)
|
| 121 |
email_principal: Optional[EmailStr] = None
|
| 122 |
telephone: Optional[str] = Field(None, min_length=8, max_length=20)
|
|
@@ -127,20 +173,23 @@ class ClientUpdate(BaseModel):
|
|
| 127 |
|
| 128 |
|
| 129 |
class ClientResponse(ClientBase):
|
|
|
|
| 130 |
id: UUID
|
| 131 |
espace_id: UUID
|
|
|
|
|
|
|
| 132 |
created_at: datetime
|
| 133 |
|
| 134 |
class Config:
|
| 135 |
from_attributes = True
|
| 136 |
|
| 137 |
|
| 138 |
-
#
|
| 139 |
# POINT DE CONTACT
|
| 140 |
-
#
|
| 141 |
|
| 142 |
class PointDeContactBase(BaseModel):
|
| 143 |
-
|
| 144 |
nom_complet: str = Field(..., min_length=1, max_length=255)
|
| 145 |
telephone: str = Field(..., min_length=8, max_length=20)
|
| 146 |
email: EmailStr
|
|
@@ -148,10 +197,12 @@ class PointDeContactBase(BaseModel):
|
|
| 148 |
|
| 149 |
|
| 150 |
class PointDeContactCreate(PointDeContactBase):
|
|
|
|
| 151 |
pass
|
| 152 |
|
| 153 |
|
| 154 |
class PointDeContactUpdate(BaseModel):
|
|
|
|
| 155 |
nom_complet: Optional[str] = Field(None, min_length=1, max_length=255)
|
| 156 |
telephone: Optional[str] = Field(None, min_length=8, max_length=20)
|
| 157 |
email: Optional[EmailStr] = None
|
|
@@ -159,36 +210,53 @@ class PointDeContactUpdate(BaseModel):
|
|
| 159 |
|
| 160 |
|
| 161 |
class PointDeContactResponse(PointDeContactBase):
|
|
|
|
| 162 |
id: UUID
|
| 163 |
espace_id: UUID
|
|
|
|
|
|
|
|
|
|
| 164 |
created_at: datetime
|
| 165 |
|
| 166 |
class Config:
|
| 167 |
from_attributes = True
|
| 168 |
|
| 169 |
|
| 170 |
-
#
|
| 171 |
# DOSSIER
|
| 172 |
-
#
|
| 173 |
|
| 174 |
class DossierBase(BaseModel):
|
|
|
|
| 175 |
client_id: UUID
|
| 176 |
titre: Optional[str] = Field(None, max_length=255)
|
| 177 |
-
type: str = Field(
|
| 178 |
-
|
|
|
|
|
|
|
|
|
|
| 179 |
description: str = Field(..., min_length=1)
|
| 180 |
statut: str = Field(
|
| 181 |
-
default="ouvert",
|
|
|
|
|
|
|
| 182 |
partie_adverse: Optional[str] = Field(None, max_length=255)
|
| 183 |
-
preference_facturation: str = Field(
|
| 184 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
|
| 186 |
|
| 187 |
class DossierCreate(DossierBase):
|
|
|
|
| 188 |
pass
|
| 189 |
|
| 190 |
|
| 191 |
class DossierUpdate(BaseModel):
|
|
|
|
| 192 |
titre: Optional[str] = Field(None, max_length=255)
|
| 193 |
type: Optional[str] = Field(
|
| 194 |
None, pattern="^(pre_contentieux|contentieux|conseil|transactionnel)$")
|
|
@@ -202,120 +270,167 @@ class DossierUpdate(BaseModel):
|
|
| 202 |
|
| 203 |
|
| 204 |
class DossierResponse(DossierBase):
|
|
|
|
| 205 |
id: UUID
|
| 206 |
espace_id: UUID
|
| 207 |
reference: str
|
|
|
|
|
|
|
| 208 |
created_at: datetime
|
| 209 |
|
| 210 |
class Config:
|
| 211 |
from_attributes = True
|
| 212 |
|
| 213 |
|
| 214 |
-
#
|
| 215 |
-
#
|
| 216 |
-
#
|
| 217 |
|
| 218 |
class EquipeDossierCreate(BaseModel):
|
|
|
|
| 219 |
utilisateur_id: UUID
|
| 220 |
role: RoleDossier
|
| 221 |
|
| 222 |
|
| 223 |
class EquipeDossierUpdate(BaseModel):
|
|
|
|
| 224 |
role: RoleDossier
|
| 225 |
|
| 226 |
|
| 227 |
class EquipeDossierResponse(BaseModel):
|
|
|
|
| 228 |
dossier_id: UUID
|
| 229 |
utilisateur_id: UUID
|
| 230 |
-
role:
|
|
|
|
| 231 |
|
| 232 |
class Config:
|
| 233 |
from_attributes = True
|
| 234 |
|
| 235 |
|
| 236 |
-
#
|
| 237 |
# AUDIENCE
|
| 238 |
-
#
|
| 239 |
|
| 240 |
class AudienceBase(BaseModel):
|
|
|
|
| 241 |
dossier_id: UUID
|
| 242 |
avocat_assigne_id: UUID
|
| 243 |
date: date
|
| 244 |
heure: time
|
| 245 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 246 |
notes: Optional[str] = None
|
| 247 |
|
| 248 |
|
| 249 |
class AudienceCreate(AudienceBase):
|
|
|
|
| 250 |
pass
|
| 251 |
|
| 252 |
|
| 253 |
class AudienceUpdate(BaseModel):
|
|
|
|
| 254 |
avocat_assigne_id: Optional[UUID] = None
|
| 255 |
date: Optional[date] = None
|
| 256 |
heure: Optional[time] = None
|
| 257 |
-
|
|
|
|
| 258 |
notes: Optional[str] = None
|
| 259 |
|
| 260 |
|
| 261 |
class AudienceResponse(AudienceBase):
|
|
|
|
| 262 |
id: UUID
|
| 263 |
espace_id: UUID
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
created_at: datetime
|
| 265 |
|
| 266 |
class Config:
|
| 267 |
from_attributes = True
|
| 268 |
|
| 269 |
|
| 270 |
-
#
|
| 271 |
# FLASH CR
|
| 272 |
-
#
|
| 273 |
|
| 274 |
class FlashCRBase(BaseModel):
|
|
|
|
| 275 |
audience_id: UUID
|
| 276 |
-
type_decision: str = Field(
|
| 277 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 278 |
notes_rapides: str = Field(..., max_length=500)
|
|
|
|
|
|
|
| 279 |
|
| 280 |
|
| 281 |
class FlashCRCreate(FlashCRBase):
|
|
|
|
| 282 |
pass
|
| 283 |
|
| 284 |
|
| 285 |
class FlashCRUpdate(BaseModel):
|
|
|
|
| 286 |
type_decision: Optional[str] = Field(
|
| 287 |
-
None, pattern="^(decision_rendue|renvoi|autre)$")
|
| 288 |
prochaine_date: Optional[date] = None
|
| 289 |
notes_rapides: Optional[str] = Field(None, max_length=500)
|
| 290 |
|
| 291 |
|
| 292 |
class FlashCRResponse(FlashCRBase):
|
|
|
|
| 293 |
id: UUID
|
| 294 |
espace_id: UUID
|
|
|
|
|
|
|
|
|
|
|
|
|
| 295 |
created_at: datetime
|
| 296 |
|
| 297 |
class Config:
|
| 298 |
from_attributes = True
|
| 299 |
|
| 300 |
|
| 301 |
-
#
|
| 302 |
# PAIEMENT
|
| 303 |
-
#
|
| 304 |
|
| 305 |
class PaiementBase(BaseModel):
|
|
|
|
| 306 |
client_id: UUID
|
| 307 |
dossier_id: UUID
|
| 308 |
-
montant: float = Field(..., gt=0)
|
| 309 |
date_reception: date
|
| 310 |
-
type: str = Field(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 311 |
description: Optional[str] = Field(None, max_length=500)
|
| 312 |
|
| 313 |
|
| 314 |
class PaiementCreate(PaiementBase):
|
|
|
|
| 315 |
pass
|
| 316 |
|
| 317 |
|
| 318 |
class PaiementUpdate(BaseModel):
|
|
|
|
| 319 |
montant: Optional[float] = Field(None, gt=0)
|
| 320 |
date_reception: Optional[date] = None
|
| 321 |
type: Optional[str] = Field(None, pattern="^(honoraires|frais)$")
|
|
@@ -323,19 +438,23 @@ class PaiementUpdate(BaseModel):
|
|
| 323 |
|
| 324 |
|
| 325 |
class PaiementResponse(PaiementBase):
|
|
|
|
| 326 |
id: UUID
|
| 327 |
espace_id: UUID
|
|
|
|
|
|
|
| 328 |
created_at: datetime
|
| 329 |
|
| 330 |
class Config:
|
| 331 |
from_attributes = True
|
| 332 |
|
| 333 |
|
| 334 |
-
#
|
| 335 |
# FICHIER
|
| 336 |
-
#
|
| 337 |
|
| 338 |
class FichierResponse(BaseModel):
|
|
|
|
| 339 |
id: UUID
|
| 340 |
espace_id: UUID
|
| 341 |
dossier_id: UUID
|
|
@@ -343,16 +462,60 @@ class FichierResponse(BaseModel):
|
|
| 343 |
taille: int
|
| 344 |
type_fichier: str
|
| 345 |
chemin_stockage: str
|
| 346 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 347 |
created_at: datetime
|
| 348 |
|
| 349 |
class Config:
|
| 350 |
from_attributes = True
|
| 351 |
|
| 352 |
|
| 353 |
-
#
|
| 354 |
-
#
|
| 355 |
-
#
|
| 356 |
|
| 357 |
-
class
|
| 358 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Dedalys Backend — Schémas Pydantic
|
| 3 |
+
Validation des données entrantes et sortantes de l'API.
|
| 4 |
+
Version conforme à l'audit backend v2.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
from datetime import date, time, datetime
|
| 8 |
+
from typing import Optional, List, Generic, TypeVar, Any
|
| 9 |
from uuid import UUID
|
| 10 |
from pydantic import BaseModel, EmailStr, Field
|
| 11 |
+
|
| 12 |
from app.core.permissions import RoleCabinet, RoleDossier
|
| 13 |
|
| 14 |
+
T = TypeVar("T")
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 18 |
+
# RÉPONSES GÉNÉRIQUES
|
| 19 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 20 |
+
|
| 21 |
+
class MessageResponse(BaseModel):
|
| 22 |
+
"""Réponse simple avec message."""
|
| 23 |
+
message: str
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class PaginatedResponse(BaseModel, Generic[T]):
|
| 27 |
+
"""Réponse paginée standardisée pour tous les endpoints de liste."""
|
| 28 |
+
data: List[T]
|
| 29 |
+
total: int
|
| 30 |
+
page: int
|
| 31 |
+
limit: int
|
| 32 |
+
pages: int
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 36 |
+
# AUTHENTIFICATION
|
| 37 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 38 |
+
|
| 39 |
+
class LoginRequest(BaseModel):
|
| 40 |
+
"""Requête de connexion."""
|
| 41 |
+
email: EmailStr
|
| 42 |
+
password: str = Field(..., min_length=8)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class TokenResponse(BaseModel):
|
| 46 |
+
"""Réponse avec tokens JWT."""
|
| 47 |
+
access_token: str
|
| 48 |
+
refresh_token: str
|
| 49 |
+
token_type: str = "bearer"
|
| 50 |
+
user: dict
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class RefreshRequest(BaseModel):
|
| 54 |
+
"""Requête de renouvellement de token."""
|
| 55 |
+
refresh_token: str
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class ForgotPasswordRequest(BaseModel):
|
| 59 |
+
"""Requête de réinitialisation de mot de passe."""
|
| 60 |
+
email: EmailStr
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class ResetPasswordRequest(BaseModel):
|
| 64 |
+
"""Requête de nouveau mot de passe."""
|
| 65 |
+
token: str
|
| 66 |
+
new_password: str = Field(..., min_length=8)
|
| 67 |
|
| 68 |
+
|
| 69 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 70 |
# UTILISATEUR
|
| 71 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 72 |
|
| 73 |
class UtilisateurBase(BaseModel):
|
| 74 |
+
"""Champs communs utilisateur."""
|
| 75 |
email: EmailStr
|
| 76 |
nom: str = Field(..., min_length=1, max_length=100)
|
| 77 |
prenom: str = Field(..., min_length=1, max_length=100)
|
|
|
|
| 78 |
|
| 79 |
|
| 80 |
class UtilisateurCreate(UtilisateurBase):
|
| 81 |
+
"""Création d'un utilisateur (superadmin only)."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
password: str = Field(..., min_length=8)
|
| 83 |
+
role_cabinet: RoleCabinet
|
| 84 |
+
espace_id: Optional[UUID] = None
|
| 85 |
|
| 86 |
|
| 87 |
class UtilisateurUpdate(BaseModel):
|
| 88 |
+
"""Mise à jour d'un utilisateur."""
|
| 89 |
nom: Optional[str] = Field(None, min_length=1, max_length=100)
|
| 90 |
prenom: Optional[str] = Field(None, min_length=1, max_length=100)
|
| 91 |
|
| 92 |
|
| 93 |
class UtilisateurUpdateRoleCabinet(BaseModel):
|
| 94 |
+
"""Mise à jour du rôle cabinet (admin only)."""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
role_cabinet: RoleCabinet
|
| 96 |
|
| 97 |
|
| 98 |
class UtilisateurResponse(UtilisateurBase):
|
| 99 |
+
"""Réponse utilisateur."""
|
| 100 |
id: UUID
|
| 101 |
espace_id: Optional[UUID] = None
|
| 102 |
+
role_cabinet: RoleCabinet
|
| 103 |
is_superadmin: bool = False
|
| 104 |
created_at: datetime
|
| 105 |
|
|
|
|
| 107 |
from_attributes = True
|
| 108 |
|
| 109 |
|
| 110 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 111 |
+
# ESPACE (CABINET)
|
| 112 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
class EspaceCreate(BaseModel):
|
| 115 |
+
"""Création d'un espace (superadmin only)."""
|
| 116 |
nom: str = Field(..., min_length=1, max_length=255)
|
| 117 |
|
| 118 |
|
| 119 |
class EspaceUpdate(BaseModel):
|
| 120 |
+
"""Mise à jour d'un espace."""
|
| 121 |
+
nom: Optional[str] = Field(None, min_length=1, max_length=255)
|
| 122 |
|
| 123 |
|
| 124 |
class EspaceResponse(BaseModel):
|
| 125 |
+
"""Réponse espace."""
|
| 126 |
id: UUID
|
| 127 |
nom: str
|
| 128 |
+
is_archived: bool = False
|
| 129 |
+
archived_at: Optional[datetime] = None
|
| 130 |
created_at: datetime
|
| 131 |
|
| 132 |
class Config:
|
|
|
|
| 134 |
|
| 135 |
|
| 136 |
class EspaceDetailResponse(EspaceResponse):
|
| 137 |
+
"""Réponse espace avec utilisateurs."""
|
| 138 |
+
utilisateurs: List[UtilisateurResponse] = []
|
| 139 |
|
| 140 |
|
| 141 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 142 |
# CLIENT
|
| 143 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 144 |
|
| 145 |
class ClientBase(BaseModel):
|
| 146 |
+
"""Champs communs client."""
|
| 147 |
raison_sociale: str = Field(..., min_length=1, max_length=255)
|
| 148 |
email_principal: EmailStr
|
| 149 |
telephone: str = Field(..., min_length=8, max_length=20)
|
| 150 |
+
statut: str = Field(..., pattern="^(PP|PM)$",
|
| 151 |
+
description="PP = Personne Physique, PM = Personne Morale")
|
| 152 |
+
forme_juridique: Optional[str] = Field(
|
| 153 |
+
None, max_length=100, description="Obligatoire si PM")
|
| 154 |
+
representant_legal: Optional[str] = Field(
|
| 155 |
+
None, max_length=255, description="Obligatoire si PM")
|
| 156 |
revenu_attendu_total: Optional[float] = Field(None, ge=0)
|
| 157 |
|
| 158 |
|
| 159 |
class ClientCreate(ClientBase):
|
| 160 |
+
"""Création d'un client."""
|
| 161 |
pass
|
| 162 |
|
| 163 |
|
| 164 |
class ClientUpdate(BaseModel):
|
| 165 |
+
"""Mise à jour d'un client."""
|
| 166 |
raison_sociale: Optional[str] = Field(None, min_length=1, max_length=255)
|
| 167 |
email_principal: Optional[EmailStr] = None
|
| 168 |
telephone: Optional[str] = Field(None, min_length=8, max_length=20)
|
|
|
|
| 173 |
|
| 174 |
|
| 175 |
class ClientResponse(ClientBase):
|
| 176 |
+
"""Réponse client."""
|
| 177 |
id: UUID
|
| 178 |
espace_id: UUID
|
| 179 |
+
is_archived: bool = False
|
| 180 |
+
archived_at: Optional[datetime] = None
|
| 181 |
created_at: datetime
|
| 182 |
|
| 183 |
class Config:
|
| 184 |
from_attributes = True
|
| 185 |
|
| 186 |
|
| 187 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 188 |
# POINT DE CONTACT
|
| 189 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 190 |
|
| 191 |
class PointDeContactBase(BaseModel):
|
| 192 |
+
"""Champs communs point de contact."""
|
| 193 |
nom_complet: str = Field(..., min_length=1, max_length=255)
|
| 194 |
telephone: str = Field(..., min_length=8, max_length=20)
|
| 195 |
email: EmailStr
|
|
|
|
| 197 |
|
| 198 |
|
| 199 |
class PointDeContactCreate(PointDeContactBase):
|
| 200 |
+
"""Création d'un point de contact."""
|
| 201 |
pass
|
| 202 |
|
| 203 |
|
| 204 |
class PointDeContactUpdate(BaseModel):
|
| 205 |
+
"""Mise à jour d'un point de contact."""
|
| 206 |
nom_complet: Optional[str] = Field(None, min_length=1, max_length=255)
|
| 207 |
telephone: Optional[str] = Field(None, min_length=8, max_length=20)
|
| 208 |
email: Optional[EmailStr] = None
|
|
|
|
| 210 |
|
| 211 |
|
| 212 |
class PointDeContactResponse(PointDeContactBase):
|
| 213 |
+
"""Réponse point de contact."""
|
| 214 |
id: UUID
|
| 215 |
espace_id: UUID
|
| 216 |
+
client_id: UUID
|
| 217 |
+
is_archived: bool = False
|
| 218 |
+
archived_at: Optional[datetime] = None
|
| 219 |
created_at: datetime
|
| 220 |
|
| 221 |
class Config:
|
| 222 |
from_attributes = True
|
| 223 |
|
| 224 |
|
| 225 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 226 |
# DOSSIER
|
| 227 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 228 |
|
| 229 |
class DossierBase(BaseModel):
|
| 230 |
+
"""Champs communs dossier."""
|
| 231 |
client_id: UUID
|
| 232 |
titre: Optional[str] = Field(None, max_length=255)
|
| 233 |
+
type: str = Field(
|
| 234 |
+
...,
|
| 235 |
+
pattern="^(pre_contentieux|contentieux|conseil|transactionnel)$",
|
| 236 |
+
description="Type de dossier"
|
| 237 |
+
)
|
| 238 |
description: str = Field(..., min_length=1)
|
| 239 |
statut: str = Field(
|
| 240 |
+
default="ouvert",
|
| 241 |
+
pattern="^(ouvert|en_instance|cloture)$"
|
| 242 |
+
)
|
| 243 |
partie_adverse: Optional[str] = Field(None, max_length=255)
|
| 244 |
+
preference_facturation: str = Field(
|
| 245 |
+
...,
|
| 246 |
+
pattern="^(forfait|capped_fees)$",
|
| 247 |
+
description="Mode de facturation"
|
| 248 |
+
)
|
| 249 |
+
revenu_attendu: Optional[float] = Field(
|
| 250 |
+
None, ge=0, description="Montant forfaitaire ou budget max")
|
| 251 |
|
| 252 |
|
| 253 |
class DossierCreate(DossierBase):
|
| 254 |
+
"""Création d'un dossier."""
|
| 255 |
pass
|
| 256 |
|
| 257 |
|
| 258 |
class DossierUpdate(BaseModel):
|
| 259 |
+
"""Mise à jour d'un dossier."""
|
| 260 |
titre: Optional[str] = Field(None, max_length=255)
|
| 261 |
type: Optional[str] = Field(
|
| 262 |
None, pattern="^(pre_contentieux|contentieux|conseil|transactionnel)$")
|
|
|
|
| 270 |
|
| 271 |
|
| 272 |
class DossierResponse(DossierBase):
|
| 273 |
+
"""Réponse dossier."""
|
| 274 |
id: UUID
|
| 275 |
espace_id: UUID
|
| 276 |
reference: str
|
| 277 |
+
is_archived: bool = False
|
| 278 |
+
archived_at: Optional[datetime] = None
|
| 279 |
created_at: datetime
|
| 280 |
|
| 281 |
class Config:
|
| 282 |
from_attributes = True
|
| 283 |
|
| 284 |
|
| 285 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 286 |
+
# ÉQUIPE DOSSIER
|
| 287 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 288 |
|
| 289 |
class EquipeDossierCreate(BaseModel):
|
| 290 |
+
"""Ajout d'un membre à l'équipe dossier."""
|
| 291 |
utilisateur_id: UUID
|
| 292 |
role: RoleDossier
|
| 293 |
|
| 294 |
|
| 295 |
class EquipeDossierUpdate(BaseModel):
|
| 296 |
+
"""Mise à jour du rôle d'un membre."""
|
| 297 |
role: RoleDossier
|
| 298 |
|
| 299 |
|
| 300 |
class EquipeDossierResponse(BaseModel):
|
| 301 |
+
"""Réponse membre équipe."""
|
| 302 |
dossier_id: UUID
|
| 303 |
utilisateur_id: UUID
|
| 304 |
+
role: str
|
| 305 |
+
utilisateurs: Optional[dict] = None # Données utilisateur jointes
|
| 306 |
|
| 307 |
class Config:
|
| 308 |
from_attributes = True
|
| 309 |
|
| 310 |
|
| 311 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 312 |
# AUDIENCE
|
| 313 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 314 |
|
| 315 |
class AudienceBase(BaseModel):
|
| 316 |
+
"""Champs communs audience."""
|
| 317 |
dossier_id: UUID
|
| 318 |
avocat_assigne_id: UUID
|
| 319 |
date: date
|
| 320 |
heure: time
|
| 321 |
+
type: str = Field(
|
| 322 |
+
default="audience",
|
| 323 |
+
pattern="^(audience|reunion)$",
|
| 324 |
+
description="audience = tribunal (juridiction obligatoire), reunion = interne"
|
| 325 |
+
)
|
| 326 |
+
juridiction: Optional[str] = Field(
|
| 327 |
+
None, max_length=255, description="Obligatoire si type=audience")
|
| 328 |
notes: Optional[str] = None
|
| 329 |
|
| 330 |
|
| 331 |
class AudienceCreate(AudienceBase):
|
| 332 |
+
"""Création d'une audience."""
|
| 333 |
pass
|
| 334 |
|
| 335 |
|
| 336 |
class AudienceUpdate(BaseModel):
|
| 337 |
+
"""Mise à jour d'une audience."""
|
| 338 |
avocat_assigne_id: Optional[UUID] = None
|
| 339 |
date: Optional[date] = None
|
| 340 |
heure: Optional[time] = None
|
| 341 |
+
type: Optional[str] = Field(None, pattern="^(audience|reunion)$")
|
| 342 |
+
juridiction: Optional[str] = Field(None, max_length=255)
|
| 343 |
notes: Optional[str] = None
|
| 344 |
|
| 345 |
|
| 346 |
class AudienceResponse(AudienceBase):
|
| 347 |
+
"""Réponse audience."""
|
| 348 |
id: UUID
|
| 349 |
espace_id: UUID
|
| 350 |
+
is_archived: bool = False
|
| 351 |
+
archived_at: Optional[datetime] = None
|
| 352 |
+
rappel_j7_envoye: bool = False
|
| 353 |
+
rappel_j3_envoye: bool = False
|
| 354 |
+
rappel_j1_envoye: bool = False
|
| 355 |
created_at: datetime
|
| 356 |
|
| 357 |
class Config:
|
| 358 |
from_attributes = True
|
| 359 |
|
| 360 |
|
| 361 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 362 |
# FLASH CR
|
| 363 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 364 |
|
| 365 |
class FlashCRBase(BaseModel):
|
| 366 |
+
"""Champs communs Flash CR."""
|
| 367 |
audience_id: UUID
|
| 368 |
+
type_decision: str = Field(
|
| 369 |
+
...,
|
| 370 |
+
pattern="^(decision_rendue|mise_en_delibere|renvoi|autre)$",
|
| 371 |
+
description="Type de décision rendue"
|
| 372 |
+
)
|
| 373 |
+
prochaine_date: Optional[date] = Field(
|
| 374 |
+
None,
|
| 375 |
+
description="Obligatoire si mise_en_delibere ou renvoi"
|
| 376 |
+
)
|
| 377 |
notes_rapides: str = Field(..., max_length=500)
|
| 378 |
+
envoyer_email: bool = Field(
|
| 379 |
+
default=True, description="Envoyer email auto au client")
|
| 380 |
|
| 381 |
|
| 382 |
class FlashCRCreate(FlashCRBase):
|
| 383 |
+
"""Création d'un Flash CR."""
|
| 384 |
pass
|
| 385 |
|
| 386 |
|
| 387 |
class FlashCRUpdate(BaseModel):
|
| 388 |
+
"""Mise à jour d'un Flash CR."""
|
| 389 |
type_decision: Optional[str] = Field(
|
| 390 |
+
None, pattern="^(decision_rendue|mise_en_delibere|renvoi|autre)$")
|
| 391 |
prochaine_date: Optional[date] = None
|
| 392 |
notes_rapides: Optional[str] = Field(None, max_length=500)
|
| 393 |
|
| 394 |
|
| 395 |
class FlashCRResponse(FlashCRBase):
|
| 396 |
+
"""Réponse Flash CR."""
|
| 397 |
id: UUID
|
| 398 |
espace_id: UUID
|
| 399 |
+
email_envoye: bool = False
|
| 400 |
+
email_envoye_at: Optional[datetime] = None
|
| 401 |
+
is_archived: bool = False
|
| 402 |
+
archived_at: Optional[datetime] = None
|
| 403 |
created_at: datetime
|
| 404 |
|
| 405 |
class Config:
|
| 406 |
from_attributes = True
|
| 407 |
|
| 408 |
|
| 409 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 410 |
# PAIEMENT
|
| 411 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 412 |
|
| 413 |
class PaiementBase(BaseModel):
|
| 414 |
+
"""Champs communs paiement."""
|
| 415 |
client_id: UUID
|
| 416 |
dossier_id: UUID
|
| 417 |
+
montant: float = Field(..., gt=0, description="Montant en FCFA")
|
| 418 |
date_reception: date
|
| 419 |
+
type: str = Field(
|
| 420 |
+
...,
|
| 421 |
+
pattern="^(honoraires|frais)$",
|
| 422 |
+
description="honoraires = rémunération, frais = débours"
|
| 423 |
+
)
|
| 424 |
description: Optional[str] = Field(None, max_length=500)
|
| 425 |
|
| 426 |
|
| 427 |
class PaiementCreate(PaiementBase):
|
| 428 |
+
"""Création d'un paiement."""
|
| 429 |
pass
|
| 430 |
|
| 431 |
|
| 432 |
class PaiementUpdate(BaseModel):
|
| 433 |
+
"""Mise à jour d'un paiement."""
|
| 434 |
montant: Optional[float] = Field(None, gt=0)
|
| 435 |
date_reception: Optional[date] = None
|
| 436 |
type: Optional[str] = Field(None, pattern="^(honoraires|frais)$")
|
|
|
|
| 438 |
|
| 439 |
|
| 440 |
class PaiementResponse(PaiementBase):
|
| 441 |
+
"""Réponse paiement."""
|
| 442 |
id: UUID
|
| 443 |
espace_id: UUID
|
| 444 |
+
is_archived: bool = False
|
| 445 |
+
archived_at: Optional[datetime] = None
|
| 446 |
created_at: datetime
|
| 447 |
|
| 448 |
class Config:
|
| 449 |
from_attributes = True
|
| 450 |
|
| 451 |
|
| 452 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 453 |
# FICHIER
|
| 454 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 455 |
|
| 456 |
class FichierResponse(BaseModel):
|
| 457 |
+
"""Réponse fichier."""
|
| 458 |
id: UUID
|
| 459 |
espace_id: UUID
|
| 460 |
dossier_id: UUID
|
|
|
|
| 462 |
taille: int
|
| 463 |
type_fichier: str
|
| 464 |
chemin_stockage: str
|
| 465 |
+
url: Optional[str] = Field(None, description="Signed URL temporaire")
|
| 466 |
+
url_expire_dans: int = Field(
|
| 467 |
+
default=900, description="Expiration URL en secondes")
|
| 468 |
+
is_archived: bool = False
|
| 469 |
+
archived_at: Optional[datetime] = None
|
| 470 |
created_at: datetime
|
| 471 |
|
| 472 |
class Config:
|
| 473 |
from_attributes = True
|
| 474 |
|
| 475 |
|
| 476 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 477 |
+
# AUDIT LOG
|
| 478 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 479 |
|
| 480 |
+
class AuditLogResponse(BaseModel):
|
| 481 |
+
"""Réponse log d'audit."""
|
| 482 |
+
id: UUID
|
| 483 |
+
action: str # creation | modification | archivage
|
| 484 |
+
ressource: str # clients | dossiers | audiences | flash_cr | paiements | fichiers
|
| 485 |
+
ressource_id: UUID
|
| 486 |
+
user_id: UUID
|
| 487 |
+
espace_id: UUID
|
| 488 |
+
valeur_avant: Optional[dict] = None
|
| 489 |
+
valeur_apres: Optional[dict] = None
|
| 490 |
+
timestamp: datetime
|
| 491 |
+
|
| 492 |
+
class Config:
|
| 493 |
+
from_attributes = True
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 497 |
+
# VUE 360° CLIENT
|
| 498 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 499 |
+
|
| 500 |
+
class Vue360Response(BaseModel):
|
| 501 |
+
"""Réponse vue 360° d'un client."""
|
| 502 |
+
client: ClientResponse
|
| 503 |
+
dossiers: List[DossierResponse] = []
|
| 504 |
+
paiements: List[PaiementResponse] = []
|
| 505 |
+
points_de_contact: List[PointDeContactResponse] = []
|
| 506 |
+
total_percu: float = 0
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 510 |
+
# RÉCAPITULATIF FINANCIER
|
| 511 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 512 |
+
|
| 513 |
+
class RecapitulatifFinancierResponse(BaseModel):
|
| 514 |
+
"""Récapitulatif financier d'un dossier."""
|
| 515 |
+
dossier_id: UUID
|
| 516 |
+
reference: str
|
| 517 |
+
titre: Optional[str]
|
| 518 |
+
revenu_attendu: float
|
| 519 |
+
total_percu: float
|
| 520 |
+
reste_a_percevoir: float
|
| 521 |
+
paiements: List[dict] = []
|
app/routers/__pycache__/audiences.cpython-313.pyc
CHANGED
|
Binary files a/app/routers/__pycache__/audiences.cpython-313.pyc and b/app/routers/__pycache__/audiences.cpython-313.pyc differ
|
|
|
app/routers/__pycache__/audit.cpython-313.pyc
ADDED
|
Binary file (4.89 kB). View file
|
|
|
app/routers/__pycache__/auth.cpython-313.pyc
CHANGED
|
Binary files a/app/routers/__pycache__/auth.cpython-313.pyc and b/app/routers/__pycache__/auth.cpython-313.pyc differ
|
|
|
app/routers/__pycache__/clients.cpython-313.pyc
CHANGED
|
Binary files a/app/routers/__pycache__/clients.cpython-313.pyc and b/app/routers/__pycache__/clients.cpython-313.pyc differ
|
|
|
app/routers/__pycache__/dossiers.cpython-313.pyc
CHANGED
|
Binary files a/app/routers/__pycache__/dossiers.cpython-313.pyc and b/app/routers/__pycache__/dossiers.cpython-313.pyc differ
|
|
|
app/routers/__pycache__/espaces.cpython-313.pyc
CHANGED
|
Binary files a/app/routers/__pycache__/espaces.cpython-313.pyc and b/app/routers/__pycache__/espaces.cpython-313.pyc differ
|
|
|
app/routers/__pycache__/fichiers.cpython-313.pyc
CHANGED
|
Binary files a/app/routers/__pycache__/fichiers.cpython-313.pyc and b/app/routers/__pycache__/fichiers.cpython-313.pyc differ
|
|
|
app/routers/__pycache__/flash_cr.cpython-313.pyc
CHANGED
|
Binary files a/app/routers/__pycache__/flash_cr.cpython-313.pyc and b/app/routers/__pycache__/flash_cr.cpython-313.pyc differ
|
|
|
app/routers/__pycache__/paiements.cpython-313.pyc
CHANGED
|
Binary files a/app/routers/__pycache__/paiements.cpython-313.pyc and b/app/routers/__pycache__/paiements.cpython-313.pyc differ
|
|
|
app/routers/__pycache__/utilisateurs.cpython-313.pyc
CHANGED
|
Binary files a/app/routers/__pycache__/utilisateurs.cpython-313.pyc and b/app/routers/__pycache__/utilisateurs.cpython-313.pyc differ
|
|
|
app/routers/audiences.py
CHANGED
|
@@ -1,24 +1,53 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
from uuid import UUID
|
| 3 |
-
from
|
| 4 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
from app.core.auth import require_permission, CurrentUser
|
| 6 |
from app.core.supabase import supabase_admin
|
| 7 |
|
| 8 |
router = APIRouter(prefix="/audiences", tags=["Audiences"])
|
| 9 |
|
| 10 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
@router.post("/", response_model=AudienceResponse, status_code=201)
|
| 12 |
async def create_audience(
|
| 13 |
payload: AudienceCreate,
|
| 14 |
espace_user: CurrentUser = Depends(require_permission("audience:write")),
|
| 15 |
):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
# Vérifier que le dossier appartient à cet espace
|
| 17 |
dossier = (
|
| 18 |
supabase_admin.table("dossiers")
|
| 19 |
.select("id")
|
| 20 |
.eq("id", str(payload.dossier_id))
|
| 21 |
.eq("espace_id", espace_user.espace_id)
|
|
|
|
| 22 |
.single()
|
| 23 |
.execute()
|
| 24 |
)
|
|
@@ -26,12 +55,30 @@ async def create_audience(
|
|
| 26 |
raise HTTPException(
|
| 27 |
status_code=404, detail="Dossier introuvable dans cet espace")
|
| 28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
data = payload.model_dump()
|
| 30 |
data["espace_id"] = espace_user.espace_id
|
| 31 |
data["dossier_id"] = str(payload.dossier_id)
|
| 32 |
data["avocat_assigne_id"] = str(payload.avocat_assigne_id)
|
| 33 |
data["date"] = str(payload.date)
|
| 34 |
data["heure"] = str(payload.heure)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
response = supabase_admin.table("audiences").insert(data).execute()
|
| 37 |
if not response.data:
|
|
@@ -40,18 +87,54 @@ async def create_audience(
|
|
| 40 |
return response.data[0]
|
| 41 |
|
| 42 |
|
| 43 |
-
@router.get("/", response_model=
|
| 44 |
async def list_audiences(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
espace_user: CurrentUser = Depends(require_permission("audience:read")),
|
| 46 |
):
|
| 47 |
-
|
|
|
|
| 48 |
supabase_admin.table("audiences")
|
| 49 |
-
.select("*")
|
| 50 |
.eq("espace_id", espace_user.espace_id)
|
| 51 |
-
.
|
| 52 |
-
.execute()
|
| 53 |
)
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
|
| 57 |
@router.get("/dossier/{dossier_id}", response_model=List[AudienceResponse])
|
|
@@ -59,12 +142,15 @@ async def list_audiences_by_dossier(
|
|
| 59 |
dossier_id: UUID,
|
| 60 |
espace_user: CurrentUser = Depends(require_permission("audience:read")),
|
| 61 |
):
|
|
|
|
| 62 |
response = (
|
| 63 |
supabase_admin.table("audiences")
|
| 64 |
.select("*")
|
| 65 |
.eq("dossier_id", str(dossier_id))
|
| 66 |
.eq("espace_id", espace_user.espace_id)
|
|
|
|
| 67 |
.order("date")
|
|
|
|
| 68 |
.execute()
|
| 69 |
)
|
| 70 |
return response.data or []
|
|
@@ -75,12 +161,40 @@ async def list_audiences_by_avocat(
|
|
| 75 |
avocat_id: UUID,
|
| 76 |
espace_user: CurrentUser = Depends(require_permission("audience:read")),
|
| 77 |
):
|
|
|
|
| 78 |
response = (
|
| 79 |
supabase_admin.table("audiences")
|
| 80 |
.select("*, dossiers(reference, titre)")
|
| 81 |
.eq("avocat_assigne_id", str(avocat_id))
|
| 82 |
.eq("espace_id", espace_user.espace_id)
|
|
|
|
| 83 |
.order("date")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
.execute()
|
| 85 |
)
|
| 86 |
return response.data or []
|
|
@@ -91,11 +205,13 @@ async def get_audience(
|
|
| 91 |
audience_id: UUID,
|
| 92 |
espace_user: CurrentUser = Depends(require_permission("audience:read")),
|
| 93 |
):
|
|
|
|
| 94 |
response = (
|
| 95 |
supabase_admin.table("audiences")
|
| 96 |
.select("*")
|
| 97 |
.eq("id", str(audience_id))
|
| 98 |
.eq("espace_id", espace_user.espace_id)
|
|
|
|
| 99 |
.single()
|
| 100 |
.execute()
|
| 101 |
)
|
|
@@ -110,9 +226,27 @@ async def update_audience(
|
|
| 110 |
payload: AudienceUpdate,
|
| 111 |
espace_user: CurrentUser = Depends(require_permission("audience:write")),
|
| 112 |
):
|
|
|
|
| 113 |
data = payload.model_dump(exclude_none=True)
|
| 114 |
if not data:
|
| 115 |
raise HTTPException(status_code=400, detail="Aucune donnée à modifier")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
if "date" in data:
|
| 117 |
data["date"] = str(data["date"])
|
| 118 |
if "heure" in data:
|
|
@@ -125,6 +259,7 @@ async def update_audience(
|
|
| 125 |
.update(data)
|
| 126 |
.eq("id", str(audience_id))
|
| 127 |
.eq("espace_id", espace_user.espace_id)
|
|
|
|
| 128 |
.execute()
|
| 129 |
)
|
| 130 |
if not response.data:
|
|
@@ -133,10 +268,22 @@ async def update_audience(
|
|
| 133 |
|
| 134 |
|
| 135 |
@router.delete("/{audience_id}", response_model=MessageResponse)
|
| 136 |
-
async def
|
| 137 |
audience_id: UUID,
|
| 138 |
espace_user: CurrentUser = Depends(require_permission("audience:delete")),
|
| 139 |
):
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Dedalys Backend — Router Audiences
|
| 3 |
+
CRUD audiences avec distinction audience/réunion, flags rappels, soft delete.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from typing import Optional, List
|
| 7 |
+
from math import ceil
|
| 8 |
from uuid import UUID
|
| 9 |
+
from datetime import datetime, timezone, date
|
| 10 |
+
|
| 11 |
+
from fastapi import APIRouter, HTTPException, Depends, Query
|
| 12 |
+
|
| 13 |
+
from app.models.schemas import (
|
| 14 |
+
AudienceCreate, AudienceUpdate, AudienceResponse,
|
| 15 |
+
PaginatedResponse, MessageResponse,
|
| 16 |
+
)
|
| 17 |
from app.core.auth import require_permission, CurrentUser
|
| 18 |
from app.core.supabase import supabase_admin
|
| 19 |
|
| 20 |
router = APIRouter(prefix="/audiences", tags=["Audiences"])
|
| 21 |
|
| 22 |
|
| 23 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 24 |
+
# CRUD AUDIENCES
|
| 25 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 26 |
+
|
| 27 |
@router.post("/", response_model=AudienceResponse, status_code=201)
|
| 28 |
async def create_audience(
|
| 29 |
payload: AudienceCreate,
|
| 30 |
espace_user: CurrentUser = Depends(require_permission("audience:write")),
|
| 31 |
):
|
| 32 |
+
"""
|
| 33 |
+
Crée une audience ou réunion.
|
| 34 |
+
- type=audience : juridiction obligatoire (tribunal)
|
| 35 |
+
- type=reunion : pas de juridiction (interne)
|
| 36 |
+
"""
|
| 37 |
+
# Validation : juridiction obligatoire si type=audience
|
| 38 |
+
if payload.type == "audience" and not payload.juridiction:
|
| 39 |
+
raise HTTPException(
|
| 40 |
+
status_code=400,
|
| 41 |
+
detail="La juridiction est obligatoire pour une audience (type=audience)"
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
# Vérifier que le dossier appartient à cet espace
|
| 45 |
dossier = (
|
| 46 |
supabase_admin.table("dossiers")
|
| 47 |
.select("id")
|
| 48 |
.eq("id", str(payload.dossier_id))
|
| 49 |
.eq("espace_id", espace_user.espace_id)
|
| 50 |
+
.eq("is_archived", False)
|
| 51 |
.single()
|
| 52 |
.execute()
|
| 53 |
)
|
|
|
|
| 55 |
raise HTTPException(
|
| 56 |
status_code=404, detail="Dossier introuvable dans cet espace")
|
| 57 |
|
| 58 |
+
# Vérifier que l'avocat assigné appartient à l'espace
|
| 59 |
+
avocat = (
|
| 60 |
+
supabase_admin.table("utilisateurs")
|
| 61 |
+
.select("id")
|
| 62 |
+
.eq("id", str(payload.avocat_assigne_id))
|
| 63 |
+
.eq("espace_id", espace_user.espace_id)
|
| 64 |
+
.single()
|
| 65 |
+
.execute()
|
| 66 |
+
)
|
| 67 |
+
if not avocat.data:
|
| 68 |
+
raise HTTPException(
|
| 69 |
+
status_code=400, detail="Avocat assigné introuvable dans cet espace")
|
| 70 |
+
|
| 71 |
data = payload.model_dump()
|
| 72 |
data["espace_id"] = espace_user.espace_id
|
| 73 |
data["dossier_id"] = str(payload.dossier_id)
|
| 74 |
data["avocat_assigne_id"] = str(payload.avocat_assigne_id)
|
| 75 |
data["date"] = str(payload.date)
|
| 76 |
data["heure"] = str(payload.heure)
|
| 77 |
+
data["is_archived"] = False
|
| 78 |
+
# Flags rappels initialisés à False
|
| 79 |
+
data["rappel_j7_envoye"] = False
|
| 80 |
+
data["rappel_j3_envoye"] = False
|
| 81 |
+
data["rappel_j1_envoye"] = False
|
| 82 |
|
| 83 |
response = supabase_admin.table("audiences").insert(data).execute()
|
| 84 |
if not response.data:
|
|
|
|
| 87 |
return response.data[0]
|
| 88 |
|
| 89 |
|
| 90 |
+
@router.get("/", response_model=PaginatedResponse[AudienceResponse])
|
| 91 |
async def list_audiences(
|
| 92 |
+
page: int = Query(1, ge=1),
|
| 93 |
+
limit: int = Query(20, ge=1, le=100),
|
| 94 |
+
type: Optional[str] = Query(
|
| 95 |
+
None, pattern="^(audience|reunion)$", description="Filtrer par type"),
|
| 96 |
+
avocat_id: Optional[UUID] = Query(None, description="Filtrer par avocat"),
|
| 97 |
+
dossier_id: Optional[UUID] = Query(
|
| 98 |
+
None, description="Filtrer par dossier"),
|
| 99 |
+
date_debut: Optional[date] = Query(None, description="Date de début"),
|
| 100 |
+
date_fin: Optional[date] = Query(None, description="Date de fin"),
|
| 101 |
espace_user: CurrentUser = Depends(require_permission("audience:read")),
|
| 102 |
):
|
| 103 |
+
"""Liste les audiences avec pagination et filtres."""
|
| 104 |
+
query = (
|
| 105 |
supabase_admin.table("audiences")
|
| 106 |
+
.select("*", count="exact")
|
| 107 |
.eq("espace_id", espace_user.espace_id)
|
| 108 |
+
.eq("is_archived", False)
|
|
|
|
| 109 |
)
|
| 110 |
+
|
| 111 |
+
# Filtres
|
| 112 |
+
if type:
|
| 113 |
+
query = query.eq("type", type)
|
| 114 |
+
if avocat_id:
|
| 115 |
+
query = query.eq("avocat_assigne_id", str(avocat_id))
|
| 116 |
+
if dossier_id:
|
| 117 |
+
query = query.eq("dossier_id", str(dossier_id))
|
| 118 |
+
if date_debut:
|
| 119 |
+
query = query.gte("date", str(date_debut))
|
| 120 |
+
if date_fin:
|
| 121 |
+
query = query.lte("date", str(date_fin))
|
| 122 |
+
|
| 123 |
+
# Pagination
|
| 124 |
+
offset = (page - 1) * limit
|
| 125 |
+
query = query.order("date").order(
|
| 126 |
+
"heure").range(offset, offset + limit - 1)
|
| 127 |
+
|
| 128 |
+
response = query.execute()
|
| 129 |
+
total = response.count or 0
|
| 130 |
+
|
| 131 |
+
return {
|
| 132 |
+
"data": response.data or [],
|
| 133 |
+
"total": total,
|
| 134 |
+
"page": page,
|
| 135 |
+
"limit": limit,
|
| 136 |
+
"pages": ceil(total / limit) if total > 0 else 1,
|
| 137 |
+
}
|
| 138 |
|
| 139 |
|
| 140 |
@router.get("/dossier/{dossier_id}", response_model=List[AudienceResponse])
|
|
|
|
| 142 |
dossier_id: UUID,
|
| 143 |
espace_user: CurrentUser = Depends(require_permission("audience:read")),
|
| 144 |
):
|
| 145 |
+
"""Liste les audiences d'un dossier spécifique."""
|
| 146 |
response = (
|
| 147 |
supabase_admin.table("audiences")
|
| 148 |
.select("*")
|
| 149 |
.eq("dossier_id", str(dossier_id))
|
| 150 |
.eq("espace_id", espace_user.espace_id)
|
| 151 |
+
.eq("is_archived", False)
|
| 152 |
.order("date")
|
| 153 |
+
.order("heure")
|
| 154 |
.execute()
|
| 155 |
)
|
| 156 |
return response.data or []
|
|
|
|
| 161 |
avocat_id: UUID,
|
| 162 |
espace_user: CurrentUser = Depends(require_permission("audience:read")),
|
| 163 |
):
|
| 164 |
+
"""Liste les audiences assignées à un avocat."""
|
| 165 |
response = (
|
| 166 |
supabase_admin.table("audiences")
|
| 167 |
.select("*, dossiers(reference, titre)")
|
| 168 |
.eq("avocat_assigne_id", str(avocat_id))
|
| 169 |
.eq("espace_id", espace_user.espace_id)
|
| 170 |
+
.eq("is_archived", False)
|
| 171 |
.order("date")
|
| 172 |
+
.order("heure")
|
| 173 |
+
.execute()
|
| 174 |
+
)
|
| 175 |
+
return response.data or []
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
@router.get("/a-venir", response_model=List[AudienceResponse])
|
| 179 |
+
async def list_audiences_a_venir(
|
| 180 |
+
jours: int = Query(7, ge=1, le=30, description="Nombre de jours à venir"),
|
| 181 |
+
espace_user: CurrentUser = Depends(require_permission("audience:read")),
|
| 182 |
+
):
|
| 183 |
+
"""Liste les audiences à venir dans les N prochains jours."""
|
| 184 |
+
from datetime import timedelta
|
| 185 |
+
|
| 186 |
+
aujourd_hui = date.today()
|
| 187 |
+
date_limite = aujourd_hui + timedelta(days=jours)
|
| 188 |
+
|
| 189 |
+
response = (
|
| 190 |
+
supabase_admin.table("audiences")
|
| 191 |
+
.select("*, dossiers(reference, titre), utilisateurs(nom, prenom)")
|
| 192 |
+
.eq("espace_id", espace_user.espace_id)
|
| 193 |
+
.eq("is_archived", False)
|
| 194 |
+
.gte("date", str(aujourd_hui))
|
| 195 |
+
.lte("date", str(date_limite))
|
| 196 |
+
.order("date")
|
| 197 |
+
.order("heure")
|
| 198 |
.execute()
|
| 199 |
)
|
| 200 |
return response.data or []
|
|
|
|
| 205 |
audience_id: UUID,
|
| 206 |
espace_user: CurrentUser = Depends(require_permission("audience:read")),
|
| 207 |
):
|
| 208 |
+
"""Récupère une audience par son ID."""
|
| 209 |
response = (
|
| 210 |
supabase_admin.table("audiences")
|
| 211 |
.select("*")
|
| 212 |
.eq("id", str(audience_id))
|
| 213 |
.eq("espace_id", espace_user.espace_id)
|
| 214 |
+
.eq("is_archived", False)
|
| 215 |
.single()
|
| 216 |
.execute()
|
| 217 |
)
|
|
|
|
| 226 |
payload: AudienceUpdate,
|
| 227 |
espace_user: CurrentUser = Depends(require_permission("audience:write")),
|
| 228 |
):
|
| 229 |
+
"""Met à jour une audience."""
|
| 230 |
data = payload.model_dump(exclude_none=True)
|
| 231 |
if not data:
|
| 232 |
raise HTTPException(status_code=400, detail="Aucune donnée à modifier")
|
| 233 |
+
|
| 234 |
+
# Validation si le type change vers audience
|
| 235 |
+
if data.get("type") == "audience" and not data.get("juridiction"):
|
| 236 |
+
existing = (
|
| 237 |
+
supabase_admin.table("audiences")
|
| 238 |
+
.select("juridiction")
|
| 239 |
+
.eq("id", str(audience_id))
|
| 240 |
+
.single()
|
| 241 |
+
.execute()
|
| 242 |
+
)
|
| 243 |
+
if existing.data and not existing.data.get("juridiction"):
|
| 244 |
+
raise HTTPException(
|
| 245 |
+
status_code=400,
|
| 246 |
+
detail="La juridiction est obligatoire pour une audience"
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
# Conversion des types pour Supabase
|
| 250 |
if "date" in data:
|
| 251 |
data["date"] = str(data["date"])
|
| 252 |
if "heure" in data:
|
|
|
|
| 259 |
.update(data)
|
| 260 |
.eq("id", str(audience_id))
|
| 261 |
.eq("espace_id", espace_user.espace_id)
|
| 262 |
+
.eq("is_archived", False)
|
| 263 |
.execute()
|
| 264 |
)
|
| 265 |
if not response.data:
|
|
|
|
| 268 |
|
| 269 |
|
| 270 |
@router.delete("/{audience_id}", response_model=MessageResponse)
|
| 271 |
+
async def archive_audience(
|
| 272 |
audience_id: UUID,
|
| 273 |
espace_user: CurrentUser = Depends(require_permission("audience:delete")),
|
| 274 |
):
|
| 275 |
+
"""Archive une audience (soft delete)."""
|
| 276 |
+
response = (
|
| 277 |
+
supabase_admin.table("audiences")
|
| 278 |
+
.update({
|
| 279 |
+
"is_archived": True,
|
| 280 |
+
"archived_at": datetime.now(timezone.utc).isoformat(),
|
| 281 |
+
})
|
| 282 |
+
.eq("id", str(audience_id))
|
| 283 |
+
.eq("espace_id", espace_user.espace_id)
|
| 284 |
+
.eq("is_archived", False)
|
| 285 |
+
.execute()
|
| 286 |
+
)
|
| 287 |
+
if not response.data:
|
| 288 |
+
raise HTTPException(status_code=404, detail="Audience introuvable")
|
| 289 |
+
return {"message": "Audience archivée"}
|
app/routers/audit.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Dedalys Backend — Router Audit Trail
|
| 3 |
+
Consultation des logs d'audit (réservé aux associés gérants).
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from typing import Optional
|
| 7 |
+
from math import ceil
|
| 8 |
+
from uuid import UUID
|
| 9 |
+
from datetime import date
|
| 10 |
+
|
| 11 |
+
from fastapi import APIRouter, HTTPException, Depends, Query
|
| 12 |
+
|
| 13 |
+
from app.models.schemas import AuditLogResponse, PaginatedResponse
|
| 14 |
+
from app.core.auth import require_permission, CurrentUser
|
| 15 |
+
from app.core.supabase import supabase_admin
|
| 16 |
+
|
| 17 |
+
router = APIRouter(prefix="/audit", tags=["Audit Trail"])
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@router.get("/", response_model=PaginatedResponse[AuditLogResponse])
|
| 21 |
+
async def list_audit_logs(
|
| 22 |
+
page: int = Query(1, ge=1),
|
| 23 |
+
limit: int = Query(50, ge=1, le=100),
|
| 24 |
+
ressource: Optional[str] = Query(
|
| 25 |
+
None,
|
| 26 |
+
description="Type de ressource",
|
| 27 |
+
pattern="^(clients|dossiers|audiences|flash_cr|paiements|fichiers|utilisateurs)$"
|
| 28 |
+
),
|
| 29 |
+
action: Optional[str] = Query(
|
| 30 |
+
None,
|
| 31 |
+
description="Type d'action",
|
| 32 |
+
pattern="^(creation|modification|archivage)$"
|
| 33 |
+
),
|
| 34 |
+
user_id: Optional[UUID] = Query(
|
| 35 |
+
None, description="Filtrer par auteur de l'action"),
|
| 36 |
+
ressource_id: Optional[UUID] = Query(
|
| 37 |
+
None, description="Filtrer par ID de ressource"),
|
| 38 |
+
date_debut: Optional[date] = Query(None, description="Date de début"),
|
| 39 |
+
date_fin: Optional[date] = Query(None, description="Date de fin"),
|
| 40 |
+
espace_user: CurrentUser = Depends(require_permission("client:read")),
|
| 41 |
+
):
|
| 42 |
+
"""
|
| 43 |
+
Consultation des logs d'audit.
|
| 44 |
+
|
| 45 |
+
Accès réservé aux associés gérants pour des raisons de confidentialité.
|
| 46 |
+
Permet de tracer toutes les actions sensibles sur les données.
|
| 47 |
+
"""
|
| 48 |
+
# Vérification du rôle — seul associe_gerant peut consulter l'audit
|
| 49 |
+
if espace_user.role_cabinet.value != "associe_gerant":
|
| 50 |
+
raise HTTPException(
|
| 51 |
+
status_code=403,
|
| 52 |
+
detail="Accès réservé à l'associé gérant"
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
query = (
|
| 56 |
+
supabase_admin.table("audit_logs")
|
| 57 |
+
.select("*", count="exact")
|
| 58 |
+
.eq("espace_id", espace_user.espace_id)
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
# Filtres
|
| 62 |
+
if ressource:
|
| 63 |
+
query = query.eq("ressource", ressource)
|
| 64 |
+
if action:
|
| 65 |
+
query = query.eq("action", action)
|
| 66 |
+
if user_id:
|
| 67 |
+
query = query.eq("user_id", str(user_id))
|
| 68 |
+
if ressource_id:
|
| 69 |
+
query = query.eq("ressource_id", str(ressource_id))
|
| 70 |
+
if date_debut:
|
| 71 |
+
query = query.gte("timestamp", f"{date_debut}T00:00:00Z")
|
| 72 |
+
if date_fin:
|
| 73 |
+
query = query.lte("timestamp", f"{date_fin}T23:59:59Z")
|
| 74 |
+
|
| 75 |
+
# Pagination
|
| 76 |
+
offset = (page - 1) * limit
|
| 77 |
+
query = query.order("timestamp", desc=True).range(
|
| 78 |
+
offset, offset + limit - 1)
|
| 79 |
+
|
| 80 |
+
response = query.execute()
|
| 81 |
+
total = response.count or 0
|
| 82 |
+
|
| 83 |
+
return {
|
| 84 |
+
"data": response.data or [],
|
| 85 |
+
"total": total,
|
| 86 |
+
"page": page,
|
| 87 |
+
"limit": limit,
|
| 88 |
+
"pages": ceil(total / limit) if total > 0 else 1,
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@router.get("/ressource/{ressource}/{ressource_id}", response_model=list[AuditLogResponse])
|
| 93 |
+
async def get_audit_by_ressource(
|
| 94 |
+
ressource: str,
|
| 95 |
+
ressource_id: UUID,
|
| 96 |
+
espace_user: CurrentUser = Depends(require_permission("client:read")),
|
| 97 |
+
):
|
| 98 |
+
"""
|
| 99 |
+
Récupère l'historique d'audit d'une ressource spécifique.
|
| 100 |
+
Utile pour voir l'historique complet des modifications d'un client, dossier, etc.
|
| 101 |
+
"""
|
| 102 |
+
# Vérification du rôle
|
| 103 |
+
if espace_user.role_cabinet.value != "associe_gerant":
|
| 104 |
+
raise HTTPException(
|
| 105 |
+
status_code=403,
|
| 106 |
+
detail="Accès réservé à l'associé gérant"
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
response = (
|
| 110 |
+
supabase_admin.table("audit_logs")
|
| 111 |
+
.select("*")
|
| 112 |
+
.eq("espace_id", espace_user.espace_id)
|
| 113 |
+
.eq("ressource", ressource)
|
| 114 |
+
.eq("ressource_id", str(ressource_id))
|
| 115 |
+
.order("timestamp", desc=True)
|
| 116 |
+
.execute()
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
return response.data or []
|
app/routers/auth.py
CHANGED
|
@@ -1,8 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from fastapi import APIRouter, HTTPException
|
|
|
|
| 2 |
from app.models.schemas import (
|
| 3 |
-
LoginRequest, TokenResponse, RefreshRequest, MessageResponse
|
|
|
|
| 4 |
)
|
| 5 |
from app.core.supabase import supabase, supabase_admin
|
|
|
|
| 6 |
|
| 7 |
router = APIRouter(prefix="/auth", tags=["Authentification"])
|
| 8 |
|
|
@@ -11,8 +19,7 @@ router = APIRouter(prefix="/auth", tags=["Authentification"])
|
|
| 11 |
async def login(payload: LoginRequest):
|
| 12 |
"""
|
| 13 |
Connexion email/password.
|
| 14 |
-
|
| 15 |
-
Les comptes sont créés par les superadmins — pas d'auto-inscription.
|
| 16 |
"""
|
| 17 |
try:
|
| 18 |
auth_response = supabase.auth.sign_in_with_password({
|
|
@@ -27,6 +34,7 @@ async def login(payload: LoginRequest):
|
|
| 27 |
raise HTTPException(
|
| 28 |
status_code=401, detail="Email ou mot de passe incorrect")
|
| 29 |
|
|
|
|
| 30 |
profile_response = (
|
| 31 |
supabase_admin.table("utilisateurs")
|
| 32 |
.select("*")
|
|
@@ -35,7 +43,8 @@ async def login(payload: LoginRequest):
|
|
| 35 |
.execute()
|
| 36 |
)
|
| 37 |
if not profile_response.data:
|
| 38 |
-
raise HTTPException(
|
|
|
|
| 39 |
|
| 40 |
return {
|
| 41 |
"access_token": auth_response.session.access_token,
|
|
@@ -47,7 +56,9 @@ async def login(payload: LoginRequest):
|
|
| 47 |
|
| 48 |
@router.post("/refresh", response_model=TokenResponse)
|
| 49 |
async def refresh_token(payload: RefreshRequest):
|
| 50 |
-
"""
|
|
|
|
|
|
|
| 51 |
try:
|
| 52 |
auth_response = supabase.auth.refresh_session(payload.refresh_token)
|
| 53 |
except Exception:
|
|
@@ -58,6 +69,7 @@ async def refresh_token(payload: RefreshRequest):
|
|
| 58 |
raise HTTPException(
|
| 59 |
status_code=401, detail="Impossible de renouveler la session")
|
| 60 |
|
|
|
|
| 61 |
profile_response = (
|
| 62 |
supabase_admin.table("utilisateurs")
|
| 63 |
.select("*")
|
|
@@ -76,6 +88,56 @@ async def refresh_token(payload: RefreshRequest):
|
|
| 76 |
|
| 77 |
@router.post("/logout", response_model=MessageResponse)
|
| 78 |
async def logout():
|
| 79 |
-
"""
|
| 80 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
return {"message": "Déconnecté avec succès"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Dedalys Backend — Router Authentification
|
| 3 |
+
Endpoints: login, refresh, logout, forgot-password, reset-password
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
from fastapi import APIRouter, HTTPException
|
| 7 |
+
|
| 8 |
from app.models.schemas import (
|
| 9 |
+
LoginRequest, TokenResponse, RefreshRequest, MessageResponse,
|
| 10 |
+
ForgotPasswordRequest, ResetPasswordRequest,
|
| 11 |
)
|
| 12 |
from app.core.supabase import supabase, supabase_admin
|
| 13 |
+
from app.core.config import settings
|
| 14 |
|
| 15 |
router = APIRouter(prefix="/auth", tags=["Authentification"])
|
| 16 |
|
|
|
|
| 19 |
async def login(payload: LoginRequest):
|
| 20 |
"""
|
| 21 |
Connexion email/password.
|
| 22 |
+
Retourne access_token (1h) et refresh_token (7j).
|
|
|
|
| 23 |
"""
|
| 24 |
try:
|
| 25 |
auth_response = supabase.auth.sign_in_with_password({
|
|
|
|
| 34 |
raise HTTPException(
|
| 35 |
status_code=401, detail="Email ou mot de passe incorrect")
|
| 36 |
|
| 37 |
+
# Récupérer le profil utilisateur
|
| 38 |
profile_response = (
|
| 39 |
supabase_admin.table("utilisateurs")
|
| 40 |
.select("*")
|
|
|
|
| 43 |
.execute()
|
| 44 |
)
|
| 45 |
if not profile_response.data:
|
| 46 |
+
raise HTTPException(
|
| 47 |
+
status_code=404, detail="Profil utilisateur introuvable")
|
| 48 |
|
| 49 |
return {
|
| 50 |
"access_token": auth_response.session.access_token,
|
|
|
|
| 56 |
|
| 57 |
@router.post("/refresh", response_model=TokenResponse)
|
| 58 |
async def refresh_token(payload: RefreshRequest):
|
| 59 |
+
"""
|
| 60 |
+
Renouvelle l'access_token à partir du refresh_token.
|
| 61 |
+
"""
|
| 62 |
try:
|
| 63 |
auth_response = supabase.auth.refresh_session(payload.refresh_token)
|
| 64 |
except Exception:
|
|
|
|
| 69 |
raise HTTPException(
|
| 70 |
status_code=401, detail="Impossible de renouveler la session")
|
| 71 |
|
| 72 |
+
# Récupérer le profil utilisateur
|
| 73 |
profile_response = (
|
| 74 |
supabase_admin.table("utilisateurs")
|
| 75 |
.select("*")
|
|
|
|
| 88 |
|
| 89 |
@router.post("/logout", response_model=MessageResponse)
|
| 90 |
async def logout():
|
| 91 |
+
"""
|
| 92 |
+
Révoque la session côté Supabase.
|
| 93 |
+
"""
|
| 94 |
+
try:
|
| 95 |
+
supabase.auth.sign_out()
|
| 96 |
+
except Exception:
|
| 97 |
+
pass # Ignorer les erreurs de déconnexion
|
| 98 |
return {"message": "Déconnecté avec succès"}
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
@router.post("/forgot-password", response_model=MessageResponse)
|
| 102 |
+
async def forgot_password(payload: ForgotPasswordRequest):
|
| 103 |
+
"""
|
| 104 |
+
Demande de réinitialisation de mot de passe.
|
| 105 |
+
Envoie un email avec un lien de reset (géré par Supabase Auth).
|
| 106 |
+
|
| 107 |
+
Retourne toujours 200 OK pour éviter l'énumération d'emails.
|
| 108 |
+
"""
|
| 109 |
+
try:
|
| 110 |
+
supabase.auth.reset_password_email(
|
| 111 |
+
payload.email,
|
| 112 |
+
options={
|
| 113 |
+
"redirect_to": settings.SUPABASE_RESET_PASSWORD_REDIRECT_URL,
|
| 114 |
+
}
|
| 115 |
+
)
|
| 116 |
+
except Exception:
|
| 117 |
+
# On ne révèle pas si l'email existe ou non (sécurité)
|
| 118 |
+
pass
|
| 119 |
+
|
| 120 |
+
return {"message": "Si cet email existe, un lien de réinitialisation a été envoyé"}
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
@router.post("/reset-password", response_model=MessageResponse)
|
| 124 |
+
async def reset_password(payload: ResetPasswordRequest):
|
| 125 |
+
"""
|
| 126 |
+
Définit un nouveau mot de passe.
|
| 127 |
+
|
| 128 |
+
MVP — Le flow Supabase Auth utilise le token dans l'URL de callback.
|
| 129 |
+
Le frontend doit d'abord échanger ce token via supabase.auth.verifyOtp()
|
| 130 |
+
puis appeler updateUser() avec le nouveau mot de passe.
|
| 131 |
+
|
| 132 |
+
Cet endpoint est exposé pour cohérence API et cas d'usage avancés.
|
| 133 |
+
"""
|
| 134 |
+
try:
|
| 135 |
+
# MVP — ici le token est l'user_id après vérification côté front
|
| 136 |
+
supabase_admin.auth.admin.update_user_by_id(
|
| 137 |
+
payload.token,
|
| 138 |
+
{"password": payload.new_password}
|
| 139 |
+
)
|
| 140 |
+
except Exception:
|
| 141 |
+
raise HTTPException(status_code=400, detail="Token invalide ou expiré")
|
| 142 |
+
|
| 143 |
+
return {"message": "Mot de passe modifié avec succès"}
|
app/routers/clients.py
CHANGED
|
@@ -1,10 +1,19 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
from uuid import UUID
|
| 3 |
-
from
|
|
|
|
|
|
|
|
|
|
| 4 |
from app.models.schemas import (
|
| 5 |
ClientCreate, ClientUpdate, ClientResponse,
|
| 6 |
PointDeContactCreate, PointDeContactUpdate, PointDeContactResponse,
|
| 7 |
-
MessageResponse,
|
| 8 |
)
|
| 9 |
from app.core.auth import require_permission, CurrentUser
|
| 10 |
from app.core.supabase import supabase_admin
|
|
@@ -12,15 +21,33 @@ from app.core.supabase import supabase_admin
|
|
| 12 |
router = APIRouter(prefix="/clients", tags=["Clients"])
|
| 13 |
|
| 14 |
|
| 15 |
-
#
|
|
|
|
|
|
|
| 16 |
|
| 17 |
@router.post("/", response_model=ClientResponse, status_code=201)
|
| 18 |
async def create_client(
|
| 19 |
payload: ClientCreate,
|
| 20 |
espace_user: CurrentUser = Depends(require_permission("client:write")),
|
| 21 |
):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
data = payload.model_dump()
|
| 23 |
data["espace_id"] = espace_user.espace_id
|
|
|
|
|
|
|
| 24 |
response = supabase_admin.table("clients").insert(data).execute()
|
| 25 |
if not response.data:
|
| 26 |
raise HTTPException(
|
|
@@ -28,19 +55,48 @@ async def create_client(
|
|
| 28 |
return response.data[0]
|
| 29 |
|
| 30 |
|
| 31 |
-
@router.get("/", response_model=
|
| 32 |
async def list_clients(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
espace_user: CurrentUser = Depends(require_permission("client:read")),
|
| 34 |
):
|
| 35 |
-
"""Liste
|
| 36 |
-
|
| 37 |
supabase_admin.table("clients")
|
| 38 |
-
.select("*")
|
| 39 |
.eq("espace_id", espace_user.espace_id)
|
| 40 |
-
.
|
| 41 |
-
.execute()
|
| 42 |
)
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
|
| 46 |
@router.get("/{client_id}", response_model=ClientResponse)
|
|
@@ -48,11 +104,13 @@ async def get_client(
|
|
| 48 |
client_id: UUID,
|
| 49 |
espace_user: CurrentUser = Depends(require_permission("client:read")),
|
| 50 |
):
|
|
|
|
| 51 |
response = (
|
| 52 |
supabase_admin.table("clients")
|
| 53 |
.select("*")
|
| 54 |
.eq("id", str(client_id))
|
| 55 |
.eq("espace_id", espace_user.espace_id)
|
|
|
|
| 56 |
.single()
|
| 57 |
.execute()
|
| 58 |
)
|
|
@@ -67,14 +125,17 @@ async def update_client(
|
|
| 67 |
payload: ClientUpdate,
|
| 68 |
espace_user: CurrentUser = Depends(require_permission("client:write")),
|
| 69 |
):
|
|
|
|
| 70 |
data = payload.model_dump(exclude_none=True)
|
| 71 |
if not data:
|
| 72 |
raise HTTPException(status_code=400, detail="Aucune donnée à modifier")
|
|
|
|
| 73 |
response = (
|
| 74 |
supabase_admin.table("clients")
|
| 75 |
.update(data)
|
| 76 |
.eq("id", str(client_id))
|
| 77 |
.eq("espace_id", espace_user.espace_id)
|
|
|
|
| 78 |
.execute()
|
| 79 |
)
|
| 80 |
if not response.data:
|
|
@@ -83,48 +144,100 @@ async def update_client(
|
|
| 83 |
|
| 84 |
|
| 85 |
@router.delete("/{client_id}", response_model=MessageResponse)
|
| 86 |
-
async def
|
| 87 |
client_id: UUID,
|
| 88 |
espace_user: CurrentUser = Depends(require_permission("client:delete")),
|
| 89 |
):
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
|
| 94 |
|
| 95 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
async def vue_360(
|
| 97 |
client_id: UUID,
|
| 98 |
espace_user: CurrentUser = Depends(require_permission("client:read")),
|
| 99 |
):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
client = (
|
| 101 |
supabase_admin.table("clients")
|
| 102 |
.select("*")
|
| 103 |
.eq("id", str(client_id))
|
| 104 |
.eq("espace_id", espace_user.espace_id)
|
|
|
|
| 105 |
.single()
|
| 106 |
.execute()
|
| 107 |
)
|
| 108 |
if not client.data:
|
| 109 |
raise HTTPException(status_code=404, detail="Client introuvable")
|
| 110 |
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
return {
|
| 119 |
"client": client.data,
|
| 120 |
"dossiers": dossiers.data or [],
|
| 121 |
"paiements": paiements.data or [],
|
| 122 |
"points_de_contact": contacts.data or [],
|
| 123 |
-
"total_percu":
|
| 124 |
}
|
| 125 |
|
| 126 |
|
| 127 |
-
#
|
|
|
|
|
|
|
| 128 |
|
| 129 |
@router.post("/{client_id}/contacts", response_model=PointDeContactResponse, status_code=201)
|
| 130 |
async def create_contact(
|
|
@@ -132,9 +245,25 @@ async def create_contact(
|
|
| 132 |
payload: PointDeContactCreate,
|
| 133 |
espace_user: CurrentUser = Depends(require_permission("client:write")),
|
| 134 |
):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
data = payload.model_dump()
|
| 136 |
data["client_id"] = str(client_id)
|
| 137 |
data["espace_id"] = espace_user.espace_id
|
|
|
|
|
|
|
| 138 |
response = supabase_admin.table("points_de_contact").insert(data).execute()
|
| 139 |
if not response.data:
|
| 140 |
raise HTTPException(
|
|
@@ -142,16 +271,18 @@ async def create_contact(
|
|
| 142 |
return response.data[0]
|
| 143 |
|
| 144 |
|
| 145 |
-
@router.get("/{client_id}/contacts", response_model=
|
| 146 |
async def list_contacts(
|
| 147 |
client_id: UUID,
|
| 148 |
espace_user: CurrentUser = Depends(require_permission("client:read")),
|
| 149 |
):
|
|
|
|
| 150 |
response = (
|
| 151 |
supabase_admin.table("points_de_contact")
|
| 152 |
.select("*")
|
| 153 |
.eq("client_id", str(client_id))
|
| 154 |
.eq("espace_id", espace_user.espace_id)
|
|
|
|
| 155 |
.execute()
|
| 156 |
)
|
| 157 |
return response.data or []
|
|
@@ -164,15 +295,18 @@ async def update_contact(
|
|
| 164 |
payload: PointDeContactUpdate,
|
| 165 |
espace_user: CurrentUser = Depends(require_permission("client:write")),
|
| 166 |
):
|
|
|
|
| 167 |
data = payload.model_dump(exclude_none=True)
|
| 168 |
if not data:
|
| 169 |
raise HTTPException(status_code=400, detail="Aucune donnée à modifier")
|
|
|
|
| 170 |
response = (
|
| 171 |
supabase_admin.table("points_de_contact")
|
| 172 |
.update(data)
|
| 173 |
.eq("id", str(contact_id))
|
| 174 |
.eq("client_id", str(client_id))
|
| 175 |
.eq("espace_id", espace_user.espace_id)
|
|
|
|
| 176 |
.execute()
|
| 177 |
)
|
| 178 |
if not response.data:
|
|
@@ -181,11 +315,24 @@ async def update_contact(
|
|
| 181 |
|
| 182 |
|
| 183 |
@router.delete("/{client_id}/contacts/{contact_id}", response_model=MessageResponse)
|
| 184 |
-
async def
|
| 185 |
client_id: UUID,
|
| 186 |
contact_id: UUID,
|
| 187 |
espace_user: CurrentUser = Depends(require_permission("client:delete")),
|
| 188 |
):
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Dedalys Backend — Router Clients
|
| 3 |
+
CRUD clients avec vue 360°, points de contact, soft delete, pagination et filtres.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from typing import Optional
|
| 7 |
+
from math import ceil
|
| 8 |
from uuid import UUID
|
| 9 |
+
from datetime import datetime, timezone
|
| 10 |
+
|
| 11 |
+
from fastapi import APIRouter, HTTPException, Depends, Query
|
| 12 |
+
|
| 13 |
from app.models.schemas import (
|
| 14 |
ClientCreate, ClientUpdate, ClientResponse,
|
| 15 |
PointDeContactCreate, PointDeContactUpdate, PointDeContactResponse,
|
| 16 |
+
PaginatedResponse, MessageResponse, Vue360Response,
|
| 17 |
)
|
| 18 |
from app.core.auth import require_permission, CurrentUser
|
| 19 |
from app.core.supabase import supabase_admin
|
|
|
|
| 21 |
router = APIRouter(prefix="/clients", tags=["Clients"])
|
| 22 |
|
| 23 |
|
| 24 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 25 |
+
# CRUD CLIENTS
|
| 26 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 27 |
|
| 28 |
@router.post("/", response_model=ClientResponse, status_code=201)
|
| 29 |
async def create_client(
|
| 30 |
payload: ClientCreate,
|
| 31 |
espace_user: CurrentUser = Depends(require_permission("client:write")),
|
| 32 |
):
|
| 33 |
+
"""Crée un nouveau client dans l'espace."""
|
| 34 |
+
# Validation PM : forme_juridique et representant_legal obligatoires
|
| 35 |
+
if payload.statut == "PM":
|
| 36 |
+
if not payload.forme_juridique:
|
| 37 |
+
raise HTTPException(
|
| 38 |
+
status_code=400,
|
| 39 |
+
detail="La forme juridique est obligatoire pour une personne morale"
|
| 40 |
+
)
|
| 41 |
+
if not payload.representant_legal:
|
| 42 |
+
raise HTTPException(
|
| 43 |
+
status_code=400,
|
| 44 |
+
detail="Le représentant légal est obligatoire pour une personne morale"
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
data = payload.model_dump()
|
| 48 |
data["espace_id"] = espace_user.espace_id
|
| 49 |
+
data["is_archived"] = False
|
| 50 |
+
|
| 51 |
response = supabase_admin.table("clients").insert(data).execute()
|
| 52 |
if not response.data:
|
| 53 |
raise HTTPException(
|
|
|
|
| 55 |
return response.data[0]
|
| 56 |
|
| 57 |
|
| 58 |
+
@router.get("/", response_model=PaginatedResponse[ClientResponse])
|
| 59 |
async def list_clients(
|
| 60 |
+
page: int = Query(1, ge=1, description="Numéro de page"),
|
| 61 |
+
limit: int = Query(20, ge=1, le=100, description="Éléments par page"),
|
| 62 |
+
search: Optional[str] = Query(
|
| 63 |
+
None, description="Recherche sur nom, email, téléphone"),
|
| 64 |
+
type: Optional[str] = Query(
|
| 65 |
+
None, pattern="^(PP|PM)$", description="Filtrer par statut"),
|
| 66 |
espace_user: CurrentUser = Depends(require_permission("client:read")),
|
| 67 |
):
|
| 68 |
+
"""Liste les clients de l'espace avec pagination et filtres."""
|
| 69 |
+
query = (
|
| 70 |
supabase_admin.table("clients")
|
| 71 |
+
.select("*", count="exact")
|
| 72 |
.eq("espace_id", espace_user.espace_id)
|
| 73 |
+
.eq("is_archived", False)
|
|
|
|
| 74 |
)
|
| 75 |
+
|
| 76 |
+
# Filtres
|
| 77 |
+
if type:
|
| 78 |
+
query = query.eq("statut", type)
|
| 79 |
+
if search:
|
| 80 |
+
query = query.or_(
|
| 81 |
+
f"raison_sociale.ilike.%{search}%,"
|
| 82 |
+
f"email_principal.ilike.%{search}%,"
|
| 83 |
+
f"telephone.ilike.%{search}%"
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
# Pagination
|
| 87 |
+
offset = (page - 1) * limit
|
| 88 |
+
query = query.order("raison_sociale").range(offset, offset + limit - 1)
|
| 89 |
+
|
| 90 |
+
response = query.execute()
|
| 91 |
+
total = response.count or 0
|
| 92 |
+
|
| 93 |
+
return {
|
| 94 |
+
"data": response.data or [],
|
| 95 |
+
"total": total,
|
| 96 |
+
"page": page,
|
| 97 |
+
"limit": limit,
|
| 98 |
+
"pages": ceil(total / limit) if total > 0 else 1,
|
| 99 |
+
}
|
| 100 |
|
| 101 |
|
| 102 |
@router.get("/{client_id}", response_model=ClientResponse)
|
|
|
|
| 104 |
client_id: UUID,
|
| 105 |
espace_user: CurrentUser = Depends(require_permission("client:read")),
|
| 106 |
):
|
| 107 |
+
"""Récupère un client par son ID."""
|
| 108 |
response = (
|
| 109 |
supabase_admin.table("clients")
|
| 110 |
.select("*")
|
| 111 |
.eq("id", str(client_id))
|
| 112 |
.eq("espace_id", espace_user.espace_id)
|
| 113 |
+
.eq("is_archived", False)
|
| 114 |
.single()
|
| 115 |
.execute()
|
| 116 |
)
|
|
|
|
| 125 |
payload: ClientUpdate,
|
| 126 |
espace_user: CurrentUser = Depends(require_permission("client:write")),
|
| 127 |
):
|
| 128 |
+
"""Met à jour un client."""
|
| 129 |
data = payload.model_dump(exclude_none=True)
|
| 130 |
if not data:
|
| 131 |
raise HTTPException(status_code=400, detail="Aucune donnée à modifier")
|
| 132 |
+
|
| 133 |
response = (
|
| 134 |
supabase_admin.table("clients")
|
| 135 |
.update(data)
|
| 136 |
.eq("id", str(client_id))
|
| 137 |
.eq("espace_id", espace_user.espace_id)
|
| 138 |
+
.eq("is_archived", False)
|
| 139 |
.execute()
|
| 140 |
)
|
| 141 |
if not response.data:
|
|
|
|
| 144 |
|
| 145 |
|
| 146 |
@router.delete("/{client_id}", response_model=MessageResponse)
|
| 147 |
+
async def archive_client(
|
| 148 |
client_id: UUID,
|
| 149 |
espace_user: CurrentUser = Depends(require_permission("client:delete")),
|
| 150 |
):
|
| 151 |
+
"""Archive un client (soft delete)."""
|
| 152 |
+
response = (
|
| 153 |
+
supabase_admin.table("clients")
|
| 154 |
+
.update({
|
| 155 |
+
"is_archived": True,
|
| 156 |
+
"archived_at": datetime.now(timezone.utc).isoformat(),
|
| 157 |
+
})
|
| 158 |
+
.eq("id", str(client_id))
|
| 159 |
+
.eq("espace_id", espace_user.espace_id)
|
| 160 |
+
.eq("is_archived", False)
|
| 161 |
+
.execute()
|
| 162 |
+
)
|
| 163 |
+
if not response.data:
|
| 164 |
+
raise HTTPException(status_code=404, detail="Client introuvable")
|
| 165 |
+
return {"message": "Client archivé"}
|
| 166 |
|
| 167 |
|
| 168 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 169 |
+
# VUE 360° CLIENT
|
| 170 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 171 |
+
|
| 172 |
+
@router.get("/{client_id}/vue360", response_model=Vue360Response)
|
| 173 |
async def vue_360(
|
| 174 |
client_id: UUID,
|
| 175 |
espace_user: CurrentUser = Depends(require_permission("client:read")),
|
| 176 |
):
|
| 177 |
+
"""
|
| 178 |
+
Vue 360° d'un client : informations, dossiers, paiements, contacts.
|
| 179 |
+
Affiche uniquement les éléments non archivés.
|
| 180 |
+
"""
|
| 181 |
+
# Client
|
| 182 |
client = (
|
| 183 |
supabase_admin.table("clients")
|
| 184 |
.select("*")
|
| 185 |
.eq("id", str(client_id))
|
| 186 |
.eq("espace_id", espace_user.espace_id)
|
| 187 |
+
.eq("is_archived", False)
|
| 188 |
.single()
|
| 189 |
.execute()
|
| 190 |
)
|
| 191 |
if not client.data:
|
| 192 |
raise HTTPException(status_code=404, detail="Client introuvable")
|
| 193 |
|
| 194 |
+
# Dossiers
|
| 195 |
+
dossiers = (
|
| 196 |
+
supabase_admin.table("dossiers")
|
| 197 |
+
.select("*")
|
| 198 |
+
.eq("client_id", str(client_id))
|
| 199 |
+
.eq("espace_id", espace_user.espace_id)
|
| 200 |
+
.eq("is_archived", False)
|
| 201 |
+
.order("created_at", desc=True)
|
| 202 |
+
.execute()
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
# Paiements
|
| 206 |
+
paiements = (
|
| 207 |
+
supabase_admin.table("paiements")
|
| 208 |
+
.select("*")
|
| 209 |
+
.eq("client_id", str(client_id))
|
| 210 |
+
.eq("espace_id", espace_user.espace_id)
|
| 211 |
+
.eq("is_archived", False)
|
| 212 |
+
.order("date_reception", desc=True)
|
| 213 |
+
.execute()
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
# Points de contact
|
| 217 |
+
contacts = (
|
| 218 |
+
supabase_admin.table("points_de_contact")
|
| 219 |
+
.select("*")
|
| 220 |
+
.eq("client_id", str(client_id))
|
| 221 |
+
.eq("espace_id", espace_user.espace_id)
|
| 222 |
+
.eq("is_archived", False)
|
| 223 |
+
.execute()
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
# Calcul total perçu
|
| 227 |
+
total_percu = sum(p["montant"] for p in (paiements.data or []))
|
| 228 |
|
| 229 |
return {
|
| 230 |
"client": client.data,
|
| 231 |
"dossiers": dossiers.data or [],
|
| 232 |
"paiements": paiements.data or [],
|
| 233 |
"points_de_contact": contacts.data or [],
|
| 234 |
+
"total_percu": total_percu,
|
| 235 |
}
|
| 236 |
|
| 237 |
|
| 238 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 239 |
+
# POINTS DE CONTACT
|
| 240 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 241 |
|
| 242 |
@router.post("/{client_id}/contacts", response_model=PointDeContactResponse, status_code=201)
|
| 243 |
async def create_contact(
|
|
|
|
| 245 |
payload: PointDeContactCreate,
|
| 246 |
espace_user: CurrentUser = Depends(require_permission("client:write")),
|
| 247 |
):
|
| 248 |
+
"""Ajoute un point de contact à un client."""
|
| 249 |
+
# Vérifier que le client existe et appartient à l'espace
|
| 250 |
+
client_check = (
|
| 251 |
+
supabase_admin.table("clients")
|
| 252 |
+
.select("id")
|
| 253 |
+
.eq("id", str(client_id))
|
| 254 |
+
.eq("espace_id", espace_user.espace_id)
|
| 255 |
+
.eq("is_archived", False)
|
| 256 |
+
.single()
|
| 257 |
+
.execute()
|
| 258 |
+
)
|
| 259 |
+
if not client_check.data:
|
| 260 |
+
raise HTTPException(status_code=404, detail="Client introuvable")
|
| 261 |
+
|
| 262 |
data = payload.model_dump()
|
| 263 |
data["client_id"] = str(client_id)
|
| 264 |
data["espace_id"] = espace_user.espace_id
|
| 265 |
+
data["is_archived"] = False
|
| 266 |
+
|
| 267 |
response = supabase_admin.table("points_de_contact").insert(data).execute()
|
| 268 |
if not response.data:
|
| 269 |
raise HTTPException(
|
|
|
|
| 271 |
return response.data[0]
|
| 272 |
|
| 273 |
|
| 274 |
+
@router.get("/{client_id}/contacts", response_model=list[PointDeContactResponse])
|
| 275 |
async def list_contacts(
|
| 276 |
client_id: UUID,
|
| 277 |
espace_user: CurrentUser = Depends(require_permission("client:read")),
|
| 278 |
):
|
| 279 |
+
"""Liste les points de contact d'un client."""
|
| 280 |
response = (
|
| 281 |
supabase_admin.table("points_de_contact")
|
| 282 |
.select("*")
|
| 283 |
.eq("client_id", str(client_id))
|
| 284 |
.eq("espace_id", espace_user.espace_id)
|
| 285 |
+
.eq("is_archived", False)
|
| 286 |
.execute()
|
| 287 |
)
|
| 288 |
return response.data or []
|
|
|
|
| 295 |
payload: PointDeContactUpdate,
|
| 296 |
espace_user: CurrentUser = Depends(require_permission("client:write")),
|
| 297 |
):
|
| 298 |
+
"""Met à jour un point de contact."""
|
| 299 |
data = payload.model_dump(exclude_none=True)
|
| 300 |
if not data:
|
| 301 |
raise HTTPException(status_code=400, detail="Aucune donnée à modifier")
|
| 302 |
+
|
| 303 |
response = (
|
| 304 |
supabase_admin.table("points_de_contact")
|
| 305 |
.update(data)
|
| 306 |
.eq("id", str(contact_id))
|
| 307 |
.eq("client_id", str(client_id))
|
| 308 |
.eq("espace_id", espace_user.espace_id)
|
| 309 |
+
.eq("is_archived", False)
|
| 310 |
.execute()
|
| 311 |
)
|
| 312 |
if not response.data:
|
|
|
|
| 315 |
|
| 316 |
|
| 317 |
@router.delete("/{client_id}/contacts/{contact_id}", response_model=MessageResponse)
|
| 318 |
+
async def archive_contact(
|
| 319 |
client_id: UUID,
|
| 320 |
contact_id: UUID,
|
| 321 |
espace_user: CurrentUser = Depends(require_permission("client:delete")),
|
| 322 |
):
|
| 323 |
+
"""Archive un point de contact (soft delete)."""
|
| 324 |
+
response = (
|
| 325 |
+
supabase_admin.table("points_de_contact")
|
| 326 |
+
.update({
|
| 327 |
+
"is_archived": True,
|
| 328 |
+
"archived_at": datetime.now(timezone.utc).isoformat(),
|
| 329 |
+
})
|
| 330 |
+
.eq("id", str(contact_id))
|
| 331 |
+
.eq("client_id", str(client_id))
|
| 332 |
+
.eq("espace_id", espace_user.espace_id)
|
| 333 |
+
.eq("is_archived", False)
|
| 334 |
+
.execute()
|
| 335 |
+
)
|
| 336 |
+
if not response.data:
|
| 337 |
+
raise HTTPException(status_code=404, detail="Contact introuvable")
|
| 338 |
+
return {"message": "Contact archivé"}
|
app/routers/dossiers.py
CHANGED
|
@@ -1,12 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import random
|
| 2 |
import string
|
| 3 |
-
from typing import List
|
|
|
|
| 4 |
from uuid import UUID
|
| 5 |
-
from
|
|
|
|
|
|
|
|
|
|
| 6 |
from app.models.schemas import (
|
| 7 |
DossierCreate, DossierUpdate, DossierResponse,
|
| 8 |
EquipeDossierCreate, EquipeDossierUpdate, EquipeDossierResponse,
|
| 9 |
-
MessageResponse,
|
| 10 |
)
|
| 11 |
from app.core.auth import require_permission, CurrentUser
|
| 12 |
from app.core.supabase import supabase_admin
|
|
@@ -15,32 +24,47 @@ router = APIRouter(prefix="/dossiers", tags=["Dossiers"])
|
|
| 15 |
|
| 16 |
|
| 17 |
def _generate_reference() -> str:
|
|
|
|
| 18 |
suffix = "".join(random.choices(
|
| 19 |
string.ascii_uppercase + string.digits, k=6))
|
| 20 |
return f"DEL-{suffix}"
|
| 21 |
|
| 22 |
|
| 23 |
-
def _auto_titre(type_dossier: str, raison_sociale: str) -> str:
|
|
|
|
| 24 |
labels = {
|
| 25 |
"pre_contentieux": "Pré-contentieux",
|
| 26 |
"contentieux": "Contentieux",
|
| 27 |
"conseil": "Conseil",
|
| 28 |
"transactionnel": "Transactionnel",
|
| 29 |
}
|
| 30 |
-
|
| 31 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
@router.post("/", response_model=DossierResponse, status_code=201)
|
| 34 |
async def create_dossier(
|
| 35 |
payload: DossierCreate,
|
| 36 |
espace_user: CurrentUser = Depends(require_permission("dossier:write")),
|
| 37 |
):
|
| 38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
client_resp = (
|
| 40 |
supabase_admin.table("clients")
|
| 41 |
.select("raison_sociale")
|
| 42 |
.eq("id", str(payload.client_id))
|
| 43 |
.eq("espace_id", espace_user.espace_id)
|
|
|
|
| 44 |
.single()
|
| 45 |
.execute()
|
| 46 |
)
|
|
@@ -52,9 +76,15 @@ async def create_dossier(
|
|
| 52 |
data["espace_id"] = espace_user.espace_id
|
| 53 |
data["client_id"] = str(payload.client_id)
|
| 54 |
data["reference"] = _generate_reference()
|
|
|
|
|
|
|
|
|
|
| 55 |
if not data.get("titre"):
|
| 56 |
data["titre"] = _auto_titre(
|
| 57 |
-
payload.type,
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
response = supabase_admin.table("dossiers").insert(data).execute()
|
| 60 |
if not response.data:
|
|
@@ -63,18 +93,72 @@ async def create_dossier(
|
|
| 63 |
return response.data[0]
|
| 64 |
|
| 65 |
|
| 66 |
-
@router.get("/", response_model=
|
| 67 |
async def list_dossiers(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
espace_user: CurrentUser = Depends(require_permission("dossier:read")),
|
| 69 |
):
|
| 70 |
-
|
|
|
|
| 71 |
supabase_admin.table("dossiers")
|
| 72 |
-
.select("*")
|
| 73 |
.eq("espace_id", espace_user.espace_id)
|
| 74 |
-
.
|
| 75 |
-
.execute()
|
| 76 |
)
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
|
| 80 |
@router.get("/{dossier_id}", response_model=DossierResponse)
|
|
@@ -82,11 +166,13 @@ async def get_dossier(
|
|
| 82 |
dossier_id: UUID,
|
| 83 |
espace_user: CurrentUser = Depends(require_permission("dossier:read")),
|
| 84 |
):
|
|
|
|
| 85 |
response = (
|
| 86 |
supabase_admin.table("dossiers")
|
| 87 |
.select("*")
|
| 88 |
.eq("id", str(dossier_id))
|
| 89 |
.eq("espace_id", espace_user.espace_id)
|
|
|
|
| 90 |
.single()
|
| 91 |
.execute()
|
| 92 |
)
|
|
@@ -101,14 +187,17 @@ async def update_dossier(
|
|
| 101 |
payload: DossierUpdate,
|
| 102 |
espace_user: CurrentUser = Depends(require_permission("dossier:write")),
|
| 103 |
):
|
|
|
|
| 104 |
data = payload.model_dump(exclude_none=True)
|
| 105 |
if not data:
|
| 106 |
raise HTTPException(status_code=400, detail="Aucune donnée à modifier")
|
|
|
|
| 107 |
response = (
|
| 108 |
supabase_admin.table("dossiers")
|
| 109 |
.update(data)
|
| 110 |
.eq("id", str(dossier_id))
|
| 111 |
.eq("espace_id", espace_user.espace_id)
|
|
|
|
| 112 |
.execute()
|
| 113 |
)
|
| 114 |
if not response.data:
|
|
@@ -117,25 +206,48 @@ async def update_dossier(
|
|
| 117 |
|
| 118 |
|
| 119 |
@router.delete("/{dossier_id}", response_model=MessageResponse)
|
| 120 |
-
async def
|
| 121 |
dossier_id: UUID,
|
| 122 |
espace_user: CurrentUser = Depends(require_permission("dossier:delete")),
|
| 123 |
):
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
|
|
|
|
|
|
|
|
|
|
| 128 |
|
| 129 |
-
@router.get("/{dossier_id}/recapitulatif")
|
| 130 |
async def recapitulatif_financier(
|
| 131 |
dossier_id: UUID,
|
| 132 |
espace_user: CurrentUser = Depends(require_permission("dossier:read")),
|
| 133 |
):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
dossier = (
|
| 135 |
supabase_admin.table("dossiers")
|
| 136 |
.select("*")
|
| 137 |
.eq("id", str(dossier_id))
|
| 138 |
.eq("espace_id", espace_user.espace_id)
|
|
|
|
| 139 |
.single()
|
| 140 |
.execute()
|
| 141 |
)
|
|
@@ -147,6 +259,7 @@ async def recapitulatif_financier(
|
|
| 147 |
.select("montant, type, date_reception, description")
|
| 148 |
.eq("dossier_id", str(dossier_id))
|
| 149 |
.eq("espace_id", espace_user.espace_id)
|
|
|
|
| 150 |
.order("date_reception", desc=True)
|
| 151 |
.execute()
|
| 152 |
)
|
|
@@ -155,17 +268,19 @@ async def recapitulatif_financier(
|
|
| 155 |
revenu_attendu = dossier.data.get("revenu_attendu") or 0
|
| 156 |
|
| 157 |
return {
|
| 158 |
-
"dossier_id":
|
| 159 |
-
"reference":
|
| 160 |
-
"titre":
|
| 161 |
-
"revenu_attendu":
|
| 162 |
-
"total_percu":
|
| 163 |
"reste_a_percevoir": revenu_attendu - total_percu,
|
| 164 |
-
"paiements":
|
| 165 |
}
|
| 166 |
|
| 167 |
|
| 168 |
-
#
|
|
|
|
|
|
|
| 169 |
|
| 170 |
@router.post("/{dossier_id}/equipe", response_model=EquipeDossierResponse, status_code=201)
|
| 171 |
async def add_membre_equipe(
|
|
@@ -174,16 +289,30 @@ async def add_membre_equipe(
|
|
| 174 |
espace_user: CurrentUser = Depends(
|
| 175 |
require_permission("equipe_dossier:write")),
|
| 176 |
):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
# Vérifier que l'utilisateur invité est bien membre de l'espace
|
| 178 |
-
|
| 179 |
-
supabase_admin.table("
|
| 180 |
-
.select("
|
|
|
|
| 181 |
.eq("espace_id", espace_user.espace_id)
|
| 182 |
-
.eq("utilisateur_id", str(payload.utilisateur_id))
|
| 183 |
.single()
|
| 184 |
.execute()
|
| 185 |
)
|
| 186 |
-
if not
|
| 187 |
raise HTTPException(
|
| 188 |
status_code=400, detail="Cet utilisateur n'est pas membre de l'espace")
|
| 189 |
|
|
@@ -192,10 +321,17 @@ async def add_membre_equipe(
|
|
| 192 |
"utilisateur_id": str(payload.utilisateur_id),
|
| 193 |
"role": payload.role.value,
|
| 194 |
}
|
| 195 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
if not response.data:
|
| 197 |
raise HTTPException(
|
| 198 |
-
status_code=500, detail="Échec
|
| 199 |
return response.data[0]
|
| 200 |
|
| 201 |
|
|
@@ -204,6 +340,7 @@ async def list_equipe(
|
|
| 204 |
dossier_id: UUID,
|
| 205 |
espace_user: CurrentUser = Depends(require_permission("dossier:read")),
|
| 206 |
):
|
|
|
|
| 207 |
response = (
|
| 208 |
supabase_admin.table("equipe_dossier")
|
| 209 |
.select("*, utilisateurs(nom, prenom, email, role_cabinet)")
|
|
@@ -221,11 +358,13 @@ async def update_membre_equipe(
|
|
| 221 |
espace_user: CurrentUser = Depends(
|
| 222 |
require_permission("equipe_dossier:write")),
|
| 223 |
):
|
| 224 |
-
|
|
|
|
| 225 |
if espace_user.role_cabinet.value != "associe_gerant":
|
| 226 |
raise HTTPException(
|
| 227 |
status_code=403,
|
| 228 |
-
detail="Seul l'associé gérant peut changer le rôle d'un membre"
|
|
|
|
| 229 |
|
| 230 |
response = (
|
| 231 |
supabase_admin.table("equipe_dossier")
|
|
@@ -247,6 +386,12 @@ async def remove_membre_equipe(
|
|
| 247 |
espace_user: CurrentUser = Depends(
|
| 248 |
require_permission("equipe_dossier:write")),
|
| 249 |
):
|
| 250 |
-
|
| 251 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 252 |
return {"message": "Membre retiré de l'équipe"}
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Dedalys Backend — Router Dossiers
|
| 3 |
+
CRUD dossiers, gestion équipe, récapitulatif financier, soft delete, pagination.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
import random
|
| 7 |
import string
|
| 8 |
+
from typing import Optional, List
|
| 9 |
+
from math import ceil
|
| 10 |
from uuid import UUID
|
| 11 |
+
from datetime import datetime, timezone
|
| 12 |
+
|
| 13 |
+
from fastapi import APIRouter, HTTPException, Depends, Query
|
| 14 |
+
|
| 15 |
from app.models.schemas import (
|
| 16 |
DossierCreate, DossierUpdate, DossierResponse,
|
| 17 |
EquipeDossierCreate, EquipeDossierUpdate, EquipeDossierResponse,
|
| 18 |
+
PaginatedResponse, MessageResponse, RecapitulatifFinancierResponse,
|
| 19 |
)
|
| 20 |
from app.core.auth import require_permission, CurrentUser
|
| 21 |
from app.core.supabase import supabase_admin
|
|
|
|
| 24 |
|
| 25 |
|
| 26 |
def _generate_reference() -> str:
|
| 27 |
+
"""Génère une référence unique au format DEL-XXXXXX."""
|
| 28 |
suffix = "".join(random.choices(
|
| 29 |
string.ascii_uppercase + string.digits, k=6))
|
| 30 |
return f"DEL-{suffix}"
|
| 31 |
|
| 32 |
|
| 33 |
+
def _auto_titre(type_dossier: str, raison_sociale: str, partie_adverse: Optional[str] = None) -> str:
|
| 34 |
+
"""Génère un titre automatique pour le dossier."""
|
| 35 |
labels = {
|
| 36 |
"pre_contentieux": "Pré-contentieux",
|
| 37 |
"contentieux": "Contentieux",
|
| 38 |
"conseil": "Conseil",
|
| 39 |
"transactionnel": "Transactionnel",
|
| 40 |
}
|
| 41 |
+
type_label = labels.get(type_dossier, type_dossier)
|
| 42 |
|
| 43 |
+
if partie_adverse:
|
| 44 |
+
return f"{raison_sociale} c/ {partie_adverse} – {type_label}"
|
| 45 |
+
return f"{raison_sociale} – {type_label}"
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 49 |
+
# CRUD DOSSIERS
|
| 50 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 51 |
|
| 52 |
@router.post("/", response_model=DossierResponse, status_code=201)
|
| 53 |
async def create_dossier(
|
| 54 |
payload: DossierCreate,
|
| 55 |
espace_user: CurrentUser = Depends(require_permission("dossier:write")),
|
| 56 |
):
|
| 57 |
+
"""
|
| 58 |
+
Crée un nouveau dossier.
|
| 59 |
+
Accessible aux avocats, juristes, associés gérants et office managers.
|
| 60 |
+
"""
|
| 61 |
+
# Vérifier que le client appartient à cet espace et n'est pas archivé
|
| 62 |
client_resp = (
|
| 63 |
supabase_admin.table("clients")
|
| 64 |
.select("raison_sociale")
|
| 65 |
.eq("id", str(payload.client_id))
|
| 66 |
.eq("espace_id", espace_user.espace_id)
|
| 67 |
+
.eq("is_archived", False)
|
| 68 |
.single()
|
| 69 |
.execute()
|
| 70 |
)
|
|
|
|
| 76 |
data["espace_id"] = espace_user.espace_id
|
| 77 |
data["client_id"] = str(payload.client_id)
|
| 78 |
data["reference"] = _generate_reference()
|
| 79 |
+
data["is_archived"] = False
|
| 80 |
+
|
| 81 |
+
# Générer le titre si non fourni
|
| 82 |
if not data.get("titre"):
|
| 83 |
data["titre"] = _auto_titre(
|
| 84 |
+
payload.type,
|
| 85 |
+
client_resp.data["raison_sociale"],
|
| 86 |
+
payload.partie_adverse
|
| 87 |
+
)
|
| 88 |
|
| 89 |
response = supabase_admin.table("dossiers").insert(data).execute()
|
| 90 |
if not response.data:
|
|
|
|
| 93 |
return response.data[0]
|
| 94 |
|
| 95 |
|
| 96 |
+
@router.get("/", response_model=PaginatedResponse[DossierResponse])
|
| 97 |
async def list_dossiers(
|
| 98 |
+
page: int = Query(1, ge=1),
|
| 99 |
+
limit: int = Query(20, ge=1, le=100),
|
| 100 |
+
search: Optional[str] = Query(
|
| 101 |
+
None, description="Recherche sur titre, description, référence"),
|
| 102 |
+
statut: Optional[str] = Query(
|
| 103 |
+
None, pattern="^(ouvert|en_instance|cloture)$"),
|
| 104 |
+
type: Optional[str] = Query(
|
| 105 |
+
None, pattern="^(pre_contentieux|contentieux|conseil|transactionnel)$"),
|
| 106 |
+
client_id: Optional[UUID] = Query(None, description="Filtrer par client"),
|
| 107 |
+
avocat_id: Optional[UUID] = Query(
|
| 108 |
+
None, description="Filtrer par avocat assigné"),
|
| 109 |
espace_user: CurrentUser = Depends(require_permission("dossier:read")),
|
| 110 |
):
|
| 111 |
+
"""Liste les dossiers avec pagination et filtres."""
|
| 112 |
+
query = (
|
| 113 |
supabase_admin.table("dossiers")
|
| 114 |
+
.select("*", count="exact")
|
| 115 |
.eq("espace_id", espace_user.espace_id)
|
| 116 |
+
.eq("is_archived", False)
|
|
|
|
| 117 |
)
|
| 118 |
+
|
| 119 |
+
# Filtres simples
|
| 120 |
+
if statut:
|
| 121 |
+
query = query.eq("statut", statut)
|
| 122 |
+
if type:
|
| 123 |
+
query = query.eq("type", type)
|
| 124 |
+
if client_id:
|
| 125 |
+
query = query.eq("client_id", str(client_id))
|
| 126 |
+
if search:
|
| 127 |
+
query = query.or_(
|
| 128 |
+
f"titre.ilike.%{search}%,"
|
| 129 |
+
f"description.ilike.%{search}%,"
|
| 130 |
+
f"reference.ilike.%{search}%"
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
# Filtre par avocat (via équipe)
|
| 134 |
+
if avocat_id:
|
| 135 |
+
equipe_resp = (
|
| 136 |
+
supabase_admin.table("equipe_dossier")
|
| 137 |
+
.select("dossier_id")
|
| 138 |
+
.eq("utilisateur_id", str(avocat_id))
|
| 139 |
+
.execute()
|
| 140 |
+
)
|
| 141 |
+
dossier_ids = [e["dossier_id"] for e in (equipe_resp.data or [])]
|
| 142 |
+
if dossier_ids:
|
| 143 |
+
query = query.in_("id", dossier_ids)
|
| 144 |
+
else:
|
| 145 |
+
return {"data": [], "total": 0, "page": page, "limit": limit, "pages": 1}
|
| 146 |
+
|
| 147 |
+
# Pagination
|
| 148 |
+
offset = (page - 1) * limit
|
| 149 |
+
query = query.order("created_at", desc=True).range(
|
| 150 |
+
offset, offset + limit - 1)
|
| 151 |
+
|
| 152 |
+
response = query.execute()
|
| 153 |
+
total = response.count or 0
|
| 154 |
+
|
| 155 |
+
return {
|
| 156 |
+
"data": response.data or [],
|
| 157 |
+
"total": total,
|
| 158 |
+
"page": page,
|
| 159 |
+
"limit": limit,
|
| 160 |
+
"pages": ceil(total / limit) if total > 0 else 1,
|
| 161 |
+
}
|
| 162 |
|
| 163 |
|
| 164 |
@router.get("/{dossier_id}", response_model=DossierResponse)
|
|
|
|
| 166 |
dossier_id: UUID,
|
| 167 |
espace_user: CurrentUser = Depends(require_permission("dossier:read")),
|
| 168 |
):
|
| 169 |
+
"""Récupère un dossier par son ID."""
|
| 170 |
response = (
|
| 171 |
supabase_admin.table("dossiers")
|
| 172 |
.select("*")
|
| 173 |
.eq("id", str(dossier_id))
|
| 174 |
.eq("espace_id", espace_user.espace_id)
|
| 175 |
+
.eq("is_archived", False)
|
| 176 |
.single()
|
| 177 |
.execute()
|
| 178 |
)
|
|
|
|
| 187 |
payload: DossierUpdate,
|
| 188 |
espace_user: CurrentUser = Depends(require_permission("dossier:write")),
|
| 189 |
):
|
| 190 |
+
"""Met à jour un dossier."""
|
| 191 |
data = payload.model_dump(exclude_none=True)
|
| 192 |
if not data:
|
| 193 |
raise HTTPException(status_code=400, detail="Aucune donnée à modifier")
|
| 194 |
+
|
| 195 |
response = (
|
| 196 |
supabase_admin.table("dossiers")
|
| 197 |
.update(data)
|
| 198 |
.eq("id", str(dossier_id))
|
| 199 |
.eq("espace_id", espace_user.espace_id)
|
| 200 |
+
.eq("is_archived", False)
|
| 201 |
.execute()
|
| 202 |
)
|
| 203 |
if not response.data:
|
|
|
|
| 206 |
|
| 207 |
|
| 208 |
@router.delete("/{dossier_id}", response_model=MessageResponse)
|
| 209 |
+
async def archive_dossier(
|
| 210 |
dossier_id: UUID,
|
| 211 |
espace_user: CurrentUser = Depends(require_permission("dossier:delete")),
|
| 212 |
):
|
| 213 |
+
"""Archive un dossier (soft delete). Réservé aux associés gérants."""
|
| 214 |
+
response = (
|
| 215 |
+
supabase_admin.table("dossiers")
|
| 216 |
+
.update({
|
| 217 |
+
"is_archived": True,
|
| 218 |
+
"archived_at": datetime.now(timezone.utc).isoformat(),
|
| 219 |
+
})
|
| 220 |
+
.eq("id", str(dossier_id))
|
| 221 |
+
.eq("espace_id", espace_user.espace_id)
|
| 222 |
+
.eq("is_archived", False)
|
| 223 |
+
.execute()
|
| 224 |
+
)
|
| 225 |
+
if not response.data:
|
| 226 |
+
raise HTTPException(status_code=404, detail="Dossier introuvable")
|
| 227 |
+
return {"message": "Dossier archivé"}
|
| 228 |
+
|
| 229 |
|
| 230 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 231 |
+
# RÉCAPITULATIF FINANCIER
|
| 232 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 233 |
|
| 234 |
+
@router.get("/{dossier_id}/recapitulatif", response_model=RecapitulatifFinancierResponse)
|
| 235 |
async def recapitulatif_financier(
|
| 236 |
dossier_id: UUID,
|
| 237 |
espace_user: CurrentUser = Depends(require_permission("dossier:read")),
|
| 238 |
):
|
| 239 |
+
"""
|
| 240 |
+
Récapitulatif financier d'un dossier :
|
| 241 |
+
- Revenu attendu (forfait ou budget capped fees)
|
| 242 |
+
- Total perçu (somme des paiements)
|
| 243 |
+
- Reste à percevoir
|
| 244 |
+
"""
|
| 245 |
dossier = (
|
| 246 |
supabase_admin.table("dossiers")
|
| 247 |
.select("*")
|
| 248 |
.eq("id", str(dossier_id))
|
| 249 |
.eq("espace_id", espace_user.espace_id)
|
| 250 |
+
.eq("is_archived", False)
|
| 251 |
.single()
|
| 252 |
.execute()
|
| 253 |
)
|
|
|
|
| 259 |
.select("montant, type, date_reception, description")
|
| 260 |
.eq("dossier_id", str(dossier_id))
|
| 261 |
.eq("espace_id", espace_user.espace_id)
|
| 262 |
+
.eq("is_archived", False)
|
| 263 |
.order("date_reception", desc=True)
|
| 264 |
.execute()
|
| 265 |
)
|
|
|
|
| 268 |
revenu_attendu = dossier.data.get("revenu_attendu") or 0
|
| 269 |
|
| 270 |
return {
|
| 271 |
+
"dossier_id": dossier_id,
|
| 272 |
+
"reference": dossier.data["reference"],
|
| 273 |
+
"titre": dossier.data.get("titre"),
|
| 274 |
+
"revenu_attendu": revenu_attendu,
|
| 275 |
+
"total_percu": total_percu,
|
| 276 |
"reste_a_percevoir": revenu_attendu - total_percu,
|
| 277 |
+
"paiements": paiements.data or [],
|
| 278 |
}
|
| 279 |
|
| 280 |
|
| 281 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 282 |
+
# ÉQUIPE DOSSIER
|
| 283 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 284 |
|
| 285 |
@router.post("/{dossier_id}/equipe", response_model=EquipeDossierResponse, status_code=201)
|
| 286 |
async def add_membre_equipe(
|
|
|
|
| 289 |
espace_user: CurrentUser = Depends(
|
| 290 |
require_permission("equipe_dossier:write")),
|
| 291 |
):
|
| 292 |
+
"""Ajoute un membre à l'équipe du dossier."""
|
| 293 |
+
# Vérifier que le dossier appartient à l'espace
|
| 294 |
+
dossier_check = (
|
| 295 |
+
supabase_admin.table("dossiers")
|
| 296 |
+
.select("id")
|
| 297 |
+
.eq("id", str(dossier_id))
|
| 298 |
+
.eq("espace_id", espace_user.espace_id)
|
| 299 |
+
.eq("is_archived", False)
|
| 300 |
+
.single()
|
| 301 |
+
.execute()
|
| 302 |
+
)
|
| 303 |
+
if not dossier_check.data:
|
| 304 |
+
raise HTTPException(status_code=404, detail="Dossier introuvable")
|
| 305 |
+
|
| 306 |
# Vérifier que l'utilisateur invité est bien membre de l'espace
|
| 307 |
+
user_check = (
|
| 308 |
+
supabase_admin.table("utilisateurs")
|
| 309 |
+
.select("id")
|
| 310 |
+
.eq("id", str(payload.utilisateur_id))
|
| 311 |
.eq("espace_id", espace_user.espace_id)
|
|
|
|
| 312 |
.single()
|
| 313 |
.execute()
|
| 314 |
)
|
| 315 |
+
if not user_check.data:
|
| 316 |
raise HTTPException(
|
| 317 |
status_code=400, detail="Cet utilisateur n'est pas membre de l'espace")
|
| 318 |
|
|
|
|
| 321 |
"utilisateur_id": str(payload.utilisateur_id),
|
| 322 |
"role": payload.role.value,
|
| 323 |
}
|
| 324 |
+
|
| 325 |
+
try:
|
| 326 |
+
response = supabase_admin.table(
|
| 327 |
+
"equipe_dossier").insert(data).execute()
|
| 328 |
+
except Exception:
|
| 329 |
+
raise HTTPException(
|
| 330 |
+
status_code=409, detail="Cet utilisateur est déjà dans l'équipe")
|
| 331 |
+
|
| 332 |
if not response.data:
|
| 333 |
raise HTTPException(
|
| 334 |
+
status_code=500, detail="Échec de l'ajout à l'équipe")
|
| 335 |
return response.data[0]
|
| 336 |
|
| 337 |
|
|
|
|
| 340 |
dossier_id: UUID,
|
| 341 |
espace_user: CurrentUser = Depends(require_permission("dossier:read")),
|
| 342 |
):
|
| 343 |
+
"""Liste les membres de l'équipe d'un dossier."""
|
| 344 |
response = (
|
| 345 |
supabase_admin.table("equipe_dossier")
|
| 346 |
.select("*, utilisateurs(nom, prenom, email, role_cabinet)")
|
|
|
|
| 358 |
espace_user: CurrentUser = Depends(
|
| 359 |
require_permission("equipe_dossier:write")),
|
| 360 |
):
|
| 361 |
+
"""Met à jour le rôle d'un membre de l'équipe. Réservé aux associés gérants."""
|
| 362 |
+
# Seul associe_gerant peut changer le rôle
|
| 363 |
if espace_user.role_cabinet.value != "associe_gerant":
|
| 364 |
raise HTTPException(
|
| 365 |
status_code=403,
|
| 366 |
+
detail="Seul l'associé gérant peut changer le rôle d'un membre"
|
| 367 |
+
)
|
| 368 |
|
| 369 |
response = (
|
| 370 |
supabase_admin.table("equipe_dossier")
|
|
|
|
| 386 |
espace_user: CurrentUser = Depends(
|
| 387 |
require_permission("equipe_dossier:write")),
|
| 388 |
):
|
| 389 |
+
"""Retire un membre de l'équipe du dossier."""
|
| 390 |
+
response = (
|
| 391 |
+
supabase_admin.table("equipe_dossier")
|
| 392 |
+
.delete()
|
| 393 |
+
.eq("dossier_id", str(dossier_id))
|
| 394 |
+
.eq("utilisateur_id", str(utilisateur_id))
|
| 395 |
+
.execute()
|
| 396 |
+
)
|
| 397 |
return {"message": "Membre retiré de l'équipe"}
|
app/routers/espaces.py
CHANGED
|
@@ -1,12 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from typing import List
|
| 2 |
from uuid import UUID
|
|
|
|
|
|
|
| 3 |
from fastapi import APIRouter, HTTPException, Depends
|
|
|
|
| 4 |
from app.models.schemas import (
|
| 5 |
EspaceCreate, EspaceUpdate, EspaceResponse, EspaceDetailResponse,
|
| 6 |
UtilisateurCreate, UtilisateurResponse, MessageResponse,
|
| 7 |
)
|
| 8 |
from app.core.auth import require_superadmin, CurrentUser
|
| 9 |
-
from app.core.supabase import
|
| 10 |
|
| 11 |
router = APIRouter(prefix="/espaces", tags=["Espaces (Superadmin)"])
|
| 12 |
|
|
@@ -16,9 +24,10 @@ async def create_espace(
|
|
| 16 |
payload: EspaceCreate,
|
| 17 |
_: CurrentUser = Depends(require_superadmin),
|
| 18 |
):
|
| 19 |
-
"""Crée un espace (
|
| 20 |
-
|
| 21 |
-
|
|
|
|
| 22 |
if not response.data:
|
| 23 |
raise HTTPException(
|
| 24 |
status_code=500, detail="Échec de la création de l'espace")
|
|
@@ -26,10 +35,17 @@ async def create_espace(
|
|
| 26 |
|
| 27 |
|
| 28 |
@router.get("/", response_model=List[EspaceResponse])
|
| 29 |
-
async def list_espaces(
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
return response.data or []
|
| 34 |
|
| 35 |
|
|
@@ -38,24 +54,30 @@ async def get_espace(
|
|
| 38 |
espace_id: UUID,
|
| 39 |
_: CurrentUser = Depends(require_superadmin),
|
| 40 |
):
|
| 41 |
-
"""
|
| 42 |
-
|
| 43 |
supabase_admin.table("espaces")
|
| 44 |
.select("*")
|
| 45 |
.eq("id", str(espace_id))
|
|
|
|
| 46 |
.single()
|
| 47 |
.execute()
|
| 48 |
)
|
| 49 |
-
if not
|
| 50 |
raise HTTPException(status_code=404, detail="Espace introuvable")
|
| 51 |
|
| 52 |
-
|
| 53 |
supabase_admin.table("utilisateurs")
|
| 54 |
.select("*")
|
| 55 |
.eq("espace_id", str(espace_id))
|
|
|
|
| 56 |
.execute()
|
| 57 |
)
|
| 58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
|
| 60 |
|
| 61 |
@router.patch("/{espace_id}", response_model=EspaceResponse)
|
|
@@ -64,11 +86,16 @@ async def update_espace(
|
|
| 64 |
payload: EspaceUpdate,
|
| 65 |
_: CurrentUser = Depends(require_superadmin),
|
| 66 |
):
|
| 67 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
response = (
|
| 69 |
supabase_admin.table("espaces")
|
| 70 |
-
.update(
|
| 71 |
.eq("id", str(espace_id))
|
|
|
|
| 72 |
.execute()
|
| 73 |
)
|
| 74 |
if not response.data:
|
|
@@ -77,81 +104,101 @@ async def update_espace(
|
|
| 77 |
|
| 78 |
|
| 79 |
@router.delete("/{espace_id}", response_model=MessageResponse)
|
| 80 |
-
async def
|
| 81 |
espace_id: UUID,
|
| 82 |
_: CurrentUser = Depends(require_superadmin),
|
| 83 |
):
|
| 84 |
-
"""
|
| 85 |
-
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
|
| 88 |
|
| 89 |
-
#
|
|
|
|
|
|
|
| 90 |
|
| 91 |
@router.post("/{espace_id}/utilisateurs", response_model=UtilisateurResponse, status_code=201)
|
| 92 |
-
async def
|
| 93 |
espace_id: UUID,
|
| 94 |
payload: UtilisateurCreate,
|
| 95 |
_: CurrentUser = Depends(require_superadmin),
|
| 96 |
):
|
| 97 |
"""
|
| 98 |
-
Crée un utilisateur et l'
|
| 99 |
-
|
| 100 |
-
associe_gerant / office_manager → admin
|
| 101 |
-
avocat / juriste → membre simple
|
| 102 |
-
Superadmin uniquement.
|
| 103 |
"""
|
| 104 |
-
|
|
|
|
| 105 |
supabase_admin.table("espaces")
|
| 106 |
.select("id")
|
| 107 |
.eq("id", str(espace_id))
|
|
|
|
| 108 |
.single()
|
| 109 |
.execute()
|
| 110 |
)
|
| 111 |
-
if not
|
| 112 |
raise HTTPException(status_code=404, detail="Espace introuvable")
|
| 113 |
|
| 114 |
-
# Créer dans Supabase Auth
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
|
|
|
| 121 |
raise HTTPException(
|
| 122 |
-
status_code=400, detail="
|
| 123 |
|
| 124 |
-
|
|
|
|
|
|
|
| 125 |
|
| 126 |
-
# Créer le profil
|
| 127 |
-
|
| 128 |
-
"id":
|
| 129 |
-
"email":
|
| 130 |
-
"nom":
|
| 131 |
-
"prenom":
|
| 132 |
"role_cabinet": payload.role_cabinet.value,
|
| 133 |
-
"espace_id":
|
| 134 |
"is_superadmin": False,
|
| 135 |
}
|
| 136 |
-
profile_resp = supabase_admin.table(
|
| 137 |
-
"utilisateurs").insert(profile).execute()
|
| 138 |
|
|
|
|
|
|
|
| 139 |
if not profile_resp.data:
|
| 140 |
-
|
|
|
|
| 141 |
raise HTTPException(
|
| 142 |
-
status_code=500, detail="Échec
|
| 143 |
|
| 144 |
return profile_resp.data[0]
|
| 145 |
|
| 146 |
|
| 147 |
@router.delete("/{espace_id}/utilisateurs/{utilisateur_id}", response_model=MessageResponse)
|
| 148 |
-
async def
|
| 149 |
espace_id: UUID,
|
| 150 |
utilisateur_id: UUID,
|
| 151 |
_: CurrentUser = Depends(require_superadmin),
|
| 152 |
):
|
| 153 |
-
"""
|
| 154 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
supabase_admin.table("utilisateurs")
|
| 156 |
.select("id")
|
| 157 |
.eq("id", str(utilisateur_id))
|
|
@@ -159,9 +206,18 @@ async def retirer_utilisateur(
|
|
| 159 |
.single()
|
| 160 |
.execute()
|
| 161 |
)
|
| 162 |
-
if not
|
| 163 |
raise HTTPException(
|
| 164 |
status_code=404, detail="Utilisateur introuvable dans cet espace")
|
| 165 |
|
| 166 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
return {"message": "Utilisateur supprimé"}
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Dedalys Backend — Router Espaces (Cabinets)
|
| 3 |
+
Endpoints réservés aux superadmins pour la gestion des espaces.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
from typing import List
|
| 7 |
from uuid import UUID
|
| 8 |
+
from datetime import datetime, timezone
|
| 9 |
+
|
| 10 |
from fastapi import APIRouter, HTTPException, Depends
|
| 11 |
+
|
| 12 |
from app.models.schemas import (
|
| 13 |
EspaceCreate, EspaceUpdate, EspaceResponse, EspaceDetailResponse,
|
| 14 |
UtilisateurCreate, UtilisateurResponse, MessageResponse,
|
| 15 |
)
|
| 16 |
from app.core.auth import require_superadmin, CurrentUser
|
| 17 |
+
from app.core.supabase import supabase_admin
|
| 18 |
|
| 19 |
router = APIRouter(prefix="/espaces", tags=["Espaces (Superadmin)"])
|
| 20 |
|
|
|
|
| 24 |
payload: EspaceCreate,
|
| 25 |
_: CurrentUser = Depends(require_superadmin),
|
| 26 |
):
|
| 27 |
+
"""Crée un nouvel espace (cabinet). Superadmin only."""
|
| 28 |
+
data = payload.model_dump()
|
| 29 |
+
data["is_archived"] = False
|
| 30 |
+
response = supabase_admin.table("espaces").insert(data).execute()
|
| 31 |
if not response.data:
|
| 32 |
raise HTTPException(
|
| 33 |
status_code=500, detail="Échec de la création de l'espace")
|
|
|
|
| 35 |
|
| 36 |
|
| 37 |
@router.get("/", response_model=List[EspaceResponse])
|
| 38 |
+
async def list_espaces(
|
| 39 |
+
_: CurrentUser = Depends(require_superadmin),
|
| 40 |
+
):
|
| 41 |
+
"""Liste tous les espaces. Superadmin only."""
|
| 42 |
+
response = (
|
| 43 |
+
supabase_admin.table("espaces")
|
| 44 |
+
.select("*")
|
| 45 |
+
.eq("is_archived", False)
|
| 46 |
+
.order("nom")
|
| 47 |
+
.execute()
|
| 48 |
+
)
|
| 49 |
return response.data or []
|
| 50 |
|
| 51 |
|
|
|
|
| 54 |
espace_id: UUID,
|
| 55 |
_: CurrentUser = Depends(require_superadmin),
|
| 56 |
):
|
| 57 |
+
"""Récupère un espace avec ses utilisateurs. Superadmin only."""
|
| 58 |
+
espace_resp = (
|
| 59 |
supabase_admin.table("espaces")
|
| 60 |
.select("*")
|
| 61 |
.eq("id", str(espace_id))
|
| 62 |
+
.eq("is_archived", False)
|
| 63 |
.single()
|
| 64 |
.execute()
|
| 65 |
)
|
| 66 |
+
if not espace_resp.data:
|
| 67 |
raise HTTPException(status_code=404, detail="Espace introuvable")
|
| 68 |
|
| 69 |
+
users_resp = (
|
| 70 |
supabase_admin.table("utilisateurs")
|
| 71 |
.select("*")
|
| 72 |
.eq("espace_id", str(espace_id))
|
| 73 |
+
.order("nom")
|
| 74 |
.execute()
|
| 75 |
)
|
| 76 |
+
|
| 77 |
+
return {
|
| 78 |
+
**espace_resp.data,
|
| 79 |
+
"utilisateurs": users_resp.data or [],
|
| 80 |
+
}
|
| 81 |
|
| 82 |
|
| 83 |
@router.patch("/{espace_id}", response_model=EspaceResponse)
|
|
|
|
| 86 |
payload: EspaceUpdate,
|
| 87 |
_: CurrentUser = Depends(require_superadmin),
|
| 88 |
):
|
| 89 |
+
"""Met à jour un espace. Superadmin only."""
|
| 90 |
+
data = payload.model_dump(exclude_none=True)
|
| 91 |
+
if not data:
|
| 92 |
+
raise HTTPException(status_code=400, detail="Aucune donnée à modifier")
|
| 93 |
+
|
| 94 |
response = (
|
| 95 |
supabase_admin.table("espaces")
|
| 96 |
+
.update(data)
|
| 97 |
.eq("id", str(espace_id))
|
| 98 |
+
.eq("is_archived", False)
|
| 99 |
.execute()
|
| 100 |
)
|
| 101 |
if not response.data:
|
|
|
|
| 104 |
|
| 105 |
|
| 106 |
@router.delete("/{espace_id}", response_model=MessageResponse)
|
| 107 |
+
async def archive_espace(
|
| 108 |
espace_id: UUID,
|
| 109 |
_: CurrentUser = Depends(require_superadmin),
|
| 110 |
):
|
| 111 |
+
"""Archive un espace (soft delete). Superadmin only."""
|
| 112 |
+
response = (
|
| 113 |
+
supabase_admin.table("espaces")
|
| 114 |
+
.update({
|
| 115 |
+
"is_archived": True,
|
| 116 |
+
"archived_at": datetime.now(timezone.utc).isoformat(),
|
| 117 |
+
})
|
| 118 |
+
.eq("id", str(espace_id))
|
| 119 |
+
.eq("is_archived", False)
|
| 120 |
+
.execute()
|
| 121 |
+
)
|
| 122 |
+
if not response.data:
|
| 123 |
+
raise HTTPException(status_code=404, detail="Espace introuvable")
|
| 124 |
+
return {"message": "Espace archivé"}
|
| 125 |
|
| 126 |
|
| 127 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 128 |
+
# GESTION DES UTILISATEURS DE L'ESPACE
|
| 129 |
+
# ════════════════════════════��═════════════════════════════════════════════════
|
| 130 |
|
| 131 |
@router.post("/{espace_id}/utilisateurs", response_model=UtilisateurResponse, status_code=201)
|
| 132 |
+
async def add_utilisateur(
|
| 133 |
espace_id: UUID,
|
| 134 |
payload: UtilisateurCreate,
|
| 135 |
_: CurrentUser = Depends(require_superadmin),
|
| 136 |
):
|
| 137 |
"""
|
| 138 |
+
Crée un utilisateur et l'ajoute à l'espace.
|
| 139 |
+
Superadmin only — pas d'auto-inscription.
|
|
|
|
|
|
|
|
|
|
| 140 |
"""
|
| 141 |
+
# Vérifier que l'espace existe
|
| 142 |
+
espace_check = (
|
| 143 |
supabase_admin.table("espaces")
|
| 144 |
.select("id")
|
| 145 |
.eq("id", str(espace_id))
|
| 146 |
+
.eq("is_archived", False)
|
| 147 |
.single()
|
| 148 |
.execute()
|
| 149 |
)
|
| 150 |
+
if not espace_check.data:
|
| 151 |
raise HTTPException(status_code=404, detail="Espace introuvable")
|
| 152 |
|
| 153 |
+
# Créer l'utilisateur dans Supabase Auth
|
| 154 |
+
try:
|
| 155 |
+
auth_response = supabase_admin.auth.admin.create_user({
|
| 156 |
+
"email": payload.email,
|
| 157 |
+
"password": payload.password,
|
| 158 |
+
"email_confirm": True,
|
| 159 |
+
})
|
| 160 |
+
except Exception as e:
|
| 161 |
raise HTTPException(
|
| 162 |
+
status_code=400, detail=f"Erreur création Auth: {str(e)}")
|
| 163 |
|
| 164 |
+
if not auth_response.user:
|
| 165 |
+
raise HTTPException(
|
| 166 |
+
status_code=500, detail="Échec création utilisateur Auth")
|
| 167 |
|
| 168 |
+
# Créer le profil dans la table utilisateurs
|
| 169 |
+
profile_data = {
|
| 170 |
+
"id": auth_response.user.id,
|
| 171 |
+
"email": payload.email,
|
| 172 |
+
"nom": payload.nom,
|
| 173 |
+
"prenom": payload.prenom,
|
| 174 |
"role_cabinet": payload.role_cabinet.value,
|
| 175 |
+
"espace_id": str(espace_id),
|
| 176 |
"is_superadmin": False,
|
| 177 |
}
|
|
|
|
|
|
|
| 178 |
|
| 179 |
+
profile_resp = supabase_admin.table(
|
| 180 |
+
"utilisateurs").insert(profile_data).execute()
|
| 181 |
if not profile_resp.data:
|
| 182 |
+
# Rollback: supprimer l'utilisateur Auth créé
|
| 183 |
+
supabase_admin.auth.admin.delete_user(auth_response.user.id)
|
| 184 |
raise HTTPException(
|
| 185 |
+
status_code=500, detail="Échec création profil utilisateur")
|
| 186 |
|
| 187 |
return profile_resp.data[0]
|
| 188 |
|
| 189 |
|
| 190 |
@router.delete("/{espace_id}/utilisateurs/{utilisateur_id}", response_model=MessageResponse)
|
| 191 |
+
async def remove_utilisateur(
|
| 192 |
espace_id: UUID,
|
| 193 |
utilisateur_id: UUID,
|
| 194 |
_: CurrentUser = Depends(require_superadmin),
|
| 195 |
):
|
| 196 |
+
"""
|
| 197 |
+
Supprime un utilisateur de l'espace et de Supabase Auth.
|
| 198 |
+
Superadmin only.
|
| 199 |
+
"""
|
| 200 |
+
# Vérifier que l'utilisateur appartient à cet espace
|
| 201 |
+
user_check = (
|
| 202 |
supabase_admin.table("utilisateurs")
|
| 203 |
.select("id")
|
| 204 |
.eq("id", str(utilisateur_id))
|
|
|
|
| 206 |
.single()
|
| 207 |
.execute()
|
| 208 |
)
|
| 209 |
+
if not user_check.data:
|
| 210 |
raise HTTPException(
|
| 211 |
status_code=404, detail="Utilisateur introuvable dans cet espace")
|
| 212 |
|
| 213 |
+
# Supprimer le profil
|
| 214 |
+
supabase_admin.table("utilisateurs").delete().eq(
|
| 215 |
+
"id", str(utilisateur_id)).execute()
|
| 216 |
+
|
| 217 |
+
# Supprimer l'utilisateur Auth
|
| 218 |
+
try:
|
| 219 |
+
supabase_admin.auth.admin.delete_user(str(utilisateur_id))
|
| 220 |
+
except Exception:
|
| 221 |
+
pass # L'utilisateur Auth peut déjà avoir été supprimé
|
| 222 |
+
|
| 223 |
return {"message": "Utilisateur supprimé"}
|
app/routers/fichiers.py
CHANGED
|
@@ -1,7 +1,15 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
from typing import List
|
| 3 |
from uuid import UUID
|
|
|
|
|
|
|
| 4 |
from fastapi import APIRouter, HTTPException, Depends, UploadFile, File
|
|
|
|
| 5 |
from app.models.schemas import FichierResponse, MessageResponse
|
| 6 |
from app.core.auth import require_permission, CurrentUser
|
| 7 |
from app.core.supabase import supabase_admin
|
|
@@ -9,6 +17,11 @@ from app.core.config import settings
|
|
| 9 |
|
| 10 |
router = APIRouter(prefix="/fichiers", tags=["Fichiers"])
|
| 11 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
MAX_FILE_SIZE = 10 * 1024 * 1024 # 10 MB
|
| 13 |
MAX_FILES_PER_DOSSIER = 50
|
| 14 |
|
|
@@ -21,15 +34,20 @@ ALLOWED_MIME_TYPES = {
|
|
| 21 |
}
|
| 22 |
|
| 23 |
MIME_LABELS = {
|
| 24 |
-
"application/pdf":
|
| 25 |
"application/msword": "DOC",
|
| 26 |
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": "DOCX",
|
| 27 |
"image/jpeg": "JPEG",
|
| 28 |
-
"image/png":
|
| 29 |
}
|
| 30 |
|
| 31 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
def _validate_file(file: UploadFile, content: bytes) -> None:
|
|
|
|
| 33 |
if len(content) > MAX_FILE_SIZE:
|
| 34 |
raise HTTPException(
|
| 35 |
status_code=400,
|
|
@@ -42,18 +60,43 @@ def _validate_file(file: UploadFile, content: bytes) -> None:
|
|
| 42 |
)
|
| 43 |
|
| 44 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
@router.post("/dossier/{dossier_id}", response_model=FichierResponse, status_code=201)
|
| 46 |
async def upload_fichier(
|
| 47 |
dossier_id: UUID,
|
| 48 |
file: UploadFile = File(...),
|
| 49 |
espace_user: CurrentUser = Depends(require_permission("fichier:write")),
|
| 50 |
):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
# Vérifier que le dossier appartient à cet espace
|
| 52 |
dossier_resp = (
|
| 53 |
supabase_admin.table("dossiers")
|
| 54 |
.select("id")
|
| 55 |
.eq("id", str(dossier_id))
|
| 56 |
.eq("espace_id", espace_user.espace_id)
|
|
|
|
| 57 |
.single()
|
| 58 |
.execute()
|
| 59 |
)
|
|
@@ -61,34 +104,46 @@ async def upload_fichier(
|
|
| 61 |
raise HTTPException(
|
| 62 |
status_code=404, detail="Dossier introuvable dans cet espace")
|
| 63 |
|
|
|
|
| 64 |
count_resp = (
|
| 65 |
supabase_admin.table("fichiers")
|
| 66 |
.select("id", count="exact")
|
| 67 |
.eq("dossier_id", str(dossier_id))
|
| 68 |
.eq("espace_id", espace_user.espace_id)
|
|
|
|
| 69 |
.execute()
|
| 70 |
)
|
| 71 |
if count_resp.count and count_resp.count >= MAX_FILES_PER_DOSSIER:
|
| 72 |
raise HTTPException(
|
| 73 |
-
status_code=400,
|
|
|
|
|
|
|
| 74 |
|
|
|
|
| 75 |
content = await file.read()
|
| 76 |
_validate_file(file, content)
|
| 77 |
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
-
|
| 90 |
-
|
| 91 |
|
|
|
|
| 92 |
metadata = {
|
| 93 |
"espace_id": espace_user.espace_id,
|
| 94 |
"dossier_id": str(dossier_id),
|
|
@@ -96,16 +151,24 @@ async def upload_fichier(
|
|
| 96 |
"taille": len(content),
|
| 97 |
"type_fichier": file.content_type,
|
| 98 |
"chemin_stockage": storage_path,
|
| 99 |
-
"
|
| 100 |
}
|
|
|
|
| 101 |
db_resp = supabase_admin.table("fichiers").insert(metadata).execute()
|
| 102 |
if not db_resp.data:
|
| 103 |
-
|
| 104 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
raise HTTPException(
|
| 106 |
status_code=500, detail="Erreur lors de l'enregistrement des métadonnées")
|
| 107 |
|
| 108 |
-
|
|
|
|
|
|
|
|
|
|
| 109 |
|
| 110 |
|
| 111 |
@router.get("/dossier/{dossier_id}", response_model=List[FichierResponse])
|
|
@@ -113,15 +176,24 @@ async def list_fichiers(
|
|
| 113 |
dossier_id: UUID,
|
| 114 |
espace_user: CurrentUser = Depends(require_permission("fichier:read")),
|
| 115 |
):
|
|
|
|
| 116 |
response = (
|
| 117 |
supabase_admin.table("fichiers")
|
| 118 |
.select("*")
|
| 119 |
.eq("dossier_id", str(dossier_id))
|
| 120 |
.eq("espace_id", espace_user.espace_id)
|
|
|
|
| 121 |
.order("created_at", desc=True)
|
| 122 |
.execute()
|
| 123 |
)
|
| 124 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
|
| 126 |
|
| 127 |
@router.get("/{fichier_id}", response_model=FichierResponse)
|
|
@@ -129,37 +201,45 @@ async def get_fichier(
|
|
| 129 |
fichier_id: UUID,
|
| 130 |
espace_user: CurrentUser = Depends(require_permission("fichier:read")),
|
| 131 |
):
|
|
|
|
| 132 |
response = (
|
| 133 |
supabase_admin.table("fichiers")
|
| 134 |
.select("*")
|
| 135 |
.eq("id", str(fichier_id))
|
| 136 |
.eq("espace_id", espace_user.espace_id)
|
|
|
|
| 137 |
.single()
|
| 138 |
.execute()
|
| 139 |
)
|
| 140 |
if not response.data:
|
| 141 |
raise HTTPException(status_code=404, detail="Fichier introuvable")
|
| 142 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
|
| 144 |
|
| 145 |
@router.delete("/{fichier_id}", response_model=MessageResponse)
|
| 146 |
-
async def
|
| 147 |
fichier_id: UUID,
|
| 148 |
espace_user: CurrentUser = Depends(require_permission("fichier:delete")),
|
| 149 |
):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
response = (
|
| 151 |
supabase_admin.table("fichiers")
|
| 152 |
-
.
|
|
|
|
|
|
|
|
|
|
| 153 |
.eq("id", str(fichier_id))
|
| 154 |
.eq("espace_id", espace_user.espace_id)
|
| 155 |
-
.
|
| 156 |
.execute()
|
| 157 |
)
|
| 158 |
if not response.data:
|
| 159 |
raise HTTPException(status_code=404, detail="Fichier introuvable")
|
| 160 |
-
|
| 161 |
-
supabase_admin.storage.from_(settings.STORAGE_BUCKET).remove([
|
| 162 |
-
response.data["chemin_stockage"]])
|
| 163 |
-
supabase_admin.table("fichiers").delete().eq(
|
| 164 |
-
"id", str(fichier_id)).execute()
|
| 165 |
-
return {"message": "Fichier supprimé"}
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Dedalys Backend — Router Fichiers
|
| 3 |
+
Upload, liste, téléchargement et archivage de fichiers avec signed URLs.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import uuid as uuid_lib
|
| 7 |
from typing import List
|
| 8 |
from uuid import UUID
|
| 9 |
+
from datetime import datetime, timezone
|
| 10 |
+
|
| 11 |
from fastapi import APIRouter, HTTPException, Depends, UploadFile, File
|
| 12 |
+
|
| 13 |
from app.models.schemas import FichierResponse, MessageResponse
|
| 14 |
from app.core.auth import require_permission, CurrentUser
|
| 15 |
from app.core.supabase import supabase_admin
|
|
|
|
| 17 |
|
| 18 |
router = APIRouter(prefix="/fichiers", tags=["Fichiers"])
|
| 19 |
|
| 20 |
+
|
| 21 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 22 |
+
# CONSTANTES
|
| 23 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 24 |
+
|
| 25 |
MAX_FILE_SIZE = 10 * 1024 * 1024 # 10 MB
|
| 26 |
MAX_FILES_PER_DOSSIER = 50
|
| 27 |
|
|
|
|
| 34 |
}
|
| 35 |
|
| 36 |
MIME_LABELS = {
|
| 37 |
+
"application/pdf": "PDF",
|
| 38 |
"application/msword": "DOC",
|
| 39 |
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": "DOCX",
|
| 40 |
"image/jpeg": "JPEG",
|
| 41 |
+
"image/png": "PNG",
|
| 42 |
}
|
| 43 |
|
| 44 |
|
| 45 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 46 |
+
# HELPERS
|
| 47 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 48 |
+
|
| 49 |
def _validate_file(file: UploadFile, content: bytes) -> None:
|
| 50 |
+
"""Valide la taille et le type du fichier."""
|
| 51 |
if len(content) > MAX_FILE_SIZE:
|
| 52 |
raise HTTPException(
|
| 53 |
status_code=400,
|
|
|
|
| 60 |
)
|
| 61 |
|
| 62 |
|
| 63 |
+
def _generate_signed_url(path: str) -> str:
|
| 64 |
+
"""Génère une signed URL temporaire pour un fichier."""
|
| 65 |
+
try:
|
| 66 |
+
response = supabase_admin.storage.from_(settings.STORAGE_BUCKET).create_signed_url(
|
| 67 |
+
path=path,
|
| 68 |
+
expires_in=settings.STORAGE_SIGNED_URL_EXPIRY,
|
| 69 |
+
)
|
| 70 |
+
return response.get("signedURL", "")
|
| 71 |
+
except Exception:
|
| 72 |
+
return ""
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 76 |
+
# ENDPOINTS
|
| 77 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 78 |
+
|
| 79 |
@router.post("/dossier/{dossier_id}", response_model=FichierResponse, status_code=201)
|
| 80 |
async def upload_fichier(
|
| 81 |
dossier_id: UUID,
|
| 82 |
file: UploadFile = File(...),
|
| 83 |
espace_user: CurrentUser = Depends(require_permission("fichier:write")),
|
| 84 |
):
|
| 85 |
+
"""
|
| 86 |
+
Upload un fichier dans un dossier.
|
| 87 |
+
|
| 88 |
+
Limites:
|
| 89 |
+
- Taille max : 10 MB
|
| 90 |
+
- Types acceptés : PDF, DOC, DOCX, JPEG, PNG
|
| 91 |
+
- Max 50 fichiers par dossier
|
| 92 |
+
"""
|
| 93 |
# Vérifier que le dossier appartient à cet espace
|
| 94 |
dossier_resp = (
|
| 95 |
supabase_admin.table("dossiers")
|
| 96 |
.select("id")
|
| 97 |
.eq("id", str(dossier_id))
|
| 98 |
.eq("espace_id", espace_user.espace_id)
|
| 99 |
+
.eq("is_archived", False)
|
| 100 |
.single()
|
| 101 |
.execute()
|
| 102 |
)
|
|
|
|
| 104 |
raise HTTPException(
|
| 105 |
status_code=404, detail="Dossier introuvable dans cet espace")
|
| 106 |
|
| 107 |
+
# Vérifier le quota de fichiers
|
| 108 |
count_resp = (
|
| 109 |
supabase_admin.table("fichiers")
|
| 110 |
.select("id", count="exact")
|
| 111 |
.eq("dossier_id", str(dossier_id))
|
| 112 |
.eq("espace_id", espace_user.espace_id)
|
| 113 |
+
.eq("is_archived", False)
|
| 114 |
.execute()
|
| 115 |
)
|
| 116 |
if count_resp.count and count_resp.count >= MAX_FILES_PER_DOSSIER:
|
| 117 |
raise HTTPException(
|
| 118 |
+
status_code=400,
|
| 119 |
+
detail=f"Limite de {MAX_FILES_PER_DOSSIER} fichiers par dossier atteinte"
|
| 120 |
+
)
|
| 121 |
|
| 122 |
+
# Lire et valider le fichier
|
| 123 |
content = await file.read()
|
| 124 |
_validate_file(file, content)
|
| 125 |
|
| 126 |
+
# Générer le chemin de stockage
|
| 127 |
+
ext = ""
|
| 128 |
+
if file.filename and "." in file.filename:
|
| 129 |
+
ext = "." + file.filename.rsplit(".", 1)[-1].lower()
|
| 130 |
+
storage_path = f"{espace_user.espace_id}/{dossier_id}/{uuid_lib.uuid4()}{ext}"
|
| 131 |
+
|
| 132 |
+
# Upload vers Supabase Storage
|
| 133 |
+
try:
|
| 134 |
+
supabase_admin.storage.from_(settings.STORAGE_BUCKET).upload(
|
| 135 |
+
path=storage_path,
|
| 136 |
+
file=content,
|
| 137 |
+
file_options={"content-type": file.content_type},
|
| 138 |
+
)
|
| 139 |
+
except Exception as e:
|
| 140 |
+
raise HTTPException(
|
| 141 |
+
status_code=500, detail=f"Erreur upload : {str(e)}")
|
| 142 |
|
| 143 |
+
# Générer signed URL (pas d'URL publique permanente)
|
| 144 |
+
signed_url = _generate_signed_url(storage_path)
|
| 145 |
|
| 146 |
+
# Enregistrer les métadonnées
|
| 147 |
metadata = {
|
| 148 |
"espace_id": espace_user.espace_id,
|
| 149 |
"dossier_id": str(dossier_id),
|
|
|
|
| 151 |
"taille": len(content),
|
| 152 |
"type_fichier": file.content_type,
|
| 153 |
"chemin_stockage": storage_path,
|
| 154 |
+
"is_archived": False,
|
| 155 |
}
|
| 156 |
+
|
| 157 |
db_resp = supabase_admin.table("fichiers").insert(metadata).execute()
|
| 158 |
if not db_resp.data:
|
| 159 |
+
# Rollback : supprimer le fichier uploadé
|
| 160 |
+
try:
|
| 161 |
+
supabase_admin.storage.from_(
|
| 162 |
+
settings.STORAGE_BUCKET).remove([storage_path])
|
| 163 |
+
except Exception:
|
| 164 |
+
pass
|
| 165 |
raise HTTPException(
|
| 166 |
status_code=500, detail="Erreur lors de l'enregistrement des métadonnées")
|
| 167 |
|
| 168 |
+
fichier = db_resp.data[0]
|
| 169 |
+
fichier["url"] = signed_url
|
| 170 |
+
fichier["url_expire_dans"] = settings.STORAGE_SIGNED_URL_EXPIRY
|
| 171 |
+
return fichier
|
| 172 |
|
| 173 |
|
| 174 |
@router.get("/dossier/{dossier_id}", response_model=List[FichierResponse])
|
|
|
|
| 176 |
dossier_id: UUID,
|
| 177 |
espace_user: CurrentUser = Depends(require_permission("fichier:read")),
|
| 178 |
):
|
| 179 |
+
"""Liste les fichiers d'un dossier."""
|
| 180 |
response = (
|
| 181 |
supabase_admin.table("fichiers")
|
| 182 |
.select("*")
|
| 183 |
.eq("dossier_id", str(dossier_id))
|
| 184 |
.eq("espace_id", espace_user.espace_id)
|
| 185 |
+
.eq("is_archived", False)
|
| 186 |
.order("created_at", desc=True)
|
| 187 |
.execute()
|
| 188 |
)
|
| 189 |
+
|
| 190 |
+
# Ajouter signed URLs à chaque fichier
|
| 191 |
+
fichiers = response.data or []
|
| 192 |
+
for f in fichiers:
|
| 193 |
+
f["url"] = _generate_signed_url(f["chemin_stockage"])
|
| 194 |
+
f["url_expire_dans"] = settings.STORAGE_SIGNED_URL_EXPIRY
|
| 195 |
+
|
| 196 |
+
return fichiers
|
| 197 |
|
| 198 |
|
| 199 |
@router.get("/{fichier_id}", response_model=FichierResponse)
|
|
|
|
| 201 |
fichier_id: UUID,
|
| 202 |
espace_user: CurrentUser = Depends(require_permission("fichier:read")),
|
| 203 |
):
|
| 204 |
+
"""Récupère un fichier avec sa signed URL temporaire."""
|
| 205 |
response = (
|
| 206 |
supabase_admin.table("fichiers")
|
| 207 |
.select("*")
|
| 208 |
.eq("id", str(fichier_id))
|
| 209 |
.eq("espace_id", espace_user.espace_id)
|
| 210 |
+
.eq("is_archived", False)
|
| 211 |
.single()
|
| 212 |
.execute()
|
| 213 |
)
|
| 214 |
if not response.data:
|
| 215 |
raise HTTPException(status_code=404, detail="Fichier introuvable")
|
| 216 |
+
|
| 217 |
+
fichier = response.data
|
| 218 |
+
fichier["url"] = _generate_signed_url(fichier["chemin_stockage"])
|
| 219 |
+
fichier["url_expire_dans"] = settings.STORAGE_SIGNED_URL_EXPIRY
|
| 220 |
+
return fichier
|
| 221 |
|
| 222 |
|
| 223 |
@router.delete("/{fichier_id}", response_model=MessageResponse)
|
| 224 |
+
async def archive_fichier(
|
| 225 |
fichier_id: UUID,
|
| 226 |
espace_user: CurrentUser = Depends(require_permission("fichier:delete")),
|
| 227 |
):
|
| 228 |
+
"""
|
| 229 |
+
Archive un fichier (soft delete).
|
| 230 |
+
Le fichier physique reste dans Storage pour traçabilité.
|
| 231 |
+
"""
|
| 232 |
response = (
|
| 233 |
supabase_admin.table("fichiers")
|
| 234 |
+
.update({
|
| 235 |
+
"is_archived": True,
|
| 236 |
+
"archived_at": datetime.now(timezone.utc).isoformat(),
|
| 237 |
+
})
|
| 238 |
.eq("id", str(fichier_id))
|
| 239 |
.eq("espace_id", espace_user.espace_id)
|
| 240 |
+
.eq("is_archived", False)
|
| 241 |
.execute()
|
| 242 |
)
|
| 243 |
if not response.data:
|
| 244 |
raise HTTPException(status_code=404, detail="Fichier introuvable")
|
| 245 |
+
return {"message": "Fichier archivé"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
app/routers/flash_cr.py
CHANGED
|
@@ -1,24 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from typing import List
|
| 2 |
from uuid import UUID
|
|
|
|
|
|
|
| 3 |
from fastapi import APIRouter, HTTPException, Depends
|
| 4 |
-
|
|
|
|
|
|
|
|
|
|
| 5 |
from app.core.auth import require_permission, CurrentUser
|
| 6 |
from app.core.supabase import supabase_admin
|
| 7 |
|
| 8 |
router = APIRouter(prefix="/flash-cr", tags=["Flash CR"])
|
| 9 |
|
| 10 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
@router.post("/", response_model=FlashCRResponse, status_code=201)
|
| 12 |
async def create_flash_cr(
|
| 13 |
payload: FlashCRCreate,
|
| 14 |
espace_user: CurrentUser = Depends(require_permission("flash_cr:write")),
|
| 15 |
):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
# Vérifier que l'audience appartient à cet espace
|
| 17 |
audience = (
|
| 18 |
supabase_admin.table("audiences")
|
| 19 |
-
.select("id")
|
| 20 |
.eq("id", str(payload.audience_id))
|
| 21 |
.eq("espace_id", espace_user.espace_id)
|
|
|
|
| 22 |
.single()
|
| 23 |
.execute()
|
| 24 |
)
|
|
@@ -26,19 +57,41 @@ async def create_flash_cr(
|
|
| 26 |
raise HTTPException(
|
| 27 |
status_code=404, detail="Audience introuvable dans cet espace")
|
| 28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
existing = (
|
| 30 |
supabase_admin.table("flash_cr")
|
| 31 |
.select("id")
|
| 32 |
.eq("audience_id", str(payload.audience_id))
|
|
|
|
| 33 |
.execute()
|
| 34 |
)
|
| 35 |
if existing.data:
|
| 36 |
raise HTTPException(
|
| 37 |
-
status_code=409,
|
|
|
|
|
|
|
| 38 |
|
|
|
|
| 39 |
data = payload.model_dump()
|
| 40 |
data["espace_id"] = espace_user.espace_id
|
| 41 |
data["audience_id"] = str(payload.audience_id)
|
|
|
|
|
|
|
| 42 |
if data.get("prochaine_date"):
|
| 43 |
data["prochaine_date"] = str(data["prochaine_date"])
|
| 44 |
|
|
@@ -46,7 +99,38 @@ async def create_flash_cr(
|
|
| 46 |
if not response.data:
|
| 47 |
raise HTTPException(
|
| 48 |
status_code=500, detail="Échec de la création du Flash CR")
|
| 49 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
|
| 52 |
@router.get("/audience/{audience_id}", response_model=FlashCRResponse)
|
|
@@ -54,11 +138,13 @@ async def get_flash_cr_by_audience(
|
|
| 54 |
audience_id: UUID,
|
| 55 |
espace_user: CurrentUser = Depends(require_permission("flash_cr:read")),
|
| 56 |
):
|
|
|
|
| 57 |
response = (
|
| 58 |
supabase_admin.table("flash_cr")
|
| 59 |
.select("*")
|
| 60 |
.eq("audience_id", str(audience_id))
|
| 61 |
.eq("espace_id", espace_user.espace_id)
|
|
|
|
| 62 |
.single()
|
| 63 |
.execute()
|
| 64 |
)
|
|
@@ -68,16 +154,50 @@ async def get_flash_cr_by_audience(
|
|
| 68 |
return response.data
|
| 69 |
|
| 70 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
@router.get("/{flash_cr_id}", response_model=FlashCRResponse)
|
| 72 |
async def get_flash_cr(
|
| 73 |
flash_cr_id: UUID,
|
| 74 |
espace_user: CurrentUser = Depends(require_permission("flash_cr:read")),
|
| 75 |
):
|
|
|
|
| 76 |
response = (
|
| 77 |
supabase_admin.table("flash_cr")
|
| 78 |
.select("*")
|
| 79 |
.eq("id", str(flash_cr_id))
|
| 80 |
.eq("espace_id", espace_user.espace_id)
|
|
|
|
| 81 |
.single()
|
| 82 |
.execute()
|
| 83 |
)
|
|
@@ -92,9 +212,27 @@ async def update_flash_cr(
|
|
| 92 |
payload: FlashCRUpdate,
|
| 93 |
espace_user: CurrentUser = Depends(require_permission("flash_cr:write")),
|
| 94 |
):
|
|
|
|
| 95 |
data = payload.model_dump(exclude_none=True)
|
| 96 |
if not data:
|
| 97 |
raise HTTPException(status_code=400, detail="Aucune donnée à modifier")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
if "prochaine_date" in data and data["prochaine_date"]:
|
| 99 |
data["prochaine_date"] = str(data["prochaine_date"])
|
| 100 |
|
|
@@ -103,6 +241,7 @@ async def update_flash_cr(
|
|
| 103 |
.update(data)
|
| 104 |
.eq("id", str(flash_cr_id))
|
| 105 |
.eq("espace_id", espace_user.espace_id)
|
|
|
|
| 106 |
.execute()
|
| 107 |
)
|
| 108 |
if not response.data:
|
|
@@ -111,10 +250,22 @@ async def update_flash_cr(
|
|
| 111 |
|
| 112 |
|
| 113 |
@router.delete("/{flash_cr_id}", response_model=MessageResponse)
|
| 114 |
-
async def
|
| 115 |
flash_cr_id: UUID,
|
| 116 |
espace_user: CurrentUser = Depends(require_permission("flash_cr:delete")),
|
| 117 |
):
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Dedalys Backend — Router Flash CR
|
| 3 |
+
CRUD Flash CR (comptes-rendus d'audience) — Killer Feature Dedalys.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
from typing import List
|
| 7 |
from uuid import UUID
|
| 8 |
+
from datetime import datetime, timezone, date
|
| 9 |
+
|
| 10 |
from fastapi import APIRouter, HTTPException, Depends
|
| 11 |
+
|
| 12 |
+
from app.models.schemas import (
|
| 13 |
+
FlashCRCreate, FlashCRUpdate, FlashCRResponse, MessageResponse,
|
| 14 |
+
)
|
| 15 |
from app.core.auth import require_permission, CurrentUser
|
| 16 |
from app.core.supabase import supabase_admin
|
| 17 |
|
| 18 |
router = APIRouter(prefix="/flash-cr", tags=["Flash CR"])
|
| 19 |
|
| 20 |
|
| 21 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 22 |
+
# CRUD FLASH CR
|
| 23 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 24 |
+
|
| 25 |
@router.post("/", response_model=FlashCRResponse, status_code=201)
|
| 26 |
async def create_flash_cr(
|
| 27 |
payload: FlashCRCreate,
|
| 28 |
espace_user: CurrentUser = Depends(require_permission("flash_cr:write")),
|
| 29 |
):
|
| 30 |
+
"""
|
| 31 |
+
Crée un Flash CR pour une audience passée.
|
| 32 |
+
|
| 33 |
+
Règles:
|
| 34 |
+
- Un seul Flash CR par audience (unicité)
|
| 35 |
+
- L'audience doit être de type 'audience' (pas 'reunion')
|
| 36 |
+
- L'audience doit être passée (date < aujourd'hui)
|
| 37 |
+
- prochaine_date obligatoire si type_decision = mise_en_delibere ou renvoi
|
| 38 |
+
"""
|
| 39 |
+
# Validation : prochaine_date obligatoire si mise_en_delibere ou renvoi
|
| 40 |
+
if payload.type_decision in ("mise_en_delibere", "renvoi") and not payload.prochaine_date:
|
| 41 |
+
raise HTTPException(
|
| 42 |
+
status_code=400,
|
| 43 |
+
detail=f"La prochaine date est obligatoire pour type_decision='{payload.type_decision}'"
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
# Vérifier que l'audience appartient à cet espace
|
| 47 |
audience = (
|
| 48 |
supabase_admin.table("audiences")
|
| 49 |
+
.select("id, date, type, dossier_id")
|
| 50 |
.eq("id", str(payload.audience_id))
|
| 51 |
.eq("espace_id", espace_user.espace_id)
|
| 52 |
+
.eq("is_archived", False)
|
| 53 |
.single()
|
| 54 |
.execute()
|
| 55 |
)
|
|
|
|
| 57 |
raise HTTPException(
|
| 58 |
status_code=404, detail="Audience introuvable dans cet espace")
|
| 59 |
|
| 60 |
+
# Vérifier que l'audience est de type 'audience' (pas reunion)
|
| 61 |
+
if audience.data.get("type") == "reunion":
|
| 62 |
+
raise HTTPException(
|
| 63 |
+
status_code=400,
|
| 64 |
+
detail="Un Flash CR ne peut être créé que pour une audience, pas une réunion"
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
# Vérifier que l'audience est passée
|
| 68 |
+
audience_date = datetime.strptime(audience.data["date"], "%Y-%m-%d").date()
|
| 69 |
+
if audience_date >= date.today():
|
| 70 |
+
raise HTTPException(
|
| 71 |
+
status_code=400,
|
| 72 |
+
detail="Un Flash CR ne peut être créé que pour une audience passée"
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
# Vérifier qu'il n'existe pas déjà un Flash CR pour cette audience
|
| 76 |
existing = (
|
| 77 |
supabase_admin.table("flash_cr")
|
| 78 |
.select("id")
|
| 79 |
.eq("audience_id", str(payload.audience_id))
|
| 80 |
+
.eq("is_archived", False)
|
| 81 |
.execute()
|
| 82 |
)
|
| 83 |
if existing.data:
|
| 84 |
raise HTTPException(
|
| 85 |
+
status_code=409,
|
| 86 |
+
detail="Un Flash CR existe déjà pour cette audience"
|
| 87 |
+
)
|
| 88 |
|
| 89 |
+
# Préparer les données
|
| 90 |
data = payload.model_dump()
|
| 91 |
data["espace_id"] = espace_user.espace_id
|
| 92 |
data["audience_id"] = str(payload.audience_id)
|
| 93 |
+
data["is_archived"] = False
|
| 94 |
+
data["email_envoye"] = False
|
| 95 |
if data.get("prochaine_date"):
|
| 96 |
data["prochaine_date"] = str(data["prochaine_date"])
|
| 97 |
|
|
|
|
| 99 |
if not response.data:
|
| 100 |
raise HTTPException(
|
| 101 |
status_code=500, detail="Échec de la création du Flash CR")
|
| 102 |
+
|
| 103 |
+
flash_cr = response.data[0]
|
| 104 |
+
|
| 105 |
+
# MVP — Envoi email si envoyer_email=True
|
| 106 |
+
# TODO: Implémenter l'envoi via Resend dans core/email.py
|
| 107 |
+
if payload.envoyer_email:
|
| 108 |
+
# Marquer comme envoyé (simulation MVP — à remplacer par envoi réel)
|
| 109 |
+
# MVP — à migrer avant lancement commercial
|
| 110 |
+
supabase_admin.table("flash_cr").update({
|
| 111 |
+
"email_envoye": True,
|
| 112 |
+
"email_envoye_at": datetime.now(timezone.utc).isoformat(),
|
| 113 |
+
}).eq("id", flash_cr["id"]).execute()
|
| 114 |
+
flash_cr["email_envoye"] = True
|
| 115 |
+
flash_cr["email_envoye_at"] = datetime.now(timezone.utc).isoformat()
|
| 116 |
+
|
| 117 |
+
return flash_cr
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
@router.get("/", response_model=List[FlashCRResponse])
|
| 121 |
+
async def list_flash_cr(
|
| 122 |
+
espace_user: CurrentUser = Depends(require_permission("flash_cr:read")),
|
| 123 |
+
):
|
| 124 |
+
"""Liste tous les Flash CR de l'espace."""
|
| 125 |
+
response = (
|
| 126 |
+
supabase_admin.table("flash_cr")
|
| 127 |
+
.select("*")
|
| 128 |
+
.eq("espace_id", espace_user.espace_id)
|
| 129 |
+
.eq("is_archived", False)
|
| 130 |
+
.order("created_at", desc=True)
|
| 131 |
+
.execute()
|
| 132 |
+
)
|
| 133 |
+
return response.data or []
|
| 134 |
|
| 135 |
|
| 136 |
@router.get("/audience/{audience_id}", response_model=FlashCRResponse)
|
|
|
|
| 138 |
audience_id: UUID,
|
| 139 |
espace_user: CurrentUser = Depends(require_permission("flash_cr:read")),
|
| 140 |
):
|
| 141 |
+
"""Récupère le Flash CR d'une audience."""
|
| 142 |
response = (
|
| 143 |
supabase_admin.table("flash_cr")
|
| 144 |
.select("*")
|
| 145 |
.eq("audience_id", str(audience_id))
|
| 146 |
.eq("espace_id", espace_user.espace_id)
|
| 147 |
+
.eq("is_archived", False)
|
| 148 |
.single()
|
| 149 |
.execute()
|
| 150 |
)
|
|
|
|
| 154 |
return response.data
|
| 155 |
|
| 156 |
|
| 157 |
+
@router.get("/dossier/{dossier_id}", response_model=List[FlashCRResponse])
|
| 158 |
+
async def list_flash_cr_by_dossier(
|
| 159 |
+
dossier_id: UUID,
|
| 160 |
+
espace_user: CurrentUser = Depends(require_permission("flash_cr:read")),
|
| 161 |
+
):
|
| 162 |
+
"""Liste les Flash CR d'un dossier (via les audiences du dossier)."""
|
| 163 |
+
# Récupérer les IDs d'audiences du dossier
|
| 164 |
+
audiences = (
|
| 165 |
+
supabase_admin.table("audiences")
|
| 166 |
+
.select("id")
|
| 167 |
+
.eq("dossier_id", str(dossier_id))
|
| 168 |
+
.eq("espace_id", espace_user.espace_id)
|
| 169 |
+
.eq("is_archived", False)
|
| 170 |
+
.execute()
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
audience_ids = [a["id"] for a in (audiences.data or [])]
|
| 174 |
+
if not audience_ids:
|
| 175 |
+
return []
|
| 176 |
+
|
| 177 |
+
response = (
|
| 178 |
+
supabase_admin.table("flash_cr")
|
| 179 |
+
.select("*")
|
| 180 |
+
.in_("audience_id", audience_ids)
|
| 181 |
+
.eq("espace_id", espace_user.espace_id)
|
| 182 |
+
.eq("is_archived", False)
|
| 183 |
+
.order("created_at", desc=True)
|
| 184 |
+
.execute()
|
| 185 |
+
)
|
| 186 |
+
return response.data or []
|
| 187 |
+
|
| 188 |
+
|
| 189 |
@router.get("/{flash_cr_id}", response_model=FlashCRResponse)
|
| 190 |
async def get_flash_cr(
|
| 191 |
flash_cr_id: UUID,
|
| 192 |
espace_user: CurrentUser = Depends(require_permission("flash_cr:read")),
|
| 193 |
):
|
| 194 |
+
"""Récupère un Flash CR par son ID."""
|
| 195 |
response = (
|
| 196 |
supabase_admin.table("flash_cr")
|
| 197 |
.select("*")
|
| 198 |
.eq("id", str(flash_cr_id))
|
| 199 |
.eq("espace_id", espace_user.espace_id)
|
| 200 |
+
.eq("is_archived", False)
|
| 201 |
.single()
|
| 202 |
.execute()
|
| 203 |
)
|
|
|
|
| 212 |
payload: FlashCRUpdate,
|
| 213 |
espace_user: CurrentUser = Depends(require_permission("flash_cr:write")),
|
| 214 |
):
|
| 215 |
+
"""Met à jour un Flash CR."""
|
| 216 |
data = payload.model_dump(exclude_none=True)
|
| 217 |
if not data:
|
| 218 |
raise HTTPException(status_code=400, detail="Aucune donnée à modifier")
|
| 219 |
+
|
| 220 |
+
# Validation si type_decision change vers mise_en_delibere ou renvoi
|
| 221 |
+
if data.get("type_decision") in ("mise_en_delibere", "renvoi"):
|
| 222 |
+
if not data.get("prochaine_date"):
|
| 223 |
+
existing = (
|
| 224 |
+
supabase_admin.table("flash_cr")
|
| 225 |
+
.select("prochaine_date")
|
| 226 |
+
.eq("id", str(flash_cr_id))
|
| 227 |
+
.single()
|
| 228 |
+
.execute()
|
| 229 |
+
)
|
| 230 |
+
if existing.data and not existing.data.get("prochaine_date"):
|
| 231 |
+
raise HTTPException(
|
| 232 |
+
status_code=400,
|
| 233 |
+
detail=f"La prochaine date est obligatoire pour type_decision='{data['type_decision']}'"
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
if "prochaine_date" in data and data["prochaine_date"]:
|
| 237 |
data["prochaine_date"] = str(data["prochaine_date"])
|
| 238 |
|
|
|
|
| 241 |
.update(data)
|
| 242 |
.eq("id", str(flash_cr_id))
|
| 243 |
.eq("espace_id", espace_user.espace_id)
|
| 244 |
+
.eq("is_archived", False)
|
| 245 |
.execute()
|
| 246 |
)
|
| 247 |
if not response.data:
|
|
|
|
| 250 |
|
| 251 |
|
| 252 |
@router.delete("/{flash_cr_id}", response_model=MessageResponse)
|
| 253 |
+
async def archive_flash_cr(
|
| 254 |
flash_cr_id: UUID,
|
| 255 |
espace_user: CurrentUser = Depends(require_permission("flash_cr:delete")),
|
| 256 |
):
|
| 257 |
+
"""Archive un Flash CR (soft delete)."""
|
| 258 |
+
response = (
|
| 259 |
+
supabase_admin.table("flash_cr")
|
| 260 |
+
.update({
|
| 261 |
+
"is_archived": True,
|
| 262 |
+
"archived_at": datetime.now(timezone.utc).isoformat(),
|
| 263 |
+
})
|
| 264 |
+
.eq("id", str(flash_cr_id))
|
| 265 |
+
.eq("espace_id", espace_user.espace_id)
|
| 266 |
+
.eq("is_archived", False)
|
| 267 |
+
.execute()
|
| 268 |
+
)
|
| 269 |
+
if not response.data:
|
| 270 |
+
raise HTTPException(status_code=404, detail="Flash CR introuvable")
|
| 271 |
+
return {"message": "Flash CR archivé"}
|
app/routers/paiements.py
CHANGED
|
@@ -1,23 +1,70 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
from uuid import UUID
|
| 3 |
-
from
|
| 4 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
from app.core.auth import require_permission, CurrentUser
|
| 6 |
from app.core.supabase import supabase_admin
|
| 7 |
|
| 8 |
router = APIRouter(prefix="/paiements", tags=["Paiements"])
|
| 9 |
|
| 10 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
@router.post("/", response_model=PaiementResponse, status_code=201)
|
| 12 |
async def create_paiement(
|
| 13 |
payload: PaiementCreate,
|
| 14 |
espace_user: CurrentUser = Depends(require_permission("paiement:write")),
|
| 15 |
):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
data = payload.model_dump()
|
| 17 |
data["espace_id"] = espace_user.espace_id
|
| 18 |
data["client_id"] = str(payload.client_id)
|
| 19 |
data["dossier_id"] = str(payload.dossier_id)
|
| 20 |
data["date_reception"] = str(payload.date_reception)
|
|
|
|
| 21 |
|
| 22 |
response = supabase_admin.table("paiements").insert(data).execute()
|
| 23 |
if not response.data:
|
|
@@ -26,18 +73,54 @@ async def create_paiement(
|
|
| 26 |
return response.data[0]
|
| 27 |
|
| 28 |
|
| 29 |
-
@router.get("/", response_model=
|
| 30 |
async def list_paiements(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
espace_user: CurrentUser = Depends(require_permission("paiement:read")),
|
| 32 |
):
|
| 33 |
-
|
|
|
|
| 34 |
supabase_admin.table("paiements")
|
| 35 |
-
.select("*")
|
| 36 |
.eq("espace_id", espace_user.espace_id)
|
| 37 |
-
.
|
| 38 |
-
.execute()
|
| 39 |
)
|
| 40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
|
| 43 |
@router.get("/dossier/{dossier_id}", response_model=List[PaiementResponse])
|
|
@@ -45,11 +128,13 @@ async def list_paiements_by_dossier(
|
|
| 45 |
dossier_id: UUID,
|
| 46 |
espace_user: CurrentUser = Depends(require_permission("paiement:read")),
|
| 47 |
):
|
|
|
|
| 48 |
response = (
|
| 49 |
supabase_admin.table("paiements")
|
| 50 |
.select("*")
|
| 51 |
.eq("dossier_id", str(dossier_id))
|
| 52 |
.eq("espace_id", espace_user.espace_id)
|
|
|
|
| 53 |
.order("date_reception", desc=True)
|
| 54 |
.execute()
|
| 55 |
)
|
|
@@ -61,11 +146,13 @@ async def list_paiements_by_client(
|
|
| 61 |
client_id: UUID,
|
| 62 |
espace_user: CurrentUser = Depends(require_permission("paiement:read")),
|
| 63 |
):
|
|
|
|
| 64 |
response = (
|
| 65 |
supabase_admin.table("paiements")
|
| 66 |
.select("*")
|
| 67 |
.eq("client_id", str(client_id))
|
| 68 |
.eq("espace_id", espace_user.espace_id)
|
|
|
|
| 69 |
.order("date_reception", desc=True)
|
| 70 |
.execute()
|
| 71 |
)
|
|
@@ -77,11 +164,13 @@ async def get_paiement(
|
|
| 77 |
paiement_id: UUID,
|
| 78 |
espace_user: CurrentUser = Depends(require_permission("paiement:read")),
|
| 79 |
):
|
|
|
|
| 80 |
response = (
|
| 81 |
supabase_admin.table("paiements")
|
| 82 |
.select("*")
|
| 83 |
.eq("id", str(paiement_id))
|
| 84 |
.eq("espace_id", espace_user.espace_id)
|
|
|
|
| 85 |
.single()
|
| 86 |
.execute()
|
| 87 |
)
|
|
@@ -96,6 +185,7 @@ async def update_paiement(
|
|
| 96 |
payload: PaiementUpdate,
|
| 97 |
espace_user: CurrentUser = Depends(require_permission("paiement:write")),
|
| 98 |
):
|
|
|
|
| 99 |
data = payload.model_dump(exclude_none=True)
|
| 100 |
if not data:
|
| 101 |
raise HTTPException(status_code=400, detail="Aucune donnée à modifier")
|
|
@@ -107,6 +197,7 @@ async def update_paiement(
|
|
| 107 |
.update(data)
|
| 108 |
.eq("id", str(paiement_id))
|
| 109 |
.eq("espace_id", espace_user.espace_id)
|
|
|
|
| 110 |
.execute()
|
| 111 |
)
|
| 112 |
if not response.data:
|
|
@@ -115,10 +206,22 @@ async def update_paiement(
|
|
| 115 |
|
| 116 |
|
| 117 |
@router.delete("/{paiement_id}", response_model=MessageResponse)
|
| 118 |
-
async def
|
| 119 |
paiement_id: UUID,
|
| 120 |
espace_user: CurrentUser = Depends(require_permission("paiement:delete")),
|
| 121 |
):
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Dedalys Backend — Router Paiements
|
| 3 |
+
CRUD paiements (honoraires et frais), soft delete, pagination et filtres.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from typing import Optional, List
|
| 7 |
+
from math import ceil
|
| 8 |
from uuid import UUID
|
| 9 |
+
from datetime import datetime, timezone, date
|
| 10 |
+
|
| 11 |
+
from fastapi import APIRouter, HTTPException, Depends, Query
|
| 12 |
+
|
| 13 |
+
from app.models.schemas import (
|
| 14 |
+
PaiementCreate, PaiementUpdate, PaiementResponse,
|
| 15 |
+
PaginatedResponse, MessageResponse,
|
| 16 |
+
)
|
| 17 |
from app.core.auth import require_permission, CurrentUser
|
| 18 |
from app.core.supabase import supabase_admin
|
| 19 |
|
| 20 |
router = APIRouter(prefix="/paiements", tags=["Paiements"])
|
| 21 |
|
| 22 |
|
| 23 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 24 |
+
# CRUD PAIEMENTS
|
| 25 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 26 |
+
|
| 27 |
@router.post("/", response_model=PaiementResponse, status_code=201)
|
| 28 |
async def create_paiement(
|
| 29 |
payload: PaiementCreate,
|
| 30 |
espace_user: CurrentUser = Depends(require_permission("paiement:write")),
|
| 31 |
):
|
| 32 |
+
"""Enregistre un nouveau paiement."""
|
| 33 |
+
# Vérifier que le client appartient à l'espace
|
| 34 |
+
client_check = (
|
| 35 |
+
supabase_admin.table("clients")
|
| 36 |
+
.select("id")
|
| 37 |
+
.eq("id", str(payload.client_id))
|
| 38 |
+
.eq("espace_id", espace_user.espace_id)
|
| 39 |
+
.eq("is_archived", False)
|
| 40 |
+
.single()
|
| 41 |
+
.execute()
|
| 42 |
+
)
|
| 43 |
+
if not client_check.data:
|
| 44 |
+
raise HTTPException(
|
| 45 |
+
status_code=404, detail="Client introuvable dans cet espace")
|
| 46 |
+
|
| 47 |
+
# Vérifier que le dossier appartient à l'espace et au client
|
| 48 |
+
dossier_check = (
|
| 49 |
+
supabase_admin.table("dossiers")
|
| 50 |
+
.select("id")
|
| 51 |
+
.eq("id", str(payload.dossier_id))
|
| 52 |
+
.eq("client_id", str(payload.client_id))
|
| 53 |
+
.eq("espace_id", espace_user.espace_id)
|
| 54 |
+
.eq("is_archived", False)
|
| 55 |
+
.single()
|
| 56 |
+
.execute()
|
| 57 |
+
)
|
| 58 |
+
if not dossier_check.data:
|
| 59 |
+
raise HTTPException(
|
| 60 |
+
status_code=404, detail="Dossier introuvable ou non lié à ce client")
|
| 61 |
+
|
| 62 |
data = payload.model_dump()
|
| 63 |
data["espace_id"] = espace_user.espace_id
|
| 64 |
data["client_id"] = str(payload.client_id)
|
| 65 |
data["dossier_id"] = str(payload.dossier_id)
|
| 66 |
data["date_reception"] = str(payload.date_reception)
|
| 67 |
+
data["is_archived"] = False
|
| 68 |
|
| 69 |
response = supabase_admin.table("paiements").insert(data).execute()
|
| 70 |
if not response.data:
|
|
|
|
| 73 |
return response.data[0]
|
| 74 |
|
| 75 |
|
| 76 |
+
@router.get("/", response_model=PaginatedResponse[PaiementResponse])
|
| 77 |
async def list_paiements(
|
| 78 |
+
page: int = Query(1, ge=1),
|
| 79 |
+
limit: int = Query(20, ge=1, le=100),
|
| 80 |
+
client_id: Optional[UUID] = Query(None, description="Filtrer par client"),
|
| 81 |
+
dossier_id: Optional[UUID] = Query(
|
| 82 |
+
None, description="Filtrer par dossier"),
|
| 83 |
+
type: Optional[str] = Query(
|
| 84 |
+
None, pattern="^(honoraires|frais)$", description="Filtrer par type"),
|
| 85 |
+
date_debut: Optional[date] = Query(None, description="Date de début"),
|
| 86 |
+
date_fin: Optional[date] = Query(None, description="Date de fin"),
|
| 87 |
espace_user: CurrentUser = Depends(require_permission("paiement:read")),
|
| 88 |
):
|
| 89 |
+
"""Liste les paiements avec pagination et filtres."""
|
| 90 |
+
query = (
|
| 91 |
supabase_admin.table("paiements")
|
| 92 |
+
.select("*", count="exact")
|
| 93 |
.eq("espace_id", espace_user.espace_id)
|
| 94 |
+
.eq("is_archived", False)
|
|
|
|
| 95 |
)
|
| 96 |
+
|
| 97 |
+
# Filtres
|
| 98 |
+
if client_id:
|
| 99 |
+
query = query.eq("client_id", str(client_id))
|
| 100 |
+
if dossier_id:
|
| 101 |
+
query = query.eq("dossier_id", str(dossier_id))
|
| 102 |
+
if type:
|
| 103 |
+
query = query.eq("type", type)
|
| 104 |
+
if date_debut:
|
| 105 |
+
query = query.gte("date_reception", str(date_debut))
|
| 106 |
+
if date_fin:
|
| 107 |
+
query = query.lte("date_reception", str(date_fin))
|
| 108 |
+
|
| 109 |
+
# Pagination
|
| 110 |
+
offset = (page - 1) * limit
|
| 111 |
+
query = query.order("date_reception", desc=True).range(
|
| 112 |
+
offset, offset + limit - 1)
|
| 113 |
+
|
| 114 |
+
response = query.execute()
|
| 115 |
+
total = response.count or 0
|
| 116 |
+
|
| 117 |
+
return {
|
| 118 |
+
"data": response.data or [],
|
| 119 |
+
"total": total,
|
| 120 |
+
"page": page,
|
| 121 |
+
"limit": limit,
|
| 122 |
+
"pages": ceil(total / limit) if total > 0 else 1,
|
| 123 |
+
}
|
| 124 |
|
| 125 |
|
| 126 |
@router.get("/dossier/{dossier_id}", response_model=List[PaiementResponse])
|
|
|
|
| 128 |
dossier_id: UUID,
|
| 129 |
espace_user: CurrentUser = Depends(require_permission("paiement:read")),
|
| 130 |
):
|
| 131 |
+
"""Liste les paiements d'un dossier."""
|
| 132 |
response = (
|
| 133 |
supabase_admin.table("paiements")
|
| 134 |
.select("*")
|
| 135 |
.eq("dossier_id", str(dossier_id))
|
| 136 |
.eq("espace_id", espace_user.espace_id)
|
| 137 |
+
.eq("is_archived", False)
|
| 138 |
.order("date_reception", desc=True)
|
| 139 |
.execute()
|
| 140 |
)
|
|
|
|
| 146 |
client_id: UUID,
|
| 147 |
espace_user: CurrentUser = Depends(require_permission("paiement:read")),
|
| 148 |
):
|
| 149 |
+
"""Liste les paiements d'un client."""
|
| 150 |
response = (
|
| 151 |
supabase_admin.table("paiements")
|
| 152 |
.select("*")
|
| 153 |
.eq("client_id", str(client_id))
|
| 154 |
.eq("espace_id", espace_user.espace_id)
|
| 155 |
+
.eq("is_archived", False)
|
| 156 |
.order("date_reception", desc=True)
|
| 157 |
.execute()
|
| 158 |
)
|
|
|
|
| 164 |
paiement_id: UUID,
|
| 165 |
espace_user: CurrentUser = Depends(require_permission("paiement:read")),
|
| 166 |
):
|
| 167 |
+
"""Récupère un paiement par son ID."""
|
| 168 |
response = (
|
| 169 |
supabase_admin.table("paiements")
|
| 170 |
.select("*")
|
| 171 |
.eq("id", str(paiement_id))
|
| 172 |
.eq("espace_id", espace_user.espace_id)
|
| 173 |
+
.eq("is_archived", False)
|
| 174 |
.single()
|
| 175 |
.execute()
|
| 176 |
)
|
|
|
|
| 185 |
payload: PaiementUpdate,
|
| 186 |
espace_user: CurrentUser = Depends(require_permission("paiement:write")),
|
| 187 |
):
|
| 188 |
+
"""Met à jour un paiement."""
|
| 189 |
data = payload.model_dump(exclude_none=True)
|
| 190 |
if not data:
|
| 191 |
raise HTTPException(status_code=400, detail="Aucune donnée à modifier")
|
|
|
|
| 197 |
.update(data)
|
| 198 |
.eq("id", str(paiement_id))
|
| 199 |
.eq("espace_id", espace_user.espace_id)
|
| 200 |
+
.eq("is_archived", False)
|
| 201 |
.execute()
|
| 202 |
)
|
| 203 |
if not response.data:
|
|
|
|
| 206 |
|
| 207 |
|
| 208 |
@router.delete("/{paiement_id}", response_model=MessageResponse)
|
| 209 |
+
async def archive_paiement(
|
| 210 |
paiement_id: UUID,
|
| 211 |
espace_user: CurrentUser = Depends(require_permission("paiement:delete")),
|
| 212 |
):
|
| 213 |
+
"""Archive un paiement (soft delete)."""
|
| 214 |
+
response = (
|
| 215 |
+
supabase_admin.table("paiements")
|
| 216 |
+
.update({
|
| 217 |
+
"is_archived": True,
|
| 218 |
+
"archived_at": datetime.now(timezone.utc).isoformat(),
|
| 219 |
+
})
|
| 220 |
+
.eq("id", str(paiement_id))
|
| 221 |
+
.eq("espace_id", espace_user.espace_id)
|
| 222 |
+
.eq("is_archived", False)
|
| 223 |
+
.execute()
|
| 224 |
+
)
|
| 225 |
+
if not response.data:
|
| 226 |
+
raise HTTPException(status_code=404, detail="Paiement introuvable")
|
| 227 |
+
return {"message": "Paiement archivé"}
|
app/routers/utilisateurs.py
CHANGED
|
@@ -1,58 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from typing import List
|
| 2 |
from uuid import UUID
|
|
|
|
| 3 |
from fastapi import APIRouter, HTTPException, Depends
|
|
|
|
| 4 |
from app.models.schemas import (
|
| 5 |
-
|
| 6 |
)
|
| 7 |
-
from app.core.auth import get_current_user,
|
| 8 |
-
from app.core.permissions import is_espace_admin
|
| 9 |
from app.core.supabase import supabase_admin
|
| 10 |
|
| 11 |
router = APIRouter(prefix="/utilisateurs", tags=["Utilisateurs"])
|
| 12 |
|
| 13 |
|
| 14 |
@router.get("/me", response_model=UtilisateurResponse)
|
| 15 |
-
async def
|
| 16 |
-
|
|
|
|
|
|
|
| 17 |
response = (
|
| 18 |
supabase_admin.table("utilisateurs")
|
| 19 |
.select("*")
|
| 20 |
-
.eq("id",
|
| 21 |
.single()
|
| 22 |
.execute()
|
| 23 |
)
|
| 24 |
if not response.data:
|
| 25 |
-
raise HTTPException(status_code=404, detail="
|
| 26 |
return response.data
|
| 27 |
|
| 28 |
|
| 29 |
@router.patch("/me", response_model=UtilisateurResponse)
|
| 30 |
-
async def
|
| 31 |
payload: UtilisateurUpdate,
|
| 32 |
current_user: CurrentUser = Depends(get_current_user),
|
| 33 |
):
|
| 34 |
-
"""
|
| 35 |
data = payload.model_dump(exclude_none=True)
|
| 36 |
if not data:
|
| 37 |
raise HTTPException(status_code=400, detail="Aucune donnée à modifier")
|
|
|
|
| 38 |
response = (
|
| 39 |
supabase_admin.table("utilisateurs")
|
| 40 |
.update(data)
|
| 41 |
-
.eq("id",
|
| 42 |
.execute()
|
| 43 |
)
|
|
|
|
|
|
|
| 44 |
return response.data[0]
|
| 45 |
|
| 46 |
|
| 47 |
@router.get("/", response_model=List[UtilisateurResponse])
|
| 48 |
async def list_utilisateurs(
|
| 49 |
-
current_user: CurrentUser = Depends(
|
| 50 |
):
|
| 51 |
-
"""
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
"""
|
| 56 |
response = (
|
| 57 |
supabase_admin.table("utilisateurs")
|
| 58 |
.select("*")
|
|
@@ -66,9 +76,12 @@ async def list_utilisateurs(
|
|
| 66 |
@router.get("/{utilisateur_id}", response_model=UtilisateurResponse)
|
| 67 |
async def get_utilisateur(
|
| 68 |
utilisateur_id: UUID,
|
| 69 |
-
current_user: CurrentUser = Depends(
|
| 70 |
):
|
| 71 |
-
"""
|
|
|
|
|
|
|
|
|
|
| 72 |
response = (
|
| 73 |
supabase_admin.table("utilisateurs")
|
| 74 |
.select("*")
|
|
@@ -78,67 +91,40 @@ async def get_utilisateur(
|
|
| 78 |
.execute()
|
| 79 |
)
|
| 80 |
if not response.data:
|
| 81 |
-
raise HTTPException(
|
| 82 |
-
status_code=404, detail="Utilisateur introuvable dans cet espace")
|
| 83 |
return response.data
|
| 84 |
|
| 85 |
|
| 86 |
-
@router.patch("/{utilisateur_id}/role
|
| 87 |
async def update_role_cabinet(
|
| 88 |
utilisateur_id: UUID,
|
| 89 |
payload: UtilisateurUpdateRoleCabinet,
|
| 90 |
current_user: CurrentUser = Depends(require_espace_admin),
|
| 91 |
):
|
| 92 |
"""
|
| 93 |
-
|
| 94 |
-
Réservé aux admins de l'espace (
|
| 95 |
-
|
| 96 |
-
Attention : changer le role_cabinet peut changer le statut admin.
|
| 97 |
-
Ex : passer un avocat en office_manager → il devient admin.
|
| 98 |
-
passer un associe_gerant en juriste → il perd ses droits admin.
|
| 99 |
"""
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
status_code=400, detail="Vous ne pouvez pas modifier votre propre rôle")
|
| 103 |
-
|
| 104 |
-
# Vérifier que la cible est bien dans le même espace
|
| 105 |
-
user = (
|
| 106 |
supabase_admin.table("utilisateurs")
|
| 107 |
-
.select("id
|
| 108 |
.eq("id", str(utilisateur_id))
|
| 109 |
.eq("espace_id", current_user.espace_id)
|
| 110 |
.single()
|
| 111 |
.execute()
|
| 112 |
)
|
| 113 |
-
if not
|
| 114 |
raise HTTPException(
|
| 115 |
status_code=404, detail="Utilisateur introuvable dans cet espace")
|
| 116 |
|
| 117 |
-
# Vérifier qu'on ne retire pas le dernier admin
|
| 118 |
-
# (si la cible est admin et que le nouveau rôle ne l'est plus)
|
| 119 |
-
if is_espace_admin(user.data["role_cabinet"]) and not is_espace_admin(payload.role_cabinet):
|
| 120 |
-
# Compter les admins restants dans l'espace
|
| 121 |
-
all_membres = (
|
| 122 |
-
supabase_admin.table("utilisateurs")
|
| 123 |
-
.select("role_cabinet")
|
| 124 |
-
.eq("espace_id", current_user.espace_id)
|
| 125 |
-
.execute()
|
| 126 |
-
)
|
| 127 |
-
admin_count = sum(
|
| 128 |
-
1 for m in (all_membres.data or [])
|
| 129 |
-
if is_espace_admin(m["role_cabinet"])
|
| 130 |
-
)
|
| 131 |
-
if admin_count <= 1:
|
| 132 |
-
raise HTTPException(
|
| 133 |
-
status_code=400,
|
| 134 |
-
detail="Impossible : l'espace doit conserver au moins un admin "
|
| 135 |
-
"(associé gérant ou office manager)",
|
| 136 |
-
)
|
| 137 |
-
|
| 138 |
response = (
|
| 139 |
supabase_admin.table("utilisateurs")
|
| 140 |
.update({"role_cabinet": payload.role_cabinet.value})
|
| 141 |
.eq("id", str(utilisateur_id))
|
| 142 |
.execute()
|
| 143 |
)
|
|
|
|
|
|
|
|
|
|
| 144 |
return response.data[0]
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Dedalys Backend — Router Utilisateurs
|
| 3 |
+
Endpoints pour la gestion du profil et des utilisateurs de l'espace.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
from typing import List
|
| 7 |
from uuid import UUID
|
| 8 |
+
|
| 9 |
from fastapi import APIRouter, HTTPException, Depends
|
| 10 |
+
|
| 11 |
from app.models.schemas import (
|
| 12 |
+
UtilisateurUpdate, UtilisateurUpdateRoleCabinet, UtilisateurResponse,
|
| 13 |
)
|
| 14 |
+
from app.core.auth import get_current_user, require_espace_admin, CurrentUser
|
|
|
|
| 15 |
from app.core.supabase import supabase_admin
|
| 16 |
|
| 17 |
router = APIRouter(prefix="/utilisateurs", tags=["Utilisateurs"])
|
| 18 |
|
| 19 |
|
| 20 |
@router.get("/me", response_model=UtilisateurResponse)
|
| 21 |
+
async def get_my_profile(
|
| 22 |
+
current_user: CurrentUser = Depends(get_current_user),
|
| 23 |
+
):
|
| 24 |
+
"""Récupère le profil de l'utilisateur connecté."""
|
| 25 |
response = (
|
| 26 |
supabase_admin.table("utilisateurs")
|
| 27 |
.select("*")
|
| 28 |
+
.eq("id", current_user.id)
|
| 29 |
.single()
|
| 30 |
.execute()
|
| 31 |
)
|
| 32 |
if not response.data:
|
| 33 |
+
raise HTTPException(status_code=404, detail="Profil introuvable")
|
| 34 |
return response.data
|
| 35 |
|
| 36 |
|
| 37 |
@router.patch("/me", response_model=UtilisateurResponse)
|
| 38 |
+
async def update_my_profile(
|
| 39 |
payload: UtilisateurUpdate,
|
| 40 |
current_user: CurrentUser = Depends(get_current_user),
|
| 41 |
):
|
| 42 |
+
"""Met à jour le profil de l'utilisateur connecté (nom, prénom uniquement)."""
|
| 43 |
data = payload.model_dump(exclude_none=True)
|
| 44 |
if not data:
|
| 45 |
raise HTTPException(status_code=400, detail="Aucune donnée à modifier")
|
| 46 |
+
|
| 47 |
response = (
|
| 48 |
supabase_admin.table("utilisateurs")
|
| 49 |
.update(data)
|
| 50 |
+
.eq("id", current_user.id)
|
| 51 |
.execute()
|
| 52 |
)
|
| 53 |
+
if not response.data:
|
| 54 |
+
raise HTTPException(status_code=500, detail="Échec de la mise à jour")
|
| 55 |
return response.data[0]
|
| 56 |
|
| 57 |
|
| 58 |
@router.get("/", response_model=List[UtilisateurResponse])
|
| 59 |
async def list_utilisateurs(
|
| 60 |
+
current_user: CurrentUser = Depends(get_current_user),
|
| 61 |
):
|
| 62 |
+
"""Liste les utilisateurs de l'espace courant."""
|
| 63 |
+
if not current_user.espace_id:
|
| 64 |
+
raise HTTPException(status_code=403, detail="Non rattaché à un espace")
|
| 65 |
+
|
|
|
|
| 66 |
response = (
|
| 67 |
supabase_admin.table("utilisateurs")
|
| 68 |
.select("*")
|
|
|
|
| 76 |
@router.get("/{utilisateur_id}", response_model=UtilisateurResponse)
|
| 77 |
async def get_utilisateur(
|
| 78 |
utilisateur_id: UUID,
|
| 79 |
+
current_user: CurrentUser = Depends(get_current_user),
|
| 80 |
):
|
| 81 |
+
"""Récupère un utilisateur de l'espace courant."""
|
| 82 |
+
if not current_user.espace_id:
|
| 83 |
+
raise HTTPException(status_code=403, detail="Non rattaché à un espace")
|
| 84 |
+
|
| 85 |
response = (
|
| 86 |
supabase_admin.table("utilisateurs")
|
| 87 |
.select("*")
|
|
|
|
| 91 |
.execute()
|
| 92 |
)
|
| 93 |
if not response.data:
|
| 94 |
+
raise HTTPException(status_code=404, detail="Utilisateur introuvable")
|
|
|
|
| 95 |
return response.data
|
| 96 |
|
| 97 |
|
| 98 |
+
@router.patch("/{utilisateur_id}/role", response_model=UtilisateurResponse)
|
| 99 |
async def update_role_cabinet(
|
| 100 |
utilisateur_id: UUID,
|
| 101 |
payload: UtilisateurUpdateRoleCabinet,
|
| 102 |
current_user: CurrentUser = Depends(require_espace_admin),
|
| 103 |
):
|
| 104 |
"""
|
| 105 |
+
Met à jour le rôle cabinet d'un utilisateur.
|
| 106 |
+
Réservé aux admins de l'espace (associé gérant, office manager).
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
"""
|
| 108 |
+
# Vérifier que l'utilisateur appartient à l'espace
|
| 109 |
+
user_check = (
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
supabase_admin.table("utilisateurs")
|
| 111 |
+
.select("id")
|
| 112 |
.eq("id", str(utilisateur_id))
|
| 113 |
.eq("espace_id", current_user.espace_id)
|
| 114 |
.single()
|
| 115 |
.execute()
|
| 116 |
)
|
| 117 |
+
if not user_check.data:
|
| 118 |
raise HTTPException(
|
| 119 |
status_code=404, detail="Utilisateur introuvable dans cet espace")
|
| 120 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
response = (
|
| 122 |
supabase_admin.table("utilisateurs")
|
| 123 |
.update({"role_cabinet": payload.role_cabinet.value})
|
| 124 |
.eq("id", str(utilisateur_id))
|
| 125 |
.execute()
|
| 126 |
)
|
| 127 |
+
if not response.data:
|
| 128 |
+
raise HTTPException(
|
| 129 |
+
status_code=500, detail="Échec de la mise à jour du rôle")
|
| 130 |
return response.data[0]
|
app/sql/schema.sql
ADDED
|
@@ -0,0 +1,438 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
-- ══════════════════════════════════════════════════════════════════════════════
|
| 2 |
+
-- DEDALYS — Schéma de base de données
|
| 3 |
+
-- PostgreSQL 15+ via Supabase
|
| 4 |
+
-- Version: 1.0.0 — Audit Backend v2
|
| 5 |
+
-- ══════════════════════════════════════════════════════════════════════════════
|
| 6 |
+
|
| 7 |
+
-- ══════════════════════════════════════════════════════════════════════════════
|
| 8 |
+
-- EXTENSIONS
|
| 9 |
+
-- ══════════════════════════════════════════════════════════════════════════════
|
| 10 |
+
|
| 11 |
+
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
-- ══════════════════════════════════════════════════════════════════════════════
|
| 15 |
+
-- TABLES
|
| 16 |
+
-- ══════════════════════════════════════════════════════════════════════════════
|
| 17 |
+
|
| 18 |
+
-- ── Espaces (Cabinets) ──────────────────────────────────────────────────────
|
| 19 |
+
|
| 20 |
+
CREATE TABLE IF NOT EXISTS espaces (
|
| 21 |
+
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
| 22 |
+
nom VARCHAR(255) NOT NULL,
|
| 23 |
+
is_archived BOOLEAN DEFAULT FALSE,
|
| 24 |
+
archived_at TIMESTAMPTZ,
|
| 25 |
+
created_at TIMESTAMPTZ DEFAULT NOW()
|
| 26 |
+
);
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
-- ── Utilisateurs ────────────────────────────────────────────────────────────
|
| 30 |
+
|
| 31 |
+
CREATE TABLE IF NOT EXISTS utilisateurs (
|
| 32 |
+
id UUID PRIMARY KEY, -- Lié à auth.users
|
| 33 |
+
email VARCHAR(255) NOT NULL UNIQUE,
|
| 34 |
+
nom VARCHAR(100) NOT NULL,
|
| 35 |
+
prenom VARCHAR(100) NOT NULL,
|
| 36 |
+
role_cabinet VARCHAR(50) NOT NULL CHECK (role_cabinet IN ('associe_gerant', 'avocat', 'juriste', 'office_manager')),
|
| 37 |
+
espace_id UUID REFERENCES espaces(id) ON DELETE CASCADE,
|
| 38 |
+
is_superadmin BOOLEAN DEFAULT FALSE,
|
| 39 |
+
created_at TIMESTAMPTZ DEFAULT NOW()
|
| 40 |
+
);
|
| 41 |
+
|
| 42 |
+
CREATE INDEX IF NOT EXISTS idx_utilisateurs_espace ON utilisateurs(espace_id);
|
| 43 |
+
CREATE INDEX IF NOT EXISTS idx_utilisateurs_email ON utilisateurs(email);
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
-- ── Clients ─────────────────────────────────────────────────────────────────
|
| 47 |
+
|
| 48 |
+
CREATE TABLE IF NOT EXISTS clients (
|
| 49 |
+
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
| 50 |
+
espace_id UUID NOT NULL REFERENCES espaces(id) ON DELETE CASCADE,
|
| 51 |
+
raison_sociale VARCHAR(255) NOT NULL,
|
| 52 |
+
email_principal VARCHAR(255) NOT NULL,
|
| 53 |
+
telephone VARCHAR(20) NOT NULL,
|
| 54 |
+
statut VARCHAR(2) NOT NULL CHECK (statut IN ('PP', 'PM')),
|
| 55 |
+
forme_juridique VARCHAR(100),
|
| 56 |
+
representant_legal VARCHAR(255),
|
| 57 |
+
revenu_attendu_total DECIMAL(15, 2),
|
| 58 |
+
is_archived BOOLEAN DEFAULT FALSE,
|
| 59 |
+
archived_at TIMESTAMPTZ,
|
| 60 |
+
created_at TIMESTAMPTZ DEFAULT NOW()
|
| 61 |
+
);
|
| 62 |
+
|
| 63 |
+
CREATE INDEX IF NOT EXISTS idx_clients_espace ON clients(espace_id);
|
| 64 |
+
CREATE INDEX IF NOT EXISTS idx_clients_archived ON clients(espace_id, is_archived);
|
| 65 |
+
CREATE INDEX IF NOT EXISTS idx_clients_search ON clients(espace_id, raison_sociale, email_principal);
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
-- ── Points de Contact ───────────────────────────────────────────────────────
|
| 69 |
+
|
| 70 |
+
CREATE TABLE IF NOT EXISTS points_de_contact (
|
| 71 |
+
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
| 72 |
+
espace_id UUID NOT NULL REFERENCES espaces(id) ON DELETE CASCADE,
|
| 73 |
+
client_id UUID NOT NULL REFERENCES clients(id) ON DELETE CASCADE,
|
| 74 |
+
nom_complet VARCHAR(255) NOT NULL,
|
| 75 |
+
telephone VARCHAR(20) NOT NULL,
|
| 76 |
+
email VARCHAR(255) NOT NULL,
|
| 77 |
+
fonction VARCHAR(100),
|
| 78 |
+
is_archived BOOLEAN DEFAULT FALSE,
|
| 79 |
+
archived_at TIMESTAMPTZ,
|
| 80 |
+
created_at TIMESTAMPTZ DEFAULT NOW()
|
| 81 |
+
);
|
| 82 |
+
|
| 83 |
+
CREATE INDEX IF NOT EXISTS idx_contacts_client ON points_de_contact(client_id);
|
| 84 |
+
CREATE INDEX IF NOT EXISTS idx_contacts_espace ON points_de_contact(espace_id);
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
-- ── Dossiers ────────────────────────────────────────────────────────────────
|
| 88 |
+
|
| 89 |
+
CREATE TABLE IF NOT EXISTS dossiers (
|
| 90 |
+
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
| 91 |
+
espace_id UUID NOT NULL REFERENCES espaces(id) ON DELETE CASCADE,
|
| 92 |
+
client_id UUID NOT NULL REFERENCES clients(id) ON DELETE CASCADE,
|
| 93 |
+
reference VARCHAR(50) NOT NULL,
|
| 94 |
+
titre VARCHAR(255),
|
| 95 |
+
type VARCHAR(50) NOT NULL CHECK (type IN ('pre_contentieux', 'contentieux', 'conseil', 'transactionnel')),
|
| 96 |
+
description TEXT NOT NULL,
|
| 97 |
+
statut VARCHAR(20) DEFAULT 'ouvert' CHECK (statut IN ('ouvert', 'en_instance', 'cloture')),
|
| 98 |
+
partie_adverse VARCHAR(255),
|
| 99 |
+
preference_facturation VARCHAR(20) NOT NULL CHECK (preference_facturation IN ('forfait', 'capped_fees')),
|
| 100 |
+
revenu_attendu DECIMAL(15, 2),
|
| 101 |
+
is_archived BOOLEAN DEFAULT FALSE,
|
| 102 |
+
archived_at TIMESTAMPTZ,
|
| 103 |
+
created_at TIMESTAMPTZ DEFAULT NOW()
|
| 104 |
+
);
|
| 105 |
+
|
| 106 |
+
CREATE INDEX IF NOT EXISTS idx_dossiers_espace ON dossiers(espace_id);
|
| 107 |
+
CREATE INDEX IF NOT EXISTS idx_dossiers_client ON dossiers(client_id);
|
| 108 |
+
CREATE INDEX IF NOT EXISTS idx_dossiers_archived ON dossiers(espace_id, is_archived);
|
| 109 |
+
CREATE INDEX IF NOT EXISTS idx_dossiers_statut ON dossiers(espace_id, statut);
|
| 110 |
+
CREATE INDEX IF NOT EXISTS idx_dossiers_reference ON dossiers(reference);
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
-- ── Équipe Dossier ──────────────────────────────────────────────────────────
|
| 114 |
+
|
| 115 |
+
CREATE TABLE IF NOT EXISTS equipe_dossier (
|
| 116 |
+
dossier_id UUID NOT NULL REFERENCES dossiers(id) ON DELETE CASCADE,
|
| 117 |
+
utilisateur_id UUID NOT NULL REFERENCES utilisateurs(id) ON DELETE CASCADE,
|
| 118 |
+
role VARCHAR(20) NOT NULL CHECK (role IN ('responsable', 'collaborateur')),
|
| 119 |
+
PRIMARY KEY (dossier_id, utilisateur_id)
|
| 120 |
+
);
|
| 121 |
+
|
| 122 |
+
CREATE INDEX IF NOT EXISTS idx_equipe_utilisateur ON equipe_dossier(utilisateur_id);
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
-- ── Audiences ───────────────────────────────────────────────────────────────
|
| 126 |
+
|
| 127 |
+
CREATE TABLE IF NOT EXISTS audiences (
|
| 128 |
+
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
| 129 |
+
espace_id UUID NOT NULL REFERENCES espaces(id) ON DELETE CASCADE,
|
| 130 |
+
dossier_id UUID NOT NULL REFERENCES dossiers(id) ON DELETE CASCADE,
|
| 131 |
+
avocat_assigne_id UUID NOT NULL REFERENCES utilisateurs(id),
|
| 132 |
+
date DATE NOT NULL,
|
| 133 |
+
heure TIME NOT NULL,
|
| 134 |
+
type VARCHAR(20) DEFAULT 'audience' CHECK (type IN ('audience', 'reunion')),
|
| 135 |
+
juridiction VARCHAR(255), -- Obligatoire si type='audience'
|
| 136 |
+
notes TEXT,
|
| 137 |
+
rappel_j7_envoye BOOLEAN DEFAULT FALSE,
|
| 138 |
+
rappel_j3_envoye BOOLEAN DEFAULT FALSE,
|
| 139 |
+
rappel_j1_envoye BOOLEAN DEFAULT FALSE,
|
| 140 |
+
is_archived BOOLEAN DEFAULT FALSE,
|
| 141 |
+
archived_at TIMESTAMPTZ,
|
| 142 |
+
created_at TIMESTAMPTZ DEFAULT NOW()
|
| 143 |
+
);
|
| 144 |
+
|
| 145 |
+
CREATE INDEX IF NOT EXISTS idx_audiences_espace ON audiences(espace_id);
|
| 146 |
+
CREATE INDEX IF NOT EXISTS idx_audiences_dossier ON audiences(dossier_id);
|
| 147 |
+
CREATE INDEX IF NOT EXISTS idx_audiences_avocat ON audiences(avocat_assigne_id);
|
| 148 |
+
CREATE INDEX IF NOT EXISTS idx_audiences_date ON audiences(espace_id, date);
|
| 149 |
+
CREATE INDEX IF NOT EXISTS idx_audiences_rappels ON audiences(date, rappel_j7_envoye, rappel_j3_envoye, rappel_j1_envoye)
|
| 150 |
+
WHERE is_archived = FALSE;
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
-- ── Flash CR ────────────────────────────────────────────────────────────────
|
| 154 |
+
|
| 155 |
+
CREATE TABLE IF NOT EXISTS flash_cr (
|
| 156 |
+
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
| 157 |
+
espace_id UUID NOT NULL REFERENCES espaces(id) ON DELETE CASCADE,
|
| 158 |
+
audience_id UUID NOT NULL REFERENCES audiences(id) ON DELETE CASCADE,
|
| 159 |
+
type_decision VARCHAR(30) NOT NULL CHECK (type_decision IN ('decision_rendue', 'mise_en_delibere', 'renvoi', 'autre')),
|
| 160 |
+
prochaine_date DATE, -- Obligatoire si mise_en_delibere ou renvoi
|
| 161 |
+
notes_rapides VARCHAR(500) NOT NULL,
|
| 162 |
+
envoyer_email BOOLEAN DEFAULT TRUE,
|
| 163 |
+
email_envoye BOOLEAN DEFAULT FALSE,
|
| 164 |
+
email_envoye_at TIMESTAMPTZ,
|
| 165 |
+
is_archived BOOLEAN DEFAULT FALSE,
|
| 166 |
+
archived_at TIMESTAMPTZ,
|
| 167 |
+
created_at TIMESTAMPTZ DEFAULT NOW(),
|
| 168 |
+
UNIQUE(audience_id) -- Un seul Flash CR par audience
|
| 169 |
+
);
|
| 170 |
+
|
| 171 |
+
CREATE INDEX IF NOT EXISTS idx_flash_cr_espace ON flash_cr(espace_id);
|
| 172 |
+
CREATE INDEX IF NOT EXISTS idx_flash_cr_audience ON flash_cr(audience_id);
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
-- ── Paiements ───────────────────────────────────────────────────────────────
|
| 176 |
+
|
| 177 |
+
CREATE TABLE IF NOT EXISTS paiements (
|
| 178 |
+
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
| 179 |
+
espace_id UUID NOT NULL REFERENCES espaces(id) ON DELETE CASCADE,
|
| 180 |
+
client_id UUID NOT NULL REFERENCES clients(id) ON DELETE CASCADE,
|
| 181 |
+
dossier_id UUID NOT NULL REFERENCES dossiers(id) ON DELETE CASCADE,
|
| 182 |
+
montant DECIMAL(15, 2) NOT NULL CHECK (montant > 0),
|
| 183 |
+
date_reception DATE NOT NULL,
|
| 184 |
+
type VARCHAR(20) NOT NULL CHECK (type IN ('honoraires', 'frais')),
|
| 185 |
+
description VARCHAR(500),
|
| 186 |
+
is_archived BOOLEAN DEFAULT FALSE,
|
| 187 |
+
archived_at TIMESTAMPTZ,
|
| 188 |
+
created_at TIMESTAMPTZ DEFAULT NOW()
|
| 189 |
+
);
|
| 190 |
+
|
| 191 |
+
CREATE INDEX IF NOT EXISTS idx_paiements_espace ON paiements(espace_id);
|
| 192 |
+
CREATE INDEX IF NOT EXISTS idx_paiements_client ON paiements(client_id);
|
| 193 |
+
CREATE INDEX IF NOT EXISTS idx_paiements_dossier ON paiements(dossier_id);
|
| 194 |
+
CREATE INDEX IF NOT EXISTS idx_paiements_date ON paiements(espace_id, date_reception);
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
-- ── Fichiers ────────────────────────────────────────────────────────────────
|
| 198 |
+
|
| 199 |
+
CREATE TABLE IF NOT EXISTS fichiers (
|
| 200 |
+
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
| 201 |
+
espace_id UUID NOT NULL REFERENCES espaces(id) ON DELETE CASCADE,
|
| 202 |
+
dossier_id UUID NOT NULL REFERENCES dossiers(id) ON DELETE CASCADE,
|
| 203 |
+
nom VARCHAR(255) NOT NULL,
|
| 204 |
+
taille INTEGER NOT NULL,
|
| 205 |
+
type_fichier VARCHAR(100) NOT NULL,
|
| 206 |
+
chemin_stockage VARCHAR(500) NOT NULL,
|
| 207 |
+
is_archived BOOLEAN DEFAULT FALSE,
|
| 208 |
+
archived_at TIMESTAMPTZ,
|
| 209 |
+
created_at TIMESTAMPTZ DEFAULT NOW()
|
| 210 |
+
);
|
| 211 |
+
|
| 212 |
+
CREATE INDEX IF NOT EXISTS idx_fichiers_espace ON fichiers(espace_id);
|
| 213 |
+
CREATE INDEX IF NOT EXISTS idx_fichiers_dossier ON fichiers(dossier_id);
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
-- ── Audit Logs ──────────────────────────────────────────────────────────────
|
| 217 |
+
|
| 218 |
+
CREATE TABLE IF NOT EXISTS audit_logs (
|
| 219 |
+
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
| 220 |
+
espace_id UUID NOT NULL REFERENCES espaces(id) ON DELETE CASCADE,
|
| 221 |
+
user_id UUID NOT NULL REFERENCES utilisateurs(id),
|
| 222 |
+
action VARCHAR(30) NOT NULL CHECK (action IN ('creation', 'modification', 'archivage')),
|
| 223 |
+
ressource VARCHAR(50) NOT NULL CHECK (ressource IN ('clients', 'dossiers', 'audiences', 'flash_cr', 'paiements', 'fichiers', 'utilisateurs')),
|
| 224 |
+
ressource_id UUID NOT NULL,
|
| 225 |
+
valeur_avant JSONB,
|
| 226 |
+
valeur_apres JSONB,
|
| 227 |
+
timestamp TIMESTAMPTZ DEFAULT NOW()
|
| 228 |
+
);
|
| 229 |
+
|
| 230 |
+
CREATE INDEX IF NOT EXISTS idx_audit_espace ON audit_logs(espace_id);
|
| 231 |
+
CREATE INDEX IF NOT EXISTS idx_audit_ressource ON audit_logs(espace_id, ressource);
|
| 232 |
+
CREATE INDEX IF NOT EXISTS idx_audit_user ON audit_logs(user_id);
|
| 233 |
+
CREATE INDEX IF NOT EXISTS idx_audit_timestamp ON audit_logs(espace_id, timestamp);
|
| 234 |
+
CREATE INDEX IF NOT EXISTS idx_audit_ressource_id ON audit_logs(ressource_id);
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
-- ══════════════════════════════════════════════════════════════════════════════
|
| 238 |
+
-- ROW LEVEL SECURITY (RLS)
|
| 239 |
+
-- ══════════════════════════════════════════════════════════════════════════════
|
| 240 |
+
-- Note: L'API utilise le service_role qui bypass RLS.
|
| 241 |
+
-- Ces policies sont une couche de sécurité supplémentaire pour les accès directs.
|
| 242 |
+
-- ══════════════════════════════════════════════════════════════════════════════
|
| 243 |
+
|
| 244 |
+
-- Activer RLS sur toutes les tables métier
|
| 245 |
+
ALTER TABLE clients ENABLE ROW LEVEL SECURITY;
|
| 246 |
+
ALTER TABLE points_de_contact ENABLE ROW LEVEL SECURITY;
|
| 247 |
+
ALTER TABLE dossiers ENABLE ROW LEVEL SECURITY;
|
| 248 |
+
ALTER TABLE equipe_dossier ENABLE ROW LEVEL SECURITY;
|
| 249 |
+
ALTER TABLE audiences ENABLE ROW LEVEL SECURITY;
|
| 250 |
+
ALTER TABLE flash_cr ENABLE ROW LEVEL SECURITY;
|
| 251 |
+
ALTER TABLE paiements ENABLE ROW LEVEL SECURITY;
|
| 252 |
+
ALTER TABLE fichiers ENABLE ROW LEVEL SECURITY;
|
| 253 |
+
ALTER TABLE audit_logs ENABLE ROW LEVEL SECURITY;
|
| 254 |
+
ALTER TABLE utilisateurs ENABLE ROW LEVEL SECURITY;
|
| 255 |
+
ALTER TABLE espaces ENABLE ROW LEVEL SECURITY;
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
-- ── Fonction helper pour récupérer l'espace_id de l'utilisateur courant ─────
|
| 259 |
+
|
| 260 |
+
CREATE OR REPLACE FUNCTION get_user_espace_id()
|
| 261 |
+
RETURNS UUID AS $$
|
| 262 |
+
BEGIN
|
| 263 |
+
RETURN (
|
| 264 |
+
SELECT espace_id
|
| 265 |
+
FROM utilisateurs
|
| 266 |
+
WHERE id = auth.uid()
|
| 267 |
+
);
|
| 268 |
+
END;
|
| 269 |
+
$$ LANGUAGE plpgsql SECURITY DEFINER;
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
-- ── Policies Clients ────────────────────────────────────────────────────────
|
| 273 |
+
|
| 274 |
+
CREATE POLICY "Users can view clients in their espace"
|
| 275 |
+
ON clients FOR SELECT
|
| 276 |
+
USING (espace_id = get_user_espace_id());
|
| 277 |
+
|
| 278 |
+
CREATE POLICY "Users can insert clients in their espace"
|
| 279 |
+
ON clients FOR INSERT
|
| 280 |
+
WITH CHECK (espace_id = get_user_espace_id());
|
| 281 |
+
|
| 282 |
+
CREATE POLICY "Users can update clients in their espace"
|
| 283 |
+
ON clients FOR UPDATE
|
| 284 |
+
USING (espace_id = get_user_espace_id());
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
-- ── Policies Points de Contact ──────────────────────────────────────────────
|
| 288 |
+
|
| 289 |
+
CREATE POLICY "Users can view contacts in their espace"
|
| 290 |
+
ON points_de_contact FOR SELECT
|
| 291 |
+
USING (espace_id = get_user_espace_id());
|
| 292 |
+
|
| 293 |
+
CREATE POLICY "Users can insert contacts in their espace"
|
| 294 |
+
ON points_de_contact FOR INSERT
|
| 295 |
+
WITH CHECK (espace_id = get_user_espace_id());
|
| 296 |
+
|
| 297 |
+
CREATE POLICY "Users can update contacts in their espace"
|
| 298 |
+
ON points_de_contact FOR UPDATE
|
| 299 |
+
USING (espace_id = get_user_espace_id());
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
-- ── Policies Dossiers ───────────────────────────────────────────────────────
|
| 303 |
+
|
| 304 |
+
CREATE POLICY "Users can view dossiers in their espace"
|
| 305 |
+
ON dossiers FOR SELECT
|
| 306 |
+
USING (espace_id = get_user_espace_id());
|
| 307 |
+
|
| 308 |
+
CREATE POLICY "Users can insert dossiers in their espace"
|
| 309 |
+
ON dossiers FOR INSERT
|
| 310 |
+
WITH CHECK (espace_id = get_user_espace_id());
|
| 311 |
+
|
| 312 |
+
CREATE POLICY "Users can update dossiers in their espace"
|
| 313 |
+
ON dossiers FOR UPDATE
|
| 314 |
+
USING (espace_id = get_user_espace_id());
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
-- ── Policies Équipe Dossier ─────────────────────────────────────────────────
|
| 318 |
+
|
| 319 |
+
CREATE POLICY "Users can view equipe for dossiers in their espace"
|
| 320 |
+
ON equipe_dossier FOR SELECT
|
| 321 |
+
USING (
|
| 322 |
+
dossier_id IN (
|
| 323 |
+
SELECT id FROM dossiers WHERE espace_id = get_user_espace_id()
|
| 324 |
+
)
|
| 325 |
+
);
|
| 326 |
+
|
| 327 |
+
CREATE POLICY "Users can modify equipe for dossiers in their espace"
|
| 328 |
+
ON equipe_dossier FOR ALL
|
| 329 |
+
USING (
|
| 330 |
+
dossier_id IN (
|
| 331 |
+
SELECT id FROM dossiers WHERE espace_id = get_user_espace_id()
|
| 332 |
+
)
|
| 333 |
+
);
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
-- ── Policies Audiences ──────────────────────────────────────────────────────
|
| 337 |
+
|
| 338 |
+
CREATE POLICY "Users can view audiences in their espace"
|
| 339 |
+
ON audiences FOR SELECT
|
| 340 |
+
USING (espace_id = get_user_espace_id());
|
| 341 |
+
|
| 342 |
+
CREATE POLICY "Users can insert audiences in their espace"
|
| 343 |
+
ON audiences FOR INSERT
|
| 344 |
+
WITH CHECK (espace_id = get_user_espace_id());
|
| 345 |
+
|
| 346 |
+
CREATE POLICY "Users can update audiences in their espace"
|
| 347 |
+
ON audiences FOR UPDATE
|
| 348 |
+
USING (espace_id = get_user_espace_id());
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
-- ── Policies Flash CR ───────────────────────────────────────────────────────
|
| 352 |
+
|
| 353 |
+
CREATE POLICY "Users can view flash_cr in their espace"
|
| 354 |
+
ON flash_cr FOR SELECT
|
| 355 |
+
USING (espace_id = get_user_espace_id());
|
| 356 |
+
|
| 357 |
+
CREATE POLICY "Users can insert flash_cr in their espace"
|
| 358 |
+
ON flash_cr FOR INSERT
|
| 359 |
+
WITH CHECK (espace_id = get_user_espace_id());
|
| 360 |
+
|
| 361 |
+
CREATE POLICY "Users can update flash_cr in their espace"
|
| 362 |
+
ON flash_cr FOR UPDATE
|
| 363 |
+
USING (espace_id = get_user_espace_id());
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
-- ── Policies Paiements ──────────────────────────────────────────────────────
|
| 367 |
+
|
| 368 |
+
CREATE POLICY "Users can view paiements in their espace"
|
| 369 |
+
ON paiements FOR SELECT
|
| 370 |
+
USING (espace_id = get_user_espace_id());
|
| 371 |
+
|
| 372 |
+
CREATE POLICY "Users can insert paiements in their espace"
|
| 373 |
+
ON paiements FOR INSERT
|
| 374 |
+
WITH CHECK (espace_id = get_user_espace_id());
|
| 375 |
+
|
| 376 |
+
CREATE POLICY "Users can update paiements in their espace"
|
| 377 |
+
ON paiements FOR UPDATE
|
| 378 |
+
USING (espace_id = get_user_espace_id());
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
-- ── Policies Fichiers ───────────────────────────────────────────────────────
|
| 382 |
+
|
| 383 |
+
CREATE POLICY "Users can view fichiers in their espace"
|
| 384 |
+
ON fichiers FOR SELECT
|
| 385 |
+
USING (espace_id = get_user_espace_id());
|
| 386 |
+
|
| 387 |
+
CREATE POLICY "Users can insert fichiers in their espace"
|
| 388 |
+
ON fichiers FOR INSERT
|
| 389 |
+
WITH CHECK (espace_id = get_user_espace_id());
|
| 390 |
+
|
| 391 |
+
CREATE POLICY "Users can update fichiers in their espace"
|
| 392 |
+
ON fichiers FOR UPDATE
|
| 393 |
+
USING (espace_id = get_user_espace_id());
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
-- ── Policies Audit Logs ─────────────────────────────────────────────────────
|
| 397 |
+
|
| 398 |
+
CREATE POLICY "Users can view audit_logs in their espace"
|
| 399 |
+
ON audit_logs FOR SELECT
|
| 400 |
+
USING (espace_id = get_user_espace_id());
|
| 401 |
+
|
| 402 |
+
CREATE POLICY "System can insert audit_logs"
|
| 403 |
+
ON audit_logs FOR INSERT
|
| 404 |
+
WITH CHECK (espace_id = get_user_espace_id());
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
-- ══════════════════════════════════════════════════════════════════════════════
|
| 408 |
+
-- STORAGE BUCKET (à créer via Supabase Dashboard ou CLI)
|
| 409 |
+
-- ══════════════════════════════════════════════════════════════════════════════
|
| 410 |
+
--
|
| 411 |
+
-- Nom du bucket : dedalys-fichiers
|
| 412 |
+
-- Configuration :
|
| 413 |
+
-- - Public : NON (privé)
|
| 414 |
+
-- - File size limit : 10 MB
|
| 415 |
+
-- - Allowed MIME types : application/pdf, application/msword,
|
| 416 |
+
-- application/vnd.openxmlformats-officedocument.wordprocessingml.document,
|
| 417 |
+
-- image/jpeg, image/png
|
| 418 |
+
--
|
| 419 |
+
-- Structure des chemins : {espace_id}/{dossier_id}/{file_uuid}.{ext}
|
| 420 |
+
--
|
| 421 |
+
-- ══════════════════════════════════════════════════════════════════════════════
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
-- ══════════════════════════════════════════════════════════════════════════════
|
| 425 |
+
-- COMMENTAIRES TABLES
|
| 426 |
+
-- ══════════════════════════════════════════════════════════════════════════════
|
| 427 |
+
|
| 428 |
+
COMMENT ON TABLE espaces IS 'Cabinets d''avocats / Directions juridiques';
|
| 429 |
+
COMMENT ON TABLE utilisateurs IS 'Utilisateurs de la plateforme liés à auth.users';
|
| 430 |
+
COMMENT ON TABLE clients IS 'Clients des cabinets (PP ou PM)';
|
| 431 |
+
COMMENT ON TABLE points_de_contact IS 'Contacts multiples par client';
|
| 432 |
+
COMMENT ON TABLE dossiers IS 'Dossiers juridiques liés à un client';
|
| 433 |
+
COMMENT ON TABLE equipe_dossier IS 'Membres de l''équipe assignés à un dossier';
|
| 434 |
+
COMMENT ON TABLE audiences IS 'Audiences tribunal ou réunions internes';
|
| 435 |
+
COMMENT ON TABLE flash_cr IS 'Comptes-rendus rapides post-audience';
|
| 436 |
+
COMMENT ON TABLE paiements IS 'Enregistrement des paiements reçus';
|
| 437 |
+
COMMENT ON TABLE fichiers IS 'Métadonnées des fichiers uploadés';
|
| 438 |
+
COMMENT ON TABLE audit_logs IS 'Trace des actions sensibles';
|
pyproject.toml
CHANGED
|
@@ -5,14 +5,16 @@ description = "Add your description here"
|
|
| 5 |
readme = "README.md"
|
| 6 |
requires-python = ">=3.13"
|
| 7 |
dependencies = [
|
| 8 |
-
"
|
| 9 |
-
"
|
| 10 |
-
"
|
| 11 |
-
"pydantic-
|
| 12 |
-
"pydantic
|
| 13 |
-
"
|
| 14 |
-
"
|
| 15 |
-
"python-
|
| 16 |
-
"
|
| 17 |
-
"
|
|
|
|
|
|
|
| 18 |
]
|
|
|
|
| 5 |
readme = "README.md"
|
| 6 |
requires-python = ">=3.13"
|
| 7 |
dependencies = [
|
| 8 |
+
"email-validator==2.1.0",
|
| 9 |
+
"fastapi==0.109.2",
|
| 10 |
+
"pydantic>=2.8",
|
| 11 |
+
"pydantic-core>=2.20.0",
|
| 12 |
+
"pydantic-settings==2.1.0",
|
| 13 |
+
"pytest>=7.0,<9",
|
| 14 |
+
"pytest-asyncio==0.23.4",
|
| 15 |
+
"python-dateutil==2.8.2",
|
| 16 |
+
"python-dotenv==1.0.1",
|
| 17 |
+
"python-multipart==0.0.9",
|
| 18 |
+
"supabase==2.3.4",
|
| 19 |
+
"uvicorn[standard]==0.27.1",
|
| 20 |
]
|
requirements.txt
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 2 |
+
# DEDALYS BACKEND — Dépendances Python
|
| 3 |
+
# Version: 1.0.0
|
| 4 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 5 |
+
|
| 6 |
+
# Framework
|
| 7 |
+
fastapi==0.109.2
|
| 8 |
+
uvicorn[standard]==0.27.1
|
| 9 |
+
python-multipart==0.0.9
|
| 10 |
+
|
| 11 |
+
# Validation & Settings
|
| 12 |
+
pydantic>=2.8
|
| 13 |
+
pydantic-core>=2.20.0
|
| 14 |
+
pydantic-settings==2.1.0
|
| 15 |
+
python-dotenv==1.0.1
|
| 16 |
+
email-validator==2.1.0
|
| 17 |
+
|
| 18 |
+
# Supabase
|
| 19 |
+
supabase==2.3.4
|
| 20 |
+
|
| 21 |
+
# Date/Time
|
| 22 |
+
python-dateutil==2.8.2
|
| 23 |
+
|
| 24 |
+
# Email (MVP — à activer pour les rappels)
|
| 25 |
+
# resend==0.7.2
|
| 26 |
+
|
| 27 |
+
# Scheduler (MVP — à activer pour les rappels automatiques)
|
| 28 |
+
# apscheduler==3.10.4
|
| 29 |
+
|
| 30 |
+
# Dev & Test
|
| 31 |
+
pytest>=7.0,<9
|
| 32 |
+
pytest-asyncio==0.23.4
|
uv.lock
CHANGED
|
The diff for this file is too large to render.
See raw diff
|
|
|