Spaces:
Runtime error
Runtime error
chrisaka commited on
Commit ·
d628201
1
Parent(s): bd2320a
feat: Add automated daily database backups, subscription expiration reminders, and enhance user creation in espaces.
Browse files- .gitignore +2 -1
- Dockerfile +2 -2
- app/core/__pycache__/backup.cpython-313.pyc +0 -0
- app/core/__pycache__/config.cpython-313.pyc +0 -0
- app/core/__pycache__/email.cpython-313.pyc +0 -0
- app/core/__pycache__/scheduler.cpython-313.pyc +0 -0
- app/core/backup.py +155 -0
- app/core/config.py +8 -0
- app/core/email.py +34 -0
- app/core/scheduler.py +106 -3
- app/models/__pycache__/schemas.cpython-313.pyc +0 -0
- app/models/schemas.py +22 -9
- 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/clients.py +0 -1
- app/routers/dossiers.py +3 -0
- app/routers/espaces.py +45 -5
- pyproject.toml +1 -0
- supabase/migrations/20260302095013_initial_schema.sql +82 -5
- uv.lock +5 -3
.gitignore
CHANGED
|
@@ -1 +1,2 @@
|
|
| 1 |
-
.env
|
|
|
|
|
|
| 1 |
+
.env
|
| 2 |
+
backups/
|
Dockerfile
CHANGED
|
@@ -9,8 +9,8 @@ ENV PYTHONUNBUFFERED=1
|
|
| 9 |
|
| 10 |
WORKDIR /app
|
| 11 |
|
| 12 |
-
# Installation de curl pour le healthcheck et
|
| 13 |
-
RUN apt-get update && apt-get install -y --no-install-recommends curl \
|
| 14 |
&& rm -rf /var/lib/apt/lists/*
|
| 15 |
|
| 16 |
# Copie des requirements.txt
|
|
|
|
| 9 |
|
| 10 |
WORKDIR /app
|
| 11 |
|
| 12 |
+
# Installation de curl pour le healthcheck et postgresql-client pour pg_dump (backups)
|
| 13 |
+
RUN apt-get update && apt-get install -y --no-install-recommends curl postgresql-client \
|
| 14 |
&& rm -rf /var/lib/apt/lists/*
|
| 15 |
|
| 16 |
# Copie des requirements.txt
|
app/core/__pycache__/backup.cpython-313.pyc
ADDED
|
Binary file (7.93 kB). View file
|
|
|
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__/email.cpython-313.pyc
CHANGED
|
Binary files a/app/core/__pycache__/email.cpython-313.pyc and b/app/core/__pycache__/email.cpython-313.pyc differ
|
|
|
app/core/__pycache__/scheduler.cpython-313.pyc
CHANGED
|
Binary files a/app/core/__pycache__/scheduler.cpython-313.pyc and b/app/core/__pycache__/scheduler.cpython-313.pyc differ
|
|
|
app/core/backup.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Dedalys Backend — Backup
|
| 3 |
+
Sauvegarde automatique de la base de données PostgreSQL via pg_dump.
|
| 4 |
+
Les backups sont uploadés dans Supabase Storage (bucket dedalys-backups).
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import logging
|
| 8 |
+
import subprocess
|
| 9 |
+
import os
|
| 10 |
+
import tempfile
|
| 11 |
+
from datetime import datetime, timezone
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
from app.core.config import settings
|
| 15 |
+
from app.core.supabase import supabase_admin
|
| 16 |
+
|
| 17 |
+
logger = logging.getLogger(__name__)
|
| 18 |
+
|
| 19 |
+
# Nombre maximum de backups à conserver
|
| 20 |
+
MAX_BACKUPS = 7
|
| 21 |
+
BACKUP_BUCKET = "dedalys-backups"
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _ensure_bucket():
|
| 25 |
+
"""Crée le bucket de backup s'il n'existe pas."""
|
| 26 |
+
try:
|
| 27 |
+
supabase_admin.storage.get_bucket(BACKUP_BUCKET)
|
| 28 |
+
except Exception:
|
| 29 |
+
try:
|
| 30 |
+
supabase_admin.storage.create_bucket(
|
| 31 |
+
BACKUP_BUCKET,
|
| 32 |
+
options={"public": False},
|
| 33 |
+
)
|
| 34 |
+
logger.info(f"Bucket '{BACKUP_BUCKET}' créé")
|
| 35 |
+
except Exception as e:
|
| 36 |
+
logger.warning(f"Impossible de créer le bucket: {e}")
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def run_backup() -> str | None:
|
| 40 |
+
"""
|
| 41 |
+
Exécute pg_dump, compresse le dump, l'uploade dans Supabase Storage,
|
| 42 |
+
puis supprime le fichier local temporaire.
|
| 43 |
+
Retourne le nom du fichier uploadé ou None en cas d'erreur.
|
| 44 |
+
"""
|
| 45 |
+
if not settings.DB_HOST or not settings.DB_PASSWORD:
|
| 46 |
+
logger.error("DB_HOST ou DB_PASSWORD manquant — backup impossible")
|
| 47 |
+
return None
|
| 48 |
+
|
| 49 |
+
# Nom du fichier avec timestamp
|
| 50 |
+
timestamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
|
| 51 |
+
filename = f"dedalys_backup_{timestamp}.sql.gz"
|
| 52 |
+
|
| 53 |
+
# Utiliser un fichier temporaire
|
| 54 |
+
with tempfile.TemporaryDirectory() as tmpdir:
|
| 55 |
+
filepath = Path(tmpdir) / filename
|
| 56 |
+
|
| 57 |
+
# Construire la commande pg_dump
|
| 58 |
+
env = os.environ.copy()
|
| 59 |
+
env["PGPASSWORD"] = settings.DB_PASSWORD
|
| 60 |
+
|
| 61 |
+
cmd = [
|
| 62 |
+
"pg_dump",
|
| 63 |
+
"-h", settings.DB_HOST,
|
| 64 |
+
"-p", str(settings.DB_PORT),
|
| 65 |
+
"-U", settings.DB_USER,
|
| 66 |
+
"-d", settings.DB_NAME,
|
| 67 |
+
"--no-owner",
|
| 68 |
+
"--no-acl",
|
| 69 |
+
"--clean",
|
| 70 |
+
"--if-exists",
|
| 71 |
+
"-Z", "9", # Compression gzip niveau 9
|
| 72 |
+
"-f", str(filepath),
|
| 73 |
+
]
|
| 74 |
+
|
| 75 |
+
try:
|
| 76 |
+
logger.info(f"Démarrage du backup → {filename}")
|
| 77 |
+
result = subprocess.run(
|
| 78 |
+
cmd,
|
| 79 |
+
env=env,
|
| 80 |
+
capture_output=True,
|
| 81 |
+
text=True,
|
| 82 |
+
timeout=300, # 5 minutes max
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
if result.returncode != 0:
|
| 86 |
+
logger.error(f"pg_dump a échoué (code {result.returncode}): {result.stderr}")
|
| 87 |
+
return None
|
| 88 |
+
|
| 89 |
+
size_mb = filepath.stat().st_size / (1024 * 1024)
|
| 90 |
+
logger.info(f"Dump créé : {filename} ({size_mb:.2f} MB)")
|
| 91 |
+
|
| 92 |
+
# Uploader dans Supabase Storage
|
| 93 |
+
_ensure_bucket()
|
| 94 |
+
with open(filepath, "rb") as f:
|
| 95 |
+
supabase_admin.storage.from_(BACKUP_BUCKET).upload(
|
| 96 |
+
filename,
|
| 97 |
+
f,
|
| 98 |
+
file_options={"content-type": "application/gzip"},
|
| 99 |
+
)
|
| 100 |
+
logger.info(f"Backup uploadé dans Supabase Storage : {filename}")
|
| 101 |
+
|
| 102 |
+
# Nettoyer les anciens backups
|
| 103 |
+
_cleanup_old_backups()
|
| 104 |
+
|
| 105 |
+
return filename
|
| 106 |
+
|
| 107 |
+
except FileNotFoundError:
|
| 108 |
+
logger.error("pg_dump introuvable. Installez PostgreSQL client (libpq).")
|
| 109 |
+
return None
|
| 110 |
+
except subprocess.TimeoutExpired:
|
| 111 |
+
logger.error("Timeout : le backup a pris plus de 5 minutes")
|
| 112 |
+
return None
|
| 113 |
+
except Exception as e:
|
| 114 |
+
logger.error(f"Erreur lors du backup : {e}")
|
| 115 |
+
return None
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def _cleanup_old_backups():
|
| 119 |
+
"""Supprime les backups les plus anciens dans Supabase Storage, ne conserve que MAX_BACKUPS."""
|
| 120 |
+
try:
|
| 121 |
+
files = supabase_admin.storage.from_(BACKUP_BUCKET).list()
|
| 122 |
+
# Trier par nom (contient le timestamp) décroissant
|
| 123 |
+
backup_files = sorted(
|
| 124 |
+
[f for f in files if f["name"].startswith("dedalys_backup_")],
|
| 125 |
+
key=lambda f: f["name"],
|
| 126 |
+
reverse=True,
|
| 127 |
+
)
|
| 128 |
+
for old in backup_files[MAX_BACKUPS:]:
|
| 129 |
+
supabase_admin.storage.from_(BACKUP_BUCKET).remove([old["name"]])
|
| 130 |
+
logger.info(f"Ancien backup supprimé : {old['name']}")
|
| 131 |
+
except Exception as e:
|
| 132 |
+
logger.warning(f"Erreur lors du nettoyage des anciens backups : {e}")
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def list_backups() -> list[dict]:
|
| 136 |
+
"""Liste les backups disponibles dans Supabase Storage."""
|
| 137 |
+
try:
|
| 138 |
+
_ensure_bucket()
|
| 139 |
+
files = supabase_admin.storage.from_(BACKUP_BUCKET).list()
|
| 140 |
+
backup_files = sorted(
|
| 141 |
+
[f for f in files if f["name"].startswith("dedalys_backup_")],
|
| 142 |
+
key=lambda f: f["name"],
|
| 143 |
+
reverse=True,
|
| 144 |
+
)
|
| 145 |
+
return [
|
| 146 |
+
{
|
| 147 |
+
"filename": f["name"],
|
| 148 |
+
"size_mb": round((f.get("metadata", {}).get("size", 0) or 0) / (1024 * 1024), 2),
|
| 149 |
+
"created_at": f.get("created_at", ""),
|
| 150 |
+
}
|
| 151 |
+
for f in backup_files
|
| 152 |
+
]
|
| 153 |
+
except Exception as e:
|
| 154 |
+
logger.error(f"Erreur lors du listage des backups : {e}")
|
| 155 |
+
return []
|
app/core/config.py
CHANGED
|
@@ -19,6 +19,14 @@ class Settings(BaseSettings):
|
|
| 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
|
|
|
|
| 19 |
SUPABASE_SERVICE_KEY: str
|
| 20 |
SUPABASE_JWT_SECRET: str # MVP — conservé pour compatibilité, non utilisé directement
|
| 21 |
|
| 22 |
+
# ── Base de données (pour pg_dump) ──────────────────────
|
| 23 |
+
DB_HOST: str = ""
|
| 24 |
+
DB_NAME: str = "postgres"
|
| 25 |
+
DB_USER: str = "postgres"
|
| 26 |
+
DB_PASSWORD: str = ""
|
| 27 |
+
DB_PORT: int = 5432
|
| 28 |
+
BACKUP_DIR: str = "backups"
|
| 29 |
+
|
| 30 |
# ── Storage ──────────────────────────────────────────────
|
| 31 |
STORAGE_BUCKET: str = "dedalys-fichiers"
|
| 32 |
STORAGE_SIGNED_URL_EXPIRY: int = 900 # 15 minutes par défaut
|
app/core/email.py
CHANGED
|
@@ -137,3 +137,37 @@ async def send_flash_cr_email(
|
|
| 137 |
subject=subject,
|
| 138 |
html_body=html_body
|
| 139 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
subject=subject,
|
| 138 |
html_body=html_body
|
| 139 |
)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
async def send_subscription_reminder(
|
| 143 |
+
destinataires: List[str],
|
| 144 |
+
espace_nom: str,
|
| 145 |
+
date_expiration: str,
|
| 146 |
+
jours_restants: int,
|
| 147 |
+
) -> bool:
|
| 148 |
+
"""Envoie un email de rappel d'expiration d'abonnement."""
|
| 149 |
+
|
| 150 |
+
subject = f"[Dedalys] Votre abonnement expire dans {jours_restants} jour{'s' if jours_restants > 1 else ''} — {espace_nom}"
|
| 151 |
+
|
| 152 |
+
frontend_url = settings.FRONTEND_URL.rstrip('/')
|
| 153 |
+
|
| 154 |
+
html_body = f"""
|
| 155 |
+
<p>Bonjour,</p>
|
| 156 |
+
|
| 157 |
+
<p>L'abonnement de votre espace <strong>{espace_nom}</strong> sur Dedalys
|
| 158 |
+
expire le <strong>{date_expiration}</strong>, soit dans <strong>{jours_restants} jour{'s' if jours_restants > 1 else ''}</strong>.</p>
|
| 159 |
+
|
| 160 |
+
<p>Pour continuer à utiliser votre espace sans interruption, nous vous invitons
|
| 161 |
+
à renouveler votre abonnement dès que possible.</p>
|
| 162 |
+
|
| 163 |
+
<p><a href="{frontend_url}">Se connecter à Dedalys</a></p>
|
| 164 |
+
|
| 165 |
+
<br>
|
| 166 |
+
<p>Cordialement,<br>L'équipe Dedalys</p>
|
| 167 |
+
"""
|
| 168 |
+
|
| 169 |
+
return await send_email_async(
|
| 170 |
+
to=destinataires,
|
| 171 |
+
subject=subject,
|
| 172 |
+
html_body=html_body
|
| 173 |
+
)
|
app/core/scheduler.py
CHANGED
|
@@ -5,12 +5,14 @@ MVP: Envoi de rappels automatiques d'audiences (J-7, J-3, J-1).
|
|
| 5 |
"""
|
| 6 |
|
| 7 |
import logging
|
|
|
|
| 8 |
from datetime import datetime, date, timedelta, timezone
|
| 9 |
from apscheduler.schedulers.asyncio import AsyncIOScheduler
|
| 10 |
from apscheduler.triggers.cron import CronTrigger
|
| 11 |
|
| 12 |
from app.core.supabase import supabase_admin
|
| 13 |
-
from app.core.email import send_audience_reminder
|
|
|
|
| 14 |
|
| 15 |
logger = logging.getLogger(__name__)
|
| 16 |
|
|
@@ -94,15 +96,116 @@ async def check_and_send_audience_reminders():
|
|
| 94 |
except Exception as e:
|
| 95 |
logger.error(f"Erreur lors de l'exécution des rappels d'audience: {e}")
|
| 96 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
def start_scheduler():
|
| 98 |
"""Démarre le planificateur de tâches asynchrones."""
|
| 99 |
-
#
|
| 100 |
scheduler.add_job(
|
| 101 |
check_and_send_audience_reminders,
|
| 102 |
-
trigger=CronTrigger(minute=0),
|
| 103 |
id="audience_reminders_job",
|
| 104 |
replace_existing=True
|
| 105 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
scheduler.start()
|
| 107 |
logger.info("Scheduler démarré : tâches planifiées activées.")
|
| 108 |
|
|
|
|
| 5 |
"""
|
| 6 |
|
| 7 |
import logging
|
| 8 |
+
import asyncio
|
| 9 |
from datetime import datetime, date, timedelta, timezone
|
| 10 |
from apscheduler.schedulers.asyncio import AsyncIOScheduler
|
| 11 |
from apscheduler.triggers.cron import CronTrigger
|
| 12 |
|
| 13 |
from app.core.supabase import supabase_admin
|
| 14 |
+
from app.core.email import send_audience_reminder, send_subscription_reminder
|
| 15 |
+
from app.core.backup import run_backup
|
| 16 |
|
| 17 |
logger = logging.getLogger(__name__)
|
| 18 |
|
|
|
|
| 96 |
except Exception as e:
|
| 97 |
logger.error(f"Erreur lors de l'exécution des rappels d'audience: {e}")
|
| 98 |
|
| 99 |
+
|
| 100 |
+
async def check_and_send_subscription_reminders():
|
| 101 |
+
"""
|
| 102 |
+
Vérifie les espaces dont l'abonnement expire bientôt (J-30, J-7)
|
| 103 |
+
et envoie des emails de rappel aux administrateurs.
|
| 104 |
+
"""
|
| 105 |
+
aujourd_hui = date.today()
|
| 106 |
+
logger.info("Vérification des abonnements expirant bientôt")
|
| 107 |
+
|
| 108 |
+
try:
|
| 109 |
+
# Récupérer les espaces actifs avec une date d'expiration définie
|
| 110 |
+
response = (
|
| 111 |
+
supabase_admin.table("espaces")
|
| 112 |
+
.select("*")
|
| 113 |
+
.eq("is_archived", False)
|
| 114 |
+
.not_.is_("date_expiration_abonnement", "null")
|
| 115 |
+
.gte("date_expiration_abonnement", str(aujourd_hui))
|
| 116 |
+
.execute()
|
| 117 |
+
)
|
| 118 |
+
espaces = response.data or []
|
| 119 |
+
|
| 120 |
+
for espace in espaces:
|
| 121 |
+
exp_str = espace.get("date_expiration_abonnement")
|
| 122 |
+
if not exp_str:
|
| 123 |
+
continue
|
| 124 |
+
|
| 125 |
+
exp_date = datetime.strptime(exp_str, "%Y-%m-%d").date()
|
| 126 |
+
jours_restants = (exp_date - aujourd_hui).days
|
| 127 |
+
|
| 128 |
+
update_flags = {}
|
| 129 |
+
should_send = False
|
| 130 |
+
|
| 131 |
+
if jours_restants <= 30 and not espace.get("rappel_abonnement_j30_envoye"):
|
| 132 |
+
update_flags["rappel_abonnement_j30_envoye"] = True
|
| 133 |
+
should_send = True
|
| 134 |
+
elif jours_restants <= 7 and not espace.get("rappel_abonnement_j7_envoye"):
|
| 135 |
+
update_flags["rappel_abonnement_j7_envoye"] = True
|
| 136 |
+
should_send = True
|
| 137 |
+
|
| 138 |
+
if not should_send:
|
| 139 |
+
continue
|
| 140 |
+
|
| 141 |
+
# Récupérer les administrateurs de l'espace (associé gérant + office manager)
|
| 142 |
+
admins_resp = (
|
| 143 |
+
supabase_admin.table("utilisateurs")
|
| 144 |
+
.select("email")
|
| 145 |
+
.eq("espace_id", espace["id"])
|
| 146 |
+
.in_("role_cabinet", ["associe_gerant", "office_manager"])
|
| 147 |
+
.execute()
|
| 148 |
+
)
|
| 149 |
+
admin_emails = [u["email"] for u in (admins_resp.data or []) if u.get("email")]
|
| 150 |
+
|
| 151 |
+
if not admin_emails:
|
| 152 |
+
continue
|
| 153 |
+
|
| 154 |
+
logger.info(f"Envoi rappel abonnement J-{jours_restants} pour espace {espace['nom']}")
|
| 155 |
+
success = await send_subscription_reminder(
|
| 156 |
+
destinataires=admin_emails,
|
| 157 |
+
espace_nom=espace["nom"],
|
| 158 |
+
date_expiration=exp_str,
|
| 159 |
+
jours_restants=jours_restants,
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
if success:
|
| 163 |
+
(
|
| 164 |
+
supabase_admin.table("espaces")
|
| 165 |
+
.update(update_flags)
|
| 166 |
+
.eq("id", espace["id"])
|
| 167 |
+
.execute()
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
logger.info("Fin de la vérification des abonnements")
|
| 171 |
+
|
| 172 |
+
except Exception as e:
|
| 173 |
+
logger.error(f"Erreur lors de la vérification des abonnements: {e}")
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
async def async_run_backup():
|
| 177 |
+
"""Wrapper async pour exécuter pg_dump sans bloquer l'event loop."""
|
| 178 |
+
loop = asyncio.get_event_loop()
|
| 179 |
+
result = await loop.run_in_executor(None, run_backup)
|
| 180 |
+
if result:
|
| 181 |
+
logger.info(f"Backup automatique terminé : {result}")
|
| 182 |
+
else:
|
| 183 |
+
logger.error("Backup automatique échoué")
|
| 184 |
+
|
| 185 |
+
|
| 186 |
def start_scheduler():
|
| 187 |
"""Démarre le planificateur de tâches asynchrones."""
|
| 188 |
+
# Rappels d'audiences — toutes les heures
|
| 189 |
scheduler.add_job(
|
| 190 |
check_and_send_audience_reminders,
|
| 191 |
+
trigger=CronTrigger(minute=0),
|
| 192 |
id="audience_reminders_job",
|
| 193 |
replace_existing=True
|
| 194 |
)
|
| 195 |
+
# Rappels d'abonnements — tous les jours à 8h UTC
|
| 196 |
+
scheduler.add_job(
|
| 197 |
+
check_and_send_subscription_reminders,
|
| 198 |
+
trigger=CronTrigger(hour=8, minute=0),
|
| 199 |
+
id="subscription_reminders_job",
|
| 200 |
+
replace_existing=True
|
| 201 |
+
)
|
| 202 |
+
# Backup quotidien — tous les jours à 2h UTC
|
| 203 |
+
scheduler.add_job(
|
| 204 |
+
async_run_backup,
|
| 205 |
+
trigger=CronTrigger(hour=2, minute=0),
|
| 206 |
+
id="daily_backup_job",
|
| 207 |
+
replace_existing=True
|
| 208 |
+
)
|
| 209 |
scheduler.start()
|
| 210 |
logger.info("Scheduler démarré : tâches planifiées activées.")
|
| 211 |
|
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
|
@@ -114,17 +114,25 @@ class UtilisateurResponse(UtilisateurBase):
|
|
| 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
|
|
@@ -150,10 +158,12 @@ class ClientBase(BaseModel):
|
|
| 150 |
statut: str = Field(..., pattern="^(PP|PM)$",
|
| 151 |
description="PP = Personne Physique, PM = Personne Morale")
|
| 152 |
forme_juridique: Optional[str] = Field(
|
| 153 |
-
None,
|
|
|
|
|
|
|
|
|
|
| 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):
|
|
@@ -167,15 +177,18 @@ class ClientUpdate(BaseModel):
|
|
| 167 |
email_principal: Optional[EmailStr] = None
|
| 168 |
telephone: Optional[str] = Field(None, min_length=8, max_length=20)
|
| 169 |
statut: Optional[str] = Field(None, pattern="^(PP|PM)$")
|
| 170 |
-
forme_juridique: Optional[str] =
|
|
|
|
|
|
|
|
|
|
| 171 |
representant_legal: Optional[str] = None
|
| 172 |
-
revenu_attendu_total: Optional[float] = Field(None, ge=0)
|
| 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
|
|
@@ -374,7 +387,7 @@ class FlashCRBase(BaseModel):
|
|
| 374 |
None,
|
| 375 |
description="Obligatoire si mise_en_delibere ou renvoi"
|
| 376 |
)
|
| 377 |
-
notes_rapides: str = Field(
|
| 378 |
envoyer_email: bool = Field(
|
| 379 |
default=True, description="Envoyer email auto au client")
|
| 380 |
|
|
@@ -514,8 +527,8 @@ 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] = []
|
|
|
|
| 114 |
class EspaceCreate(BaseModel):
|
| 115 |
"""Création d'un espace (superadmin only)."""
|
| 116 |
nom: str = Field(..., min_length=1, max_length=255)
|
| 117 |
+
type_abonnement: Optional[str] = Field(None, max_length=50)
|
| 118 |
+
date_expiration_abonnement: Optional[date] = None
|
| 119 |
|
| 120 |
|
| 121 |
class EspaceUpdate(BaseModel):
|
| 122 |
"""Mise à jour d'un espace."""
|
| 123 |
nom: Optional[str] = Field(None, min_length=1, max_length=255)
|
| 124 |
+
type_abonnement: Optional[str] = Field(None, max_length=50)
|
| 125 |
+
date_expiration_abonnement: Optional[date] = None
|
| 126 |
|
| 127 |
|
| 128 |
class EspaceResponse(BaseModel):
|
| 129 |
"""Réponse espace."""
|
| 130 |
id: UUID
|
| 131 |
nom: str
|
| 132 |
+
type_abonnement: Optional[str] = None
|
| 133 |
+
date_expiration_abonnement: Optional[date] = None
|
| 134 |
+
rappel_abonnement_j30_envoye: bool = False
|
| 135 |
+
rappel_abonnement_j7_envoye: bool = False
|
| 136 |
is_archived: bool = False
|
| 137 |
archived_at: Optional[datetime] = None
|
| 138 |
created_at: datetime
|
|
|
|
| 158 |
statut: str = Field(..., pattern="^(PP|PM)$",
|
| 159 |
description="PP = Personne Physique, PM = Personne Morale")
|
| 160 |
forme_juridique: Optional[str] = Field(
|
| 161 |
+
None,
|
| 162 |
+
pattern="^(sarl|sa|sas|snc|scs|succursale|bureau_de_liaison|gie|cooperative|ong|association|fondation|entite_publique)$",
|
| 163 |
+
description="Obligatoire si PM",
|
| 164 |
+
)
|
| 165 |
representant_legal: Optional[str] = Field(
|
| 166 |
None, max_length=255, description="Obligatoire si PM")
|
|
|
|
| 167 |
|
| 168 |
|
| 169 |
class ClientCreate(ClientBase):
|
|
|
|
| 177 |
email_principal: Optional[EmailStr] = None
|
| 178 |
telephone: Optional[str] = Field(None, min_length=8, max_length=20)
|
| 179 |
statut: Optional[str] = Field(None, pattern="^(PP|PM)$")
|
| 180 |
+
forme_juridique: Optional[str] = Field(
|
| 181 |
+
None,
|
| 182 |
+
pattern="^(SARL|SA|SAS|SNC|SCS|Succursale|Bureau de liaison|GIE|Coopérative|ONG|Association|Fondation|Entité publique)$",
|
| 183 |
+
)
|
| 184 |
representant_legal: Optional[str] = None
|
|
|
|
| 185 |
|
| 186 |
|
| 187 |
class ClientResponse(ClientBase):
|
| 188 |
"""Réponse client."""
|
| 189 |
id: UUID
|
| 190 |
espace_id: UUID
|
| 191 |
+
revenu_attendu_total: float = Field(default=0, description="Somme des revenu_attendu de tous les dossiers du client")
|
| 192 |
is_archived: bool = False
|
| 193 |
archived_at: Optional[datetime] = None
|
| 194 |
created_at: datetime
|
|
|
|
| 387 |
None,
|
| 388 |
description="Obligatoire si mise_en_delibere ou renvoi"
|
| 389 |
)
|
| 390 |
+
notes_rapides: Optional[str] = Field(None, max_length=500)
|
| 391 |
envoyer_email: bool = Field(
|
| 392 |
default=True, description="Envoyer email auto au client")
|
| 393 |
|
|
|
|
| 527 |
"""Récapitulatif financier d'un dossier."""
|
| 528 |
dossier_id: UUID
|
| 529 |
reference: str
|
| 530 |
+
titre: Optional[str] = None
|
| 531 |
+
revenu_attendu: float = 0
|
| 532 |
+
total_percu: float = 0
|
| 533 |
+
reste_a_percevoir: float = 0
|
| 534 |
paiements: List[dict] = []
|
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/clients.py
CHANGED
|
@@ -20,7 +20,6 @@ from app.core.supabase import supabase_admin
|
|
| 20 |
|
| 21 |
router = APIRouter(prefix="/clients", tags=["Clients"])
|
| 22 |
|
| 23 |
-
|
| 24 |
# ══════════════════════════════════════════════════════════════════════════════
|
| 25 |
# CRUD CLIENTS
|
| 26 |
# ══════════════════════════════════════════════════════════════════════════════
|
|
|
|
| 20 |
|
| 21 |
router = APIRouter(prefix="/clients", tags=["Clients"])
|
| 22 |
|
|
|
|
| 23 |
# ══════════════════════════════════════════════════════════════════════════════
|
| 24 |
# CRUD CLIENTS
|
| 25 |
# ══════════════════════════════════════════════════════════════════════════════
|
app/routers/dossiers.py
CHANGED
|
@@ -90,6 +90,7 @@ async def create_dossier(
|
|
| 90 |
if not response.data:
|
| 91 |
raise HTTPException(
|
| 92 |
status_code=500, detail="Échec de la création du dossier")
|
|
|
|
| 93 |
return response.data[0]
|
| 94 |
|
| 95 |
|
|
@@ -202,6 +203,7 @@ async def update_dossier(
|
|
| 202 |
)
|
| 203 |
if not response.data:
|
| 204 |
raise HTTPException(status_code=404, detail="Dossier introuvable")
|
|
|
|
| 205 |
return response.data[0]
|
| 206 |
|
| 207 |
|
|
@@ -224,6 +226,7 @@ async def archive_dossier(
|
|
| 224 |
)
|
| 225 |
if not response.data:
|
| 226 |
raise HTTPException(status_code=404, detail="Dossier introuvable")
|
|
|
|
| 227 |
return {"message": "Dossier archivé"}
|
| 228 |
|
| 229 |
|
|
|
|
| 90 |
if not response.data:
|
| 91 |
raise HTTPException(
|
| 92 |
status_code=500, detail="Échec de la création du dossier")
|
| 93 |
+
|
| 94 |
return response.data[0]
|
| 95 |
|
| 96 |
|
|
|
|
| 203 |
)
|
| 204 |
if not response.data:
|
| 205 |
raise HTTPException(status_code=404, detail="Dossier introuvable")
|
| 206 |
+
|
| 207 |
return response.data[0]
|
| 208 |
|
| 209 |
|
|
|
|
| 226 |
)
|
| 227 |
if not response.data:
|
| 228 |
raise HTTPException(status_code=404, detail="Dossier introuvable")
|
| 229 |
+
|
| 230 |
return {"message": "Dossier archivé"}
|
| 231 |
|
| 232 |
|
app/routers/espaces.py
CHANGED
|
@@ -15,6 +15,7 @@ from app.models.schemas import (
|
|
| 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 |
|
|
@@ -154,12 +155,19 @@ async def add_utilisateurs(
|
|
| 154 |
created_auth_ids = [] # pour rollback global si besoin
|
| 155 |
|
| 156 |
for user_data in payload:
|
|
|
|
|
|
|
|
|
|
| 157 |
# Créer l'utilisateur dans Supabase Auth
|
| 158 |
try:
|
| 159 |
auth_response = supabase_admin.auth.admin.create_user({
|
| 160 |
"email": user_data.email,
|
| 161 |
"password": user_data.password,
|
| 162 |
"email_confirm": True,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
})
|
| 164 |
except Exception as e:
|
| 165 |
# Rollback tous les utilisateurs déjà créés
|
|
@@ -184,19 +192,22 @@ async def add_utilisateurs(
|
|
| 184 |
|
| 185 |
created_auth_ids.append(auth_response.user.id)
|
| 186 |
|
| 187 |
-
# Créer le profil
|
| 188 |
profile_data = {
|
| 189 |
"id": auth_response.user.id,
|
| 190 |
"email": user_data.email,
|
| 191 |
-
"nom":
|
| 192 |
-
"prenom":
|
| 193 |
"role_cabinet": user_data.role_cabinet.value,
|
| 194 |
"espace_id": str(espace_id),
|
| 195 |
"is_superadmin": False,
|
| 196 |
}
|
| 197 |
|
| 198 |
-
profile_resp =
|
| 199 |
-
"utilisateurs")
|
|
|
|
|
|
|
|
|
|
| 200 |
if not profile_resp.data:
|
| 201 |
for auth_id in created_auth_ids:
|
| 202 |
try:
|
|
@@ -245,3 +256,32 @@ async def remove_utilisateur(
|
|
| 245 |
pass # L'utilisateur Auth peut déjà avoir été supprimé
|
| 246 |
|
| 247 |
return {"message": "Utilisateur supprimé"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
)
|
| 16 |
from app.core.auth import require_superadmin, CurrentUser
|
| 17 |
from app.core.supabase import supabase_admin
|
| 18 |
+
from app.core.backup import run_backup, list_backups
|
| 19 |
|
| 20 |
router = APIRouter(prefix="/espaces", tags=["Espaces (Superadmin)"])
|
| 21 |
|
|
|
|
| 155 |
created_auth_ids = [] # pour rollback global si besoin
|
| 156 |
|
| 157 |
for user_data in payload:
|
| 158 |
+
nom = user_data.nom.strip()
|
| 159 |
+
prenom = user_data.prenom.strip()
|
| 160 |
+
|
| 161 |
# Créer l'utilisateur dans Supabase Auth
|
| 162 |
try:
|
| 163 |
auth_response = supabase_admin.auth.admin.create_user({
|
| 164 |
"email": user_data.email,
|
| 165 |
"password": user_data.password,
|
| 166 |
"email_confirm": True,
|
| 167 |
+
"user_metadata": {
|
| 168 |
+
"nom": nom,
|
| 169 |
+
"prenom": prenom,
|
| 170 |
+
},
|
| 171 |
})
|
| 172 |
except Exception as e:
|
| 173 |
# Rollback tous les utilisateurs déjà créés
|
|
|
|
| 192 |
|
| 193 |
created_auth_ids.append(auth_response.user.id)
|
| 194 |
|
| 195 |
+
# Créer le profil (upsert pour gérer un éventuel trigger Supabase)
|
| 196 |
profile_data = {
|
| 197 |
"id": auth_response.user.id,
|
| 198 |
"email": user_data.email,
|
| 199 |
+
"nom": nom,
|
| 200 |
+
"prenom": prenom,
|
| 201 |
"role_cabinet": user_data.role_cabinet.value,
|
| 202 |
"espace_id": str(espace_id),
|
| 203 |
"is_superadmin": False,
|
| 204 |
}
|
| 205 |
|
| 206 |
+
profile_resp = (
|
| 207 |
+
supabase_admin.table("utilisateurs")
|
| 208 |
+
.upsert(profile_data, on_conflict="id")
|
| 209 |
+
.execute()
|
| 210 |
+
)
|
| 211 |
if not profile_resp.data:
|
| 212 |
for auth_id in created_auth_ids:
|
| 213 |
try:
|
|
|
|
| 256 |
pass # L'utilisateur Auth peut déjà avoir été supprimé
|
| 257 |
|
| 258 |
return {"message": "Utilisateur supprimé"}
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 262 |
+
# BACKUPS
|
| 263 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 264 |
+
|
| 265 |
+
@router.post("/backups", status_code=201)
|
| 266 |
+
async def trigger_backup(
|
| 267 |
+
_: CurrentUser = Depends(require_superadmin),
|
| 268 |
+
):
|
| 269 |
+
"""Déclenche un backup manuel de la base de données. Superadmin only."""
|
| 270 |
+
import asyncio
|
| 271 |
+
loop = asyncio.get_event_loop()
|
| 272 |
+
filepath = await loop.run_in_executor(None, run_backup)
|
| 273 |
+
if not filepath:
|
| 274 |
+
raise HTTPException(
|
| 275 |
+
status_code=500,
|
| 276 |
+
detail="Échec du backup. Vérifiez les logs et la config DB.",
|
| 277 |
+
)
|
| 278 |
+
return {"message": "Backup créé avec succès", "filepath": filepath}
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
@router.get("/backups")
|
| 282 |
+
async def get_backups(
|
| 283 |
+
_: CurrentUser = Depends(require_superadmin),
|
| 284 |
+
):
|
| 285 |
+
"""Liste les backups disponibles. Superadmin only."""
|
| 286 |
+
return {"backups": list_backups()}
|
| 287 |
+
|
pyproject.toml
CHANGED
|
@@ -17,6 +17,7 @@ dependencies = [
|
|
| 17 |
"python-dotenv==1.0.1",
|
| 18 |
"python-multipart==0.0.9",
|
| 19 |
"resend>=2.23.0",
|
|
|
|
| 20 |
"supabase==2.3.4",
|
| 21 |
"uvicorn[standard]==0.27.1",
|
| 22 |
]
|
|
|
|
| 17 |
"python-dotenv==1.0.1",
|
| 18 |
"python-multipart==0.0.9",
|
| 19 |
"resend>=2.23.0",
|
| 20 |
+
"gotrue>=2.8,<2.9",
|
| 21 |
"supabase==2.3.4",
|
| 22 |
"uvicorn[standard]==0.27.1",
|
| 23 |
]
|
supabase/migrations/20260302095013_initial_schema.sql
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
-- ══════════════════════════════════════════════════════════════════════════════
|
| 2 |
-- DEDALYS — Schéma de base de données
|
| 3 |
-- PostgreSQL 15+ via Supabase
|
| 4 |
-
-- Version: 1.
|
| 5 |
-- ══════════════════════════════════════════════════════════════════════════════
|
| 6 |
|
| 7 |
-- ══════════════════════════════════════════════════════════════════════════════
|
|
@@ -20,6 +20,10 @@ CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
|
|
| 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()
|
|
@@ -31,8 +35,8 @@ CREATE TABLE IF NOT EXISTS espaces (
|
|
| 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,
|
|
@@ -52,9 +56,17 @@ CREATE TABLE IF NOT EXISTS clients (
|
|
| 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()
|
|
@@ -64,6 +76,11 @@ 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 |
|
|
@@ -83,6 +100,11 @@ CREATE TABLE IF NOT EXISTS points_de_contact (
|
|
| 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 |
|
|
@@ -234,6 +256,61 @@ CREATE INDEX IF NOT EXISTS idx_audit_timestamp ON audit_logs(espace_id, timestam
|
|
| 234 |
CREATE INDEX IF NOT EXISTS idx_audit_ressource_id ON audit_logs(ressource_id);
|
| 235 |
|
| 236 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
-- ══════════════════════════════════════════════════════════════════════════════
|
| 238 |
-- ROW LEVEL SECURITY (RLS)
|
| 239 |
-- ══════════════════════════════════════════════════════════════════════════════
|
|
|
|
| 1 |
-- ══════════════════════════════════════════════════════════════════════════════
|
| 2 |
-- DEDALYS — Schéma de base de données
|
| 3 |
-- PostgreSQL 15+ via Supabase
|
| 4 |
+
-- Version: 1.1.0
|
| 5 |
-- ══════════════════════════════════════════════════════════════════════════════
|
| 6 |
|
| 7 |
-- ══════════════════════════════════════════════════════════════════════════════
|
|
|
|
| 20 |
CREATE TABLE IF NOT EXISTS espaces (
|
| 21 |
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
| 22 |
nom VARCHAR(255) NOT NULL,
|
| 23 |
+
type_abonnement VARCHAR(50) DEFAULT NULL, -- Type d'abonnement (à définir)
|
| 24 |
+
date_expiration_abonnement DATE DEFAULT NULL,
|
| 25 |
+
rappel_abonnement_j30_envoye BOOLEAN DEFAULT FALSE,
|
| 26 |
+
rappel_abonnement_j7_envoye BOOLEAN DEFAULT FALSE,
|
| 27 |
is_archived BOOLEAN DEFAULT FALSE,
|
| 28 |
archived_at TIMESTAMPTZ,
|
| 29 |
created_at TIMESTAMPTZ DEFAULT NOW()
|
|
|
|
| 35 |
CREATE TABLE IF NOT EXISTS utilisateurs (
|
| 36 |
id UUID PRIMARY KEY, -- Lié à auth.users
|
| 37 |
email VARCHAR(255) NOT NULL UNIQUE,
|
| 38 |
+
nom VARCHAR(100) NOT NULL CHECK (TRIM(nom) <> ''),
|
| 39 |
+
prenom VARCHAR(100) NOT NULL CHECK (TRIM(prenom) <> ''),
|
| 40 |
role_cabinet VARCHAR(50) NOT NULL CHECK (role_cabinet IN ('associe_gerant', 'avocat', 'juriste', 'office_manager')),
|
| 41 |
espace_id UUID REFERENCES espaces(id) ON DELETE CASCADE,
|
| 42 |
is_superadmin BOOLEAN DEFAULT FALSE,
|
|
|
|
| 56 |
email_principal VARCHAR(255) NOT NULL,
|
| 57 |
telephone VARCHAR(20) NOT NULL,
|
| 58 |
statut VARCHAR(2) NOT NULL CHECK (statut IN ('PP', 'PM')),
|
| 59 |
+
forme_juridique VARCHAR(100) CHECK (
|
| 60 |
+
forme_juridique IS NULL
|
| 61 |
+
OR forme_juridique IN (
|
| 62 |
+
'sarl', 'sa', 'sas', 'snc', 'scs',
|
| 63 |
+
'succursale', 'bureau_de_liaison', 'gie',
|
| 64 |
+
'cooperative', 'ong', 'association',
|
| 65 |
+
'fondation', 'entite_publique'
|
| 66 |
+
)
|
| 67 |
+
),
|
| 68 |
representant_legal VARCHAR(255),
|
| 69 |
+
revenu_attendu_total DECIMAL(15, 2) DEFAULT 0,
|
| 70 |
is_archived BOOLEAN DEFAULT FALSE,
|
| 71 |
archived_at TIMESTAMPTZ,
|
| 72 |
created_at TIMESTAMPTZ DEFAULT NOW()
|
|
|
|
| 76 |
CREATE INDEX IF NOT EXISTS idx_clients_archived ON clients(espace_id, is_archived);
|
| 77 |
CREATE INDEX IF NOT EXISTS idx_clients_search ON clients(espace_id, raison_sociale, email_principal);
|
| 78 |
|
| 79 |
+
-- Email unique par espace (hors archivés)
|
| 80 |
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_clients_email_unique_per_espace
|
| 81 |
+
ON clients (espace_id, email_principal)
|
| 82 |
+
WHERE is_archived = FALSE;
|
| 83 |
+
|
| 84 |
|
| 85 |
-- ── Points de Contact ───────────────────────────────────────────────────────
|
| 86 |
|
|
|
|
| 100 |
CREATE INDEX IF NOT EXISTS idx_contacts_client ON points_de_contact(client_id);
|
| 101 |
CREATE INDEX IF NOT EXISTS idx_contacts_espace ON points_de_contact(espace_id);
|
| 102 |
|
| 103 |
+
-- Email unique par client (hors archivés)
|
| 104 |
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_contacts_email_unique_per_client
|
| 105 |
+
ON points_de_contact (client_id, email)
|
| 106 |
+
WHERE is_archived = FALSE;
|
| 107 |
+
|
| 108 |
|
| 109 |
-- ── Dossiers ────────────────────────────────────────────────────────────────
|
| 110 |
|
|
|
|
| 256 |
CREATE INDEX IF NOT EXISTS idx_audit_ressource_id ON audit_logs(ressource_id);
|
| 257 |
|
| 258 |
|
| 259 |
+
-- ══════════════════════════════════════════════════════════════════════════════
|
| 260 |
+
-- TRIGGERS
|
| 261 |
+
-- ══════════════════════════════════════════════════════════════════════════════
|
| 262 |
+
|
| 263 |
+
-- ── Recalcul automatique de clients.revenu_attendu_total ────────────────────
|
| 264 |
+
|
| 265 |
+
CREATE OR REPLACE FUNCTION recalc_revenu_attendu_total()
|
| 266 |
+
RETURNS TRIGGER AS $$
|
| 267 |
+
DECLARE
|
| 268 |
+
target_client_id UUID;
|
| 269 |
+
BEGIN
|
| 270 |
+
-- Déterminer le client concerné
|
| 271 |
+
IF TG_OP = 'DELETE' THEN
|
| 272 |
+
target_client_id := OLD.client_id;
|
| 273 |
+
ELSE
|
| 274 |
+
target_client_id := NEW.client_id;
|
| 275 |
+
END IF;
|
| 276 |
+
|
| 277 |
+
-- Recalculer la somme des revenu_attendu des dossiers non archivés
|
| 278 |
+
UPDATE clients
|
| 279 |
+
SET revenu_attendu_total = COALESCE((
|
| 280 |
+
SELECT SUM(COALESCE(revenu_attendu, 0))
|
| 281 |
+
FROM dossiers
|
| 282 |
+
WHERE client_id = target_client_id
|
| 283 |
+
AND is_archived = FALSE
|
| 284 |
+
), 0)
|
| 285 |
+
WHERE id = target_client_id;
|
| 286 |
+
|
| 287 |
+
-- Si UPDATE a changé le client_id, recalculer aussi l'ancien client
|
| 288 |
+
IF TG_OP = 'UPDATE' AND OLD.client_id IS DISTINCT FROM NEW.client_id THEN
|
| 289 |
+
UPDATE clients
|
| 290 |
+
SET revenu_attendu_total = COALESCE((
|
| 291 |
+
SELECT SUM(COALESCE(revenu_attendu, 0))
|
| 292 |
+
FROM dossiers
|
| 293 |
+
WHERE client_id = OLD.client_id
|
| 294 |
+
AND is_archived = FALSE
|
| 295 |
+
), 0)
|
| 296 |
+
WHERE id = OLD.client_id;
|
| 297 |
+
END IF;
|
| 298 |
+
|
| 299 |
+
RETURN COALESCE(NEW, OLD);
|
| 300 |
+
END;
|
| 301 |
+
$$ LANGUAGE plpgsql SECURITY DEFINER;
|
| 302 |
+
|
| 303 |
+
CREATE TRIGGER trg_recalc_revenu_attendu_total
|
| 304 |
+
AFTER INSERT OR DELETE ON dossiers
|
| 305 |
+
FOR EACH ROW
|
| 306 |
+
EXECUTE FUNCTION recalc_revenu_attendu_total();
|
| 307 |
+
|
| 308 |
+
CREATE TRIGGER trg_recalc_revenu_attendu_total_update
|
| 309 |
+
AFTER UPDATE OF revenu_attendu, is_archived, client_id ON dossiers
|
| 310 |
+
FOR EACH ROW
|
| 311 |
+
EXECUTE FUNCTION recalc_revenu_attendu_total();
|
| 312 |
+
|
| 313 |
+
|
| 314 |
-- ══════════════════════════════════════════════════════════════════════════════
|
| 315 |
-- ROW LEVEL SECURITY (RLS)
|
| 316 |
-- ══════════════════════════════════════════════════════════════════════════════
|
uv.lock
CHANGED
|
@@ -114,6 +114,7 @@ dependencies = [
|
|
| 114 |
{ name = "apscheduler" },
|
| 115 |
{ name = "email-validator" },
|
| 116 |
{ name = "fastapi" },
|
|
|
|
| 117 |
{ name = "pydantic" },
|
| 118 |
{ name = "pydantic-core" },
|
| 119 |
{ name = "pydantic-settings" },
|
|
@@ -132,6 +133,7 @@ requires-dist = [
|
|
| 132 |
{ name = "apscheduler", specifier = ">=3.11.2" },
|
| 133 |
{ name = "email-validator", specifier = "==2.1.0" },
|
| 134 |
{ name = "fastapi", specifier = "==0.109.2" },
|
|
|
|
| 135 |
{ name = "pydantic", specifier = ">=2.8" },
|
| 136 |
{ name = "pydantic-core", specifier = ">=2.20.0" },
|
| 137 |
{ name = "pydantic-settings", specifier = "==2.1.0" },
|
|
@@ -195,15 +197,15 @@ wheels = [
|
|
| 195 |
|
| 196 |
[[package]]
|
| 197 |
name = "gotrue"
|
| 198 |
-
version = "2.
|
| 199 |
source = { registry = "https://pypi.org/simple" }
|
| 200 |
dependencies = [
|
| 201 |
{ name = "httpx", extra = ["http2"] },
|
| 202 |
{ name = "pydantic" },
|
| 203 |
]
|
| 204 |
-
sdist = { url = "https://files.pythonhosted.org/packages/
|
| 205 |
wheels = [
|
| 206 |
-
{ url = "https://files.pythonhosted.org/packages/
|
| 207 |
]
|
| 208 |
|
| 209 |
[[package]]
|
|
|
|
| 114 |
{ name = "apscheduler" },
|
| 115 |
{ name = "email-validator" },
|
| 116 |
{ name = "fastapi" },
|
| 117 |
+
{ name = "gotrue" },
|
| 118 |
{ name = "pydantic" },
|
| 119 |
{ name = "pydantic-core" },
|
| 120 |
{ name = "pydantic-settings" },
|
|
|
|
| 133 |
{ name = "apscheduler", specifier = ">=3.11.2" },
|
| 134 |
{ name = "email-validator", specifier = "==2.1.0" },
|
| 135 |
{ name = "fastapi", specifier = "==0.109.2" },
|
| 136 |
+
{ name = "gotrue", specifier = ">=2.8,<2.9" },
|
| 137 |
{ name = "pydantic", specifier = ">=2.8" },
|
| 138 |
{ name = "pydantic-core", specifier = ">=2.20.0" },
|
| 139 |
{ name = "pydantic-settings", specifier = "==2.1.0" },
|
|
|
|
| 197 |
|
| 198 |
[[package]]
|
| 199 |
name = "gotrue"
|
| 200 |
+
version = "2.8.1"
|
| 201 |
source = { registry = "https://pypi.org/simple" }
|
| 202 |
dependencies = [
|
| 203 |
{ name = "httpx", extra = ["http2"] },
|
| 204 |
{ name = "pydantic" },
|
| 205 |
]
|
| 206 |
+
sdist = { url = "https://files.pythonhosted.org/packages/e6/7f/407a0de3c4f57e2be6620be53c2398b550644763b4bddd19d19b29e8be1d/gotrue-2.8.1.tar.gz", hash = "sha256:644d0096c4c390f7e36d9cb05271a7091c01e7dc6d506eb117b8fe8fc48eb8d9", size = 41223, upload-time = "2024-09-08T20:17:11.935Z" }
|
| 207 |
wheels = [
|
| 208 |
+
{ url = "https://files.pythonhosted.org/packages/18/ee/4aad2b25941393e956ccda6aea8b2e144dbd780adb893e7f5b7147f0527e/gotrue-2.8.1-py3-none-any.whl", hash = "sha256:97dff077d71cca629f046c35ba34fae132b69c55fe271651766ddcf6d8132468", size = 48388, upload-time = "2024-09-08T20:17:10.378Z" },
|
| 209 |
]
|
| 210 |
|
| 211 |
[[package]]
|