# Fablabs Manager — 04. Modèle de données (conceptuel et logique)

| Élément | Valeur |
|---|---|
| Version | 1.0 (phase de conception) |
| Date | 2026-11-15 |
| Statut | Soumis à validation |
| Moteurs cibles | PostgreSQL 16 (central), SQLite 3.45+ (agence/cPanel) |

---

## 1. Conventions

| Convention | Règle |
|---|---|
| Clé primaire | `id UUID` généré côté application (UUIDv7, ordonné dans le temps) |
| Nommage | Tables `app_modele` (défaut Django), colonnes `snake_case`, modèles `PascalCase` |
| Horodatage | `created_at`, `updated_at` en UTC (`DateTimeField`, `USE_TZ=True`) |
| Suppression | Logique : `deleted_at`, `deleted_by` ; aucune suppression physique de données métier |
| Montants | `BigIntegerField` en XAF entiers, toujours positifs ; le sens est porté par le type d'opération |
| Énumérations | `CharField` + `TextChoices` + contrainte `CHECK` (portable) plutôt que `ENUM` PostgreSQL |
| JSON | `JSONField` (PostgreSQL `jsonb`, SQLite `json`) réservé aux payloads et paramètres, jamais aux données requêtables critiques |
| Contraintes | `UniqueConstraint`, `CheckConstraint` déclarées dans `Meta.constraints` (portables) |
| Index | Nommés explicitement (`idx_<table>_<colonnes>`), incluant `deleted_at` quand pertinent |
| Traçabilité | `created_by`, `updated_by` (`SET_NULL`), `origin_node` (UUID du nœud émetteur, sans FK), `version` |
| Codes lisibles | Séquence par agence et par type, table `core_sequence`, jamais réutilisée |

### 1.1 Mixins et champs communs

```python
# apps/core/models.py (conception)
class UUIDModel(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid7, editable=False)

class TimeStampedModel(models.Model):
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)
    updated_at = models.DateTimeField(auto_now=True)

class ActorTrackedModel(models.Model):
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True,
                                   on_delete=models.SET_NULL, related_name="+")
    updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True,
                                   on_delete=models.SET_NULL, related_name="+")

class SoftDeleteModel(models.Model):
    deleted_at = models.DateTimeField(null=True, blank=True, db_index=True)
    deleted_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True,
                                   on_delete=models.SET_NULL, related_name="+")
    deletion_reason = models.TextField(blank=True)

class SyncableModel(models.Model):
    origin_node = models.UUIDField(null=True, blank=True, db_index=True)   # pas de FK : découplage
    version = models.PositiveIntegerField(default=1)
    sync_state = models.CharField(max_length=16, default="LOCAL_PENDING",
                                  choices=SyncState.choices)
    last_synced_at = models.DateTimeField(null=True, blank=True)
```

Base concrète : `BaseModel(UUIDModel, TimeStampedModel, ActorTrackedModel, SoftDeleteModel, SyncableModel)` — classe abstraite héritée par toutes les entités métier mutables.

### 1.2 Champs de synchronisation sur les entités répliquées

| Champ | Rôle |
|---|---|
| `origin_node` | Nœud qui a créé/modifié la version courante ; sert à l'arbitrage |
| `version` | Incrémenté à chaque écriture locale ; support de la concurrence optimiste |
| `sync_state` | `LOCAL_PENDING` (pas encore poussé), `SYNCED`, `CONFLICT` |
| `last_synced_at` | Dernière confirmation d'application par le pair |

Les entités **immuables** (mouvements de stock, événements financiers, décisions de validation) ne portent **pas** `version` : elles ne sont jamais modifiées, seulement ajoutées.

---

### 1.3 Convention des énumérations (codes machine / libellés)

**Règle** : la base et l'API stockent un **code machine stable, en anglais, en majuscules**. Les documents fonctionnels (`02`, `07`, `15`, `16`) emploient des **libellés français** pour la lisibilité ; la table ci-dessous fait foi pour l'implémentation. Les libellés sont traduits par `gettext` (FR/EN).

| Domaine | Libellé FR (docs fonctionnels) | Code machine (BDD/API) |
|---|---|---|
| Workflow générique | BROUILLON / EN ATTENTE / APPROUVÉ(E) / REJETÉ(E) / ANNULÉ(E) / ARCHIVÉ(E) / CONFLIT | `DRAFT` / `PENDING` / `APPROVED` / `REJECTED` / `CANCELLED` / `ARCHIVED` / `CONFLICT` |
| Agence | BROUILLON / ACTIVE / SUSPENDUE / FERMÉE / ARCHIVÉE / SUPPRIMÉE | `DRAFT` / `ACTIVE` / `SUSPENDED` / `CLOSED` / `ARCHIVED` / `DELETED` |
| Membre | BROUILLON / EN ATTENTE / APPROUVÉ / ACTIF / SUSPENDU / ARCHIVÉ / FUSIONNÉ / REJETÉ | `DRAFT` / `PENDING` / `APPROVED` / `ACTIVE` / `SUSPENDED` / `ARCHIVED` / `MERGED` / `REJECTED` |
| Session | PLANIFIÉE / OUVERTE / EN COURS / CLÔTURÉE / ANNULÉE / ARCHIVÉE | `PLANNED` / `OPEN` / `IN_PROGRESS` / `CLOSED` / `CANCELLED` / `ARCHIVED` |
| Inscription formation | DEMANDÉE / CONFIRMÉE / PRÉSENTE / ABSENTE / CERTIFIÉE / ANNULÉE / LISTE D'ATTENTE | `REQUESTED` / `CONFIRMED` / `PRESENT` / `ABSENT` / `CERTIFIED` / `CANCELLED` / `WAITLISTED` |
| Projet | BROUILLON / SOUMIS / APPROUVÉ / EN COURS / EN PAUSE / TERMINÉ / ARCHIVÉ / REJETÉ / ANNULÉ | `DRAFT` / `SUBMITTED` / `APPROVED` / `IN_PROGRESS` / `ON_HOLD` / `COMPLETED` / `ARCHIVED` / `REJECTED` / `CANCELLED` |
| Équipement | EN SERVICE / EN MAINTENANCE / EN PANNE / HORS SERVICE / RÉFORMÉ | `IN_SERVICE` / `UNDER_MAINTENANCE` / `BROKEN` / `OUT_OF_SERVICE` / `DECOMMISSIONED` |
| Incident | OUVERT / EN COURS / RÉSOLU / CLÔTURÉ | `OPEN` / `IN_PROGRESS` / `RESOLVED` / `CLOSED` |
| Transfert de stock | BROUILLON / EN ATTENTE / APPROUVÉ / EXPÉDIÉ / REÇU / LITIGE / ANNULÉ | `DRAFT` / `PENDING` / `APPROVED` / `SHIPPED` / `RECEIVED` / `DISPUTED` / `CANCELLED` |
| Mouvement de stock | ENTRÉE / SORTIE / TRANSFERT SORTANT / TRANSFERT ENTRANT / AJUSTEMENT | `ENTRY` / `ISSUE` / `TRANSFER_OUT` / `TRANSFER_IN` / `ADJUSTMENT` |
| Évaluation | PRÉ / POST / PRATIQUE | `PRE` / `POST` / `PRACTICAL` |
| Présence | PRÉSENT / ABSENT / RETARD / EXCUSÉ | `PRESENT` / `ABSENT` / `LATE` / `EXCUSED` |

## 2. Vue d'ensemble des domaines

```mermaid
flowchart LR
    subgraph ID["Identité & organisation"]
        REG[Region] --> AGY[Agency]
        USR[User] --> MEMB[AgencyMembership]
        AGY --> MEMB
        ROLE[Role] --> MEMB
    end
    subgraph OPS["Opérations"]
        MEM[Member] --> ENR[Enrollment]
        SES[TrainingSession] --> ENR
        PRJ[Project] --> PM[ProjectMember]
        EQ[Equipment] --> INC[Incident]
        ITEM[Item] --> MOV[StockMovement]
    end
    subgraph FIN["Pilotage financier"]
        BUD[Budget] --> BL[BudgetLine]
        BL --> EXP[Expense]
        EXP --> PAY[Payment]
        EXP --> FE[FinancialEvent]
    end
    subgraph SYNC["Réplication"]
        NODE[Node] --> OUT[OutboxEvent]
        OUT --> CHG[SyncChange]
    end
    AGY --> MEM
    AGY --> SES
    AGY --> BUD
    AGY --> NODE
```

---

## 3. Modèle conceptuel (MCD)

### 3.1 Organisation, identité, sécurité

```mermaid
erDiagram
    REGION ||--o{ AGENCY : "contient"
    REGION ||--o{ REGION_ASSIGNMENT : "supervisée par"
    USER ||--o{ REGION_ASSIGNMENT : "supervise"
    AGENCY ||--o{ AGENCY_MEMBERSHIP : "emploie"
    USER ||--o{ AGENCY_MEMBERSHIP : "est affecté"
    ROLE ||--o{ AGENCY_MEMBERSHIP : "définit les droits"
    ROLE }o--o{ PERMISSION : "accorde"
    AGENCY ||--|| AGENCY_SETTINGS : "paramètre"
    AGENCY ||--o{ AGENCY_HISTORY : "historise"
    USER ||--o{ LOGIN_EVENT : "tente"
    USER ||--o{ USER_SESSION : "ouvre"

    REGION {
        uuid id
        string code
        string name
        string description
    }
    AGENCY {
        uuid id
        string code
        string name
        enum status
        uuid region_id
        uuid manager_id
    }
    USER {
        uuid id
        string email
        string matricule
        bool is_active
        bool mfa_enabled
    }
    ROLE {
        uuid id
        string code
        string name_fr
        string name_en
        enum scope
    }
```

### 3.2 Membres, formation, projets

```mermaid
erDiagram
    AGENCY ||--o{ MEMBER : "rattache"
    MEMBER_CATEGORY ||--o{ MEMBER : "classe"
    MEMBER ||--|| GUARDIAN : "tuteur (si mineur)"
    MEMBER ||--o{ CONSENT : "donne"
    MEMBER ||--o{ MEMBER_CARD : "possède"
    MEMBER ||--o| USER : "compte portail"
    MEMBER ||--o{ MEMBER_STATUS_HISTORY : "historise"
    MEMBER ||--o{ ENROLLMENT : "s'inscrit"
    TRAINING_SESSION ||--o{ ENROLLMENT : "accueille"
    TRAINING_MODULE ||--o{ TRAINING_SESSION : "instancie"
    TRAINING_DOMAIN ||--o{ TRAINING_MODULE : "regroupe"
    TRAINER ||--o{ SESSION_TRAINER : "anime"
    TRAINING_SESSION ||--o{ SESSION_TRAINER : "affecte"
    TRAINING_SESSION ||--o{ SESSION_SCHEDULE : "planifie"
    SESSION_SCHEDULE ||--o{ ATTENDANCE : "relève"
    ENROLLMENT ||--o{ EVALUATION : "évalue"
    ENROLLMENT ||--o| CERTIFICATE : "certifie"
    MEMBER ||--o{ SKILL_AWARD : "acquiert"
    SKILL ||--o{ SKILL_AWARD : "validée"

    MEMBER {
        uuid id
        string member_number
        string first_name
        string last_name
        date birth_date
        string phone
        enum status
        uuid agency_id
    }
    TRAINING_SESSION {
        uuid id
        string code
        date start_date
        date end_date
        int capacity
        enum status
    }
    ENROLLMENT {
        uuid id
        uuid session_id
        uuid member_id
        enum status
    }
    ATTENDANCE {
        uuid id
        uuid schedule_id
        uuid member_id
        enum status
        datetime recorded_at
    }
    CERTIFICATE {
        uuid id
        string code
        string verification_token
        date issued_at
    }
```

### 3.3 Projets, équipements, stocks

```mermaid
erDiagram
    AGENCY ||--o{ PROJECT : "porte"
    PROJECT ||--o{ PROJECT_MEMBER : "réunit"
    PROJECT ||--o{ PROJECT_MILESTONE : "jalonne"
    PROJECT ||--o{ DELIVERABLE : "livre"
    PROJECT ||--o{ PROJECT_EVALUATION : "évalue"
    AGENCY ||--o{ EQUIPMENT : "possède"
    EQUIPMENT_CATEGORY ||--o{ EQUIPMENT : "classe"
    EQUIPMENT ||--o{ INCIDENT : "subit"
    EQUIPMENT ||--o{ MAINTENANCE_PLAN : "planifie"
    EQUIPMENT ||--o{ MAINTENANCE_INTERVENTION : "reçoit"
    EQUIPMENT ||--o{ EQUIPMENT_USAGE : "utilisé"
    AGENCY ||--o{ ITEM : "stocke"
    ITEM_CATEGORY ||--o{ ITEM : "classe"
    ITEM ||--o{ STOCK_MOVEMENT : "mouvemente"
    STOCK_TRANSFER ||--o{ STOCK_TRANSFER_LINE : "détaille"
    INVENTORY_COUNT ||--o{ INVENTORY_COUNT_LINE : "compte"

    PROJECT {
        uuid id
        uuid agency_id
        string code
        string title
        enum status
        int budget_xaf
    }
    EQUIPMENT {
        uuid id
        string inventory_number
        uuid agency_id
        enum status
        date next_maintenance_on
    }
    STOCK_MOVEMENT {
        uuid id
        uuid item_id
        enum type
        int quantity
        int unit_cost_xaf
        datetime occurred_at
    }
```

### 3.4 Finance analytique

```mermaid
erDiagram
    AGENCY ||--o{ FISCAL_YEAR : "ouvre"
    FISCAL_YEAR ||--o{ BUDGET : "contient"
    BUDGET ||--o{ BUDGET_LINE : "ventile"
    BUDGET_CATEGORY ||--o{ BUDGET_LINE : "catégorise"
    ACTIVITY ||--o{ BUDGET_LINE : "impute"
    FUNDING_SOURCE ||--o{ BUDGET_LINE : "finance"
    BUDGET_LINE ||--o{ EXPENSE : "consomme"
    BUDGET_LINE ||--o{ COMMITMENT : "réserve"
    EXPENSE ||--o{ PAYMENT : "règle"
    REVENUE ||--o{ PAYMENT : "encaisse"
    INVOICE ||--o{ PAYMENT : "documente"
    EXPENSE ||--o{ FINANCIAL_EVENT : "émet"
    REVENUE ||--o{ FINANCIAL_EVENT : "émet"
    VALIDATION_REQUEST ||--o{ VALIDATION_DECISION : "reçoit"

    BUDGET {
        uuid id
        uuid agency_id
        uuid fiscal_year_id
        enum status
        int version_number
    }
    BUDGET_LINE {
        uuid id
        uuid budget_id
        uuid category_id
        uuid activity_id
        uuid funding_source_id
        int planned_xaf
        int approved_xaf
    }
    EXPENSE {
        uuid id
        string code
        uuid budget_line_id
        int amount_xaf
        enum status
        uuid correction_of_id
    }
    FINANCIAL_EVENT {
        uuid id
        uuid op_id
        enum type
        int amount_xaf
        string hash
        string prev_hash
    }
```

### 3.5 Synchronisation

```mermaid
erDiagram
    NODE ||--o{ OUTBOX_EVENT : "émet"
    NODE ||--o{ INBOX_EVENT : "reçoit"
    NODE ||--o{ SYNC_CURSOR : "positionne"
    NODE ||--o{ SYNC_CONFLICT : "déclenche"
    NODE ||--o{ SYNC_RUN : "exécute"
    NODE ||--o{ SYNC_CHECKPOINT : "scelle"
    NODE ||--o{ SYNC_NONCE : "authentifie"
    AGENCY ||--o| NODE : "héberge"

    OUTBOX_EVENT {
        uuid id
        uuid op_id
        string entity_type
        uuid entity_id
        enum op_type
        int base_version
        json payload
        enum status
        int attempts
        string hash
    }
    SYNC_CHANGE {
        bigint seq
        string entity_type
        uuid entity_id
        uuid agency_id
        int version
        enum change_type
    }
```

---

## 4. Modèle logique de données (MLD)

Légende : `PK` clé primaire, `FK` clé étrangère, `UQ` unicité, `IX` index, `NN` non nul, `CK` contrainte de vérification.

### 4.1 `core`

| Table | Colonnes principales | Contraintes / index |
|---|---|---|
| `core_sequence` | `id`, `agency_id FK`, `name`, `year`, `last_value` | UQ `(agency_id, name, year)` ; verrou `select_for_update` |
| `core_joblock` | `id`, `name UQ`, `locked_at`, `locked_by`, `expires_at` | IX `(expires_at)` |
| `core_setting` | `id`, `key`, `value JSON`, `scope`, `agency_id FK NULL`, `updated_at`, `updated_by FK` | UQ `(key, scope, agency_id)` |

### 4.2 `accounts`

| Table | Colonnes | Contraintes |
|---|---|---|
| `accounts_user` | `id PK`, `email UQ NN`, `matricule UQ NULL`, `password`, `first_name`, `last_name`, `phone`, `is_active`, `is_staff`, `is_superuser`, `must_change_password`, `mfa_enabled`, `mfa_secret` (chiffré), `mfa_backup_codes JSON`, `last_login`, `language`, `theme`, `failed_attempts`, `locked_until`, `created_at`, `updated_at`, `deleted_at` | IX `(email)`, IX `(matricule)`, IX `(is_active, deleted_at)` |
| `accounts_role` | `id PK`, `code UQ`, `name_fr`, `name_en`, `scope` (`NATIONAL`, `REGIONAL`, `AGENCY`, `MEMBER`), `is_system`, `description` | CK scope |
| `accounts_role_permissions` | `role_id FK`, `permission_id FK` | UQ `(role_id, permission_id)` |
| `accounts_agency_membership` | `id PK`, `user_id FK`, `agency_id FK`, `role_id FK`, `start_date`, `end_date NULL`, `is_primary`, `created_by FK`, `created_at` | UQ partielle `(user_id, agency_id, role_id)` où `end_date IS NULL` ; IX `(agency_id, role_id)` |
| `accounts_region_assignment` | `id PK`, `user_id FK`, `region_id FK`, `start_date`, `end_date NULL` | UQ partielle active |
| `accounts_login_event` | `id PK`, `user_id FK NULL`, `username_attempted`, `result` (`SUCCESS`, `BAD_PASSWORD`, `LOCKED`, `MFA_FAILED`, `INACTIVE`), `ip`, `user_agent`, `agency_id FK NULL`, `created_at` | IX `(created_at)`, IX `(user_id, created_at)` |
| `accounts_user_session` | `id PK`, `user_id FK`, `session_key UQ`, `ip`, `user_agent`, `created_at`, `last_seen_at`, `revoked_at NULL` | IX `(user_id, revoked_at)` |
| `accounts_password_reset` | `id PK`, `user_id FK`, `token_hash UQ`, `expires_at`, `used_at NULL`, `requested_ip` | IX `(expires_at)` |
| `accounts_member_invitation` | `id PK`, `member_id FK`, `code_hash UQ`, `phone`, `expires_at`, `used_at NULL`, `created_by FK` | IX `(member_id)` |

### 4.3 `regions` et `agencies`

| Table | Colonnes | Contraintes |
|---|---|---|
| `regions_region` | `id PK`, `code UQ`, `name`, `description`, `is_active`, `created_at`, `updated_at` | IX `(is_active)` |
| `agencies_agency` | `id PK`, `code UQ NN` (immuable), `name NN`, `legal_name`, `agency_type` (`FIXE`, `MOBILE`, `PARTENAIRE`), `region_id FK PROTECT`, `city`, `quarter`, `address`, `latitude`, `longitude`, `phone`, `email`, `website`, `opened_on`, `closed_on`, `status`, `manager_id FK NULL PROTECT`, `logo`, `photo`, `timezone`, `currency`, `capacity`, `notes`, `created_at`, `updated_at`, `deleted_at`, `created_by`, `updated_by` | IX `(region_id, status)`, IX `(status)` ; CK code `^[A-Z]{2,6}$` |
| `agencies_agency_settings` | `id PK`, `agency_id FK UQ`, `dual_approval_above BIGINT`, `default_attendance_threshold INT`, `default_certificate_score INT`, `allow_waitlist BOOL`, `member_number_template`, `max_upload_mb`, `notification_email`, `updated_at` | CK seuils ≥ 0 |
| `agencies_agency_history` | `id PK`, `agency_id FK`, `event_type`, `from_value JSON`, `to_value JSON`, `actor_id FK`, `occurred_at`, `comment` | IX `(agency_id, occurred_at)` |
| `agencies_agency_document` | `id PK`, `agency_id FK`, `document_id FK`, `kind` | UQ `(agency_id, document_id, kind)` |

### 4.4 `members`

| Table | Colonnes | Contraintes |
|---|---|---|
| `members_member_category` | `id PK`, `code`, `name_fr`, `name_en`, `scope` (`NATIONAL`, `AGENCY`), `agency_id FK NULL`, `requires_guardian`, `required_fields JSON`, `is_active` | UQ `(code, scope, agency_id)` |
| `members_member` | `id PK`, `member_number UQ NN`, `agency_id FK PROTECT NN`, `category_id FK PROTECT`, `first_name NN`, `last_name NN`, `birth_date`, `sex`, `phone`, `phone_alt`, `email`, `address`, `quarter`, `city`, `photo`, `status`, `joined_on`, `validated_by FK NULL`, `validated_at`, `notes_internal`, `user_id FK NULL UQ`, `created_at`, `updated_at`, `created_by`, `updated_by`, `deleted_at`, `origin_node`, `version`, `sync_state`, `last_synced_at` | IX `(agency_id, status)`, IX `(agency_id, phone)`, IX `(agency_id, last_name, first_name)`, IX `(birth_date)` ; CK statut |
| `members_guardian` | `id PK`, `member_id FK UQ`, `full_name NN`, `relation`, `phone NN`, `email`, `id_number`, `consent_signed_at` | — |
| `members_consent` | `id PK`, `member_id FK`, `consent_type` (`DATA`, `IMAGE`, `CHARTER`, `MARKETING`), `granted BOOL`, `granted_at`, `document_id FK NULL`, `ip`, `withdrawn_at NULL` | UQ `(member_id, consent_type, granted_at)` |
| `members_member_status_history` | `id PK`, `member_id FK`, `from_status`, `to_status`, `reason`, `actor_id FK`, `occurred_at` | IX `(member_id, occurred_at)` |
| `members_member_merge` | `id PK`, `source_id FK`, `target_id FK`, `reason`, `actor_id FK`, `occurred_at` | CK `source_id <> target_id` |
| `members_member_card` | `id PK`, `member_id FK`, `card_number UQ`, `issued_at`, `expires_at`, `qr_token UQ`, `pdf_file`, `status` | IX `(member_id)` |
| `members_visitor` | `id PK`, `agency_id FK`, `first_name`, `last_name`, `phone`, `email`, `organization`, `id_type`, `id_number`, `created_at`, `created_by` | IX `(agency_id, phone)` |
| `members_visit` | `id PK`, `agency_id FK`, `visitor_id FK`, `purpose`, `person_to_see`, `host_id FK NULL`, `check_in_at`, `check_out_at NULL`, `created_by` | IX `(agency_id, check_in_at)` |
| `members_member_note` | `id PK`, `member_id FK`, `body`, `visibility` (`AGENCY`, `MANAGEMENT`), `author_id FK`, `created_at` | IX `(member_id)` |

> **Note** : la recherche floue sur `last_name`/`first_name` utilise `icontains` + index ; en PostgreSQL, un index `GIN pg_trgm` est ajouté par migration conditionnelle (voir §7).

### 4.5 `training`

| Table | Colonnes | Contraintes |
|---|---|---|
| `training_domain` | `id PK`, `code UQ`, `name_fr`, `name_en`, `description`, `color`, `is_active` | — |
| `training_module` | `id PK`, `code UQ`, `domain_id FK`, `title_fr`, `title_en`, `objectives`, `prerequisites`, `duration_hours`, `level`, `target_audience`, `is_active`, `scope`, `agency_id FK NULL` | IX `(domain_id, is_active)` |
| `training_skill` | `id PK`, `code UQ`, `name_fr`, `name_en`, `domain_id FK` | — |
| `training_module_skills` | `module_id FK`, `skill_id FK` | UQ paire |
| `training_trainer` | `id PK`, `user_id FK NULL`, `agency_id FK NULL`, `trainer_type` (`INTERNAL`, `EXTERNAL`), `full_name`, `phone`, `email`, `specialties`, `bio`, `is_active` | IX `(agency_id, is_active)` |
| `training_session` | `id PK`, `code UQ`, `agency_id FK`, `module_id FK`, `title`, `start_date`, `end_date`, `location`, `capacity`, `waitlist_enabled`, `price_xaf`, `status`, `created_by`, `created_at`, `updated_at`, `origin_node`, `version`, `sync_state` | IX `(agency_id, start_date)`, IX `(agency_id, status)` ; CK `end_date >= start_date`, `capacity > 0` |
| `training_session_trainer` | `id PK`, `session_id FK`, `trainer_id FK`, `role` (`MAIN`, `ASSISTANT`), `planned_hours` | UQ `(session_id, trainer_id)` |
| `training_session_schedule` | `id PK`, `session_id FK`, `date`, `start_time`, `end_time`, `topic`, `room` | IX `(session_id, date)` ; CK `end_time > start_time` |
| `training_enrollment` | `id PK`, `session_id FK`, `member_id FK`, `status`, `enrolled_at`, `enrolled_by FK`, `source` (`AGENCY`, `PORTAL`, `PWA`), `cancelled_at NULL`, `cancel_reason` | UQ `(session_id, member_id)` ; IX `(member_id, status)` |
| `training_attendance` | `id PK`, `schedule_id FK`, `member_id FK`, `status` (`PRESENT`, `ABSENT`, `LATE`, `EXCUSED`), `recorded_by FK`, `recorded_at`, `note` | UQ `(schedule_id, member_id)` ; IX `(member_id, recorded_at)` |
| `training_evaluation` | `id PK`, `enrollment_id FK`, `evaluation_type`, `score`, `max_score`, `passed`, `evaluator_id FK`, `evaluated_at`, `comment` | CK `score >= 0 AND score <= max_score` |
| `training_skill_award` | `id PK`, `member_id FK`, `skill_id FK`, `session_id FK NULL`, `level`, `awarded_by FK`, `awarded_at` | UQ `(member_id, skill_id, awarded_at)` |
| `training_certificate` | `id PK`, `code UQ`, `certificate_type`, `enrollment_id FK`, `member_id FK`, `session_id FK`, `issued_at`, `issued_by FK`, `pdf_file`, `verification_token UQ`, `revoked_at NULL`, `revocation_reason` | UQ `(enrollment_id, certificate_type)` ; IX `(member_id, issued_at)` |

### 4.6 `projects`

| Table | Colonnes | Contraintes |
|---|---|---|
| `projects_project` | `id PK`, `code UQ`, `agency_id FK`, `title`, `summary`, `description`, `status`, `owner_member_id FK NULL`, `owner_user_id FK NULL`, `supervisor_id FK NULL`, `start_date`, `end_date`, `budget_xaf`, `is_innovation`, `validated_by FK NULL`, `validated_at`, `created_at`, `updated_at`, `origin_node`, `version`, `sync_state` | CK `owner_member_id IS NOT NULL OR owner_user_id IS NOT NULL` |
| `projects_project_member` | `id PK`, `project_id FK`, `member_id FK NULL`, `user_id FK NULL`, `role`, `joined_at` | UQ `(project_id, member_id)` |
| `projects_project_milestone` | `id PK`, `project_id FK`, `title`, `due_date`, `weight INT`, `progress INT`, `status`, `completed_at NULL` | CK `progress BETWEEN 0 AND 100`, `weight > 0` |
| `projects_deliverable` | `id PK`, `project_id FK`, `title`, `due_date`, `document_id FK NULL`, `status`, `submitted_at NULL`, `validated_at NULL` | — |
| `projects_project_evaluation` | `id PK`, `project_id FK`, `evaluator_id FK`, `evaluated_at`, `criteria JSON`, `total_score`, `comment` | CK `total_score >= 0` |
| `projects_project_status_history` | `id PK`, `project_id FK`, `from_status`, `to_status`, `actor_id FK`, `occurred_at`, `comment` | IX `(project_id, occurred_at)` |

### 4.7 `equipment`

| Table | Colonnes | Contraintes |
|---|---|---|
| `equipment_category` | `id PK`, `code UQ`, `name_fr`, `name_en`, `maintenance_interval_days NULL` | — |
| `equipment_equipment` | `id PK`, `inventory_number UQ`, `agency_id FK`, `category_id FK`, `name`, `brand`, `model`, `serial_number`, `purchase_date`, `purchase_value_xaf`, `supplier_id FK NULL`, `location`, `status`, `condition`, `warranty_end`, `next_maintenance_on`, `usage_hours`, `photo`, `notes`, `created_at`, `updated_at`, `origin_node`, `version`, `sync_state` | UQ `(agency_id, inventory_number)` ; IX `(agency_id, status)`, IX `(next_maintenance_on)` |
| `equipment_usage` | `id PK`, `equipment_id FK`, `used_on`, `hours`, `purpose`, `operator_id FK`, `session_id FK NULL`, `project_id FK NULL` | IX `(equipment_id, used_on)` |
| `equipment_incident` | `id PK`, `code UQ`, `equipment_id FK`, `severity`, `description`, `reported_by FK`, `reported_at`, `status`, `resolved_at NULL`, `resolution` | IX `(equipment_id, status)` |
| `equipment_maintenance_plan` | `id PK`, `equipment_id FK`, `interval_days`, `last_done_on`, `next_due_on`, `checklist JSON`, `is_active` | IX `(next_due_on, is_active)` |
| `equipment_intervention` | `id PK`, `equipment_id FK`, `incident_id FK NULL`, `plan_id FK NULL`, `intervention_type`, `scheduled_on`, `done_on NULL`, `technician_id FK`, `diagnosis`, `actions`, `cost_xaf`, `status`, `document_id FK NULL` | CK intervention_type cohérent |
| `equipment_intervention_part` | `id PK`, `intervention_id FK`, `item_id FK`, `quantity`, `unit_cost_xaf` | UQ `(intervention_id, item_id)` |
| `equipment_alert` | `id PK`, `equipment_id FK`, `alert_type`, `level`, `message`, `created_at`, `acknowledged_at NULL`, `acknowledged_by FK NULL` | IX `(equipment_id, alert_type)` |
| `equipment_transfer` | `id PK`, `equipment_id FK`, `from_agency_id FK`, `to_agency_id FK`, `status`, `requested_by FK`, `validated_by FK NULL`, `shipped_at NULL`, `received_at NULL`, `note` | IX `(equipment_id, status)` |

### 4.8 `inventory`

| Table | Colonnes | Contraintes |
|---|---|---|
| `inventory_supplier` | `id PK`, `code`, `name`, `contact_name`, `phone`, `email`, `address`, `agency_id FK NULL` (NULL = national), `is_active` | UQ `(code, agency_id)` |
| `inventory_item_category` | `id PK`, `code`, `name_fr`, `name_en`, `scope`, `agency_id FK NULL` | UQ `(code, scope, agency_id)` |
| `inventory_item` | `id PK`, `code`, `agency_id FK`, `category_id FK`, `name`, `unit`, `min_stock`, `current_qty`, `unit_cost_xaf`, `average_cost_xaf`, `location`, `is_active`, `created_at`, `updated_at`, `origin_node`, `version`, `sync_state` | UQ `(agency_id, code)` ; IX `(agency_id, is_active)` ; CK `current_qty >= 0` (sauf ajustement contrôlé) |
| `inventory_movement` | `id PK`, `agency_id FK`, `item_id FK`, `movement_type` (`ENTRY`, `ISSUE`, `TRANSFER_OUT`, `TRANSFER_IN`, `ADJUSTMENT`), `quantity` (signé), `unit_cost_xaf`, `total_cost_xaf`, `reason`, `reference`, `transfer_id FK NULL`, `count_id FK NULL`, `actor_id FK`, `occurred_at`, `op_id UQ` | IX `(item_id, occurred_at)`, IX `(agency_id, occurred_at)` ; **immuable** |
| `inventory_transfer` | `id PK`, `code UQ`, `from_agency_id FK`, `to_agency_id FK`, `status`, `shipped_by FK NULL`, `shipped_at NULL`, `received_by FK NULL`, `received_at NULL`, `note`, `origin_node`, `version` | CK `from_agency_id <> to_agency_id` |
| `inventory_transfer_line` | `id PK`, `transfer_id FK`, `item_id FK`, `quantity`, `unit_cost_xaf` | UQ `(transfer_id, item_id)` |
| `inventory_count` | `id PK`, `code UQ`, `agency_id FK`, `counted_on`, `status`, `responsible_id FK`, `validated_by FK NULL`, `validated_at NULL` | IX `(agency_id, status)` |
| `inventory_count_line` | `id PK`, `count_id FK`, `item_id FK`, `expected_qty`, `counted_qty`, `difference`, `unit_cost_xaf`, `justification` | UQ `(count_id, item_id)` |

### 4.9 `finance`

| Table | Colonnes | Contraintes |
|---|---|---|
| `finance_fiscal_year` | `id PK`, `agency_id FK`, `year`, `start_date`, `end_date`, `status`, `closed_by FK NULL`, `closed_at NULL` | UQ `(agency_id, year)` ; CK `end_date > start_date` |
| `finance_budget_category` | `id PK`, `code`, `name_fr`, `name_en`, `parent_id FK NULL`, `scope`, `agency_id FK NULL`, `is_active` | UQ `(code, scope, agency_id)` |
| `finance_activity` | `id PK`, `code`, `name`, `activity_type`, `agency_id FK NULL`, `project_id FK NULL`, `start_date`, `end_date`, `status` | IX `(agency_id, activity_type)` |
| `finance_funding_source` | `id PK`, `code`, `name`, `source_type` (`SUBSIDY`, `PARTNERSHIP`, `OWN_REVENUE`, `DONATION`), `donor`, `agency_id FK NULL`, `is_active` | UQ `(code, agency_id)` |
| `finance_budget` | `id PK`, `code UQ`, `agency_id FK`, `fiscal_year_id FK`, `version_number`, `status`, `total_xaf`, `approved_by FK NULL`, `approved_at NULL`, `notes`, `created_at`, `updated_at`, `origin_node`, `version`, `sync_state` | UQ `(agency_id, fiscal_year_id, version_number)` |
| `finance_budget_line` | `id PK`, `budget_id FK`, `category_id FK`, `activity_id FK NULL`, `funding_source_id FK NULL`, `planned_xaf`, `approved_xaf`, `notes` | UQ `(budget_id, category_id, activity_id, funding_source_id)` ; CK montants ≥ 0 |
| `finance_commitment` | `id PK`, `code UQ`, `agency_id FK`, `budget_line_id FK`, `label`, `amount_xaf`, `supplier_id FK NULL`, `committed_on`, `status`, `created_by FK`, `approved_by FK NULL`, `approved_at NULL`, `origin_node`, `version` | IX `(agency_id, status)` |
| `finance_revenue` | `id PK`, `code UQ`, `agency_id FK`, `fiscal_year_id FK`, `budget_line_id FK NULL`, `category_id FK`, `activity_id FK NULL`, `funding_source_id FK NULL`, `project_id FK NULL`, `label`, `amount_xaf`, `received_on`, `status`, `payment_method`, `reference`, `document_id FK NULL`, `created_at`, `updated_at`, `origin_node`, `version` | CK montant > 0 |
| `finance_expense` | `id PK`, `code UQ`, `agency_id FK`, `fiscal_year_id FK`, `budget_line_id FK`, `category_id FK`, `activity_id FK NULL`, `project_id FK NULL`, `label`, `amount_xaf`, `supplier_id FK NULL`, `invoice_ref`, `incurred_on`, `status`, `requested_by FK`, `approved_by FK NULL`, `approved_at NULL`, `paid_at NULL`, `correction_of_id FK NULL`, `origin_node`, `version` | IX `(agency_id, status)`, IX `(agency_id, incurred_on)` ; CK montant > 0 |
| `finance_invoice` | `id PK`, `code UQ`, `agency_id FK`, `invoice_type` (`SUPPLIER`, `CUSTOMER`), `number`, `invoice_date`, `due_date`, `amount_xaf`, `tax_xaf`, `total_xaf`, `party_id FK NULL`, `party_label`, `status`, `document_id FK NULL` | UQ `(agency_id, invoice_type, number)` |
| `finance_invoice_line` | `id PK`, `invoice_id FK`, `description`, `quantity`, `unit_price_xaf`, `line_total_xaf` | CK quantité > 0 |
| `finance_payment` | `id PK`, `code UQ`, `agency_id FK`, `invoice_id FK NULL`, `expense_id FK NULL`, `revenue_id FK NULL`, `amount_xaf`, `paid_on`, `method`, `reference`, `status`, `recorded_by FK`, `reconciled_at NULL` | CK une seule cible non nulle ; CK montant > 0 |
| `finance_reconciliation` | `id PK`, `agency_id FK`, `period_start`, `period_end`, `account_label`, `statement_reference`, `difference_xaf`, `status`, `done_by FK`, `done_at` | — |
| `finance_reconciliation_payment` | `reconciliation_id FK`, `payment_id FK` | UQ paire |
| `finance_supporting_document` | `id PK`, `expense_id FK NULL`, `revenue_id FK NULL`, `commitment_id FK NULL`, `document_id FK` | CK au moins une cible |
| `finance_financial_event` | `id PK`, `op_id UQ`, `agency_id FK`, `event_type`, `entity_type`, `entity_id UUID`, `amount_xaf`, `occurred_at`, `actor_id FK NULL`, `payload JSON`, `prev_hash`, `hash`, `origin_node`, `created_at` | **Immuable** ; IX `(agency_id, occurred_at)`, `(entity_type, entity_id)` |
| `finance_threshold` | `id PK`, `scope`, `agency_id FK NULL`, `module`, `min_amount`, `max_amount`, `required_approvals`, `forbid_self_approval`, `is_active` | CK `max_amount >= min_amount`, `required_approvals >= 1` |

### 4.10 `approvals`

| Table | Colonnes | Contraintes |
|---|---|---|
| `approvals_validation_request` | `id PK`, `entity_type`, `entity_id UUID`, `agency_id FK`, `requested_by FK`, `requested_at`, `status`, `amount_xaf NULL`, `threshold_id FK NULL`, `comment`, `origin_node`, `version` | UQ `(entity_type, entity_id, status)` où `status = 'PENDING'` |
| `approvals_validation_decision` | `id PK`, `request_id FK`, `validator_id FK`, `decision` (`APPROVE`, `REJECT`), `comment`, `decided_at`, `source_node`, `op_id UQ`, `hash` | **Append-only** ; IX `(request_id, decided_at)` |
| `approvals_validation_history` | `id PK`, `request_id FK`, `from_status`, `to_status`, `actor_id FK`, `occurred_at`, `comment` | IX `(request_id, occurred_at)` |

### 4.11 `events`, `documents`, `communications`

| Table | Colonnes | Contraintes |
|---|---|---|
| `events_event` | `id PK`, `code UQ`, `agency_id FK NULL`, `title`, `description`, `event_type`, `start_at`, `end_at`, `location`, `capacity`, `status`, `organizer_id FK`, `budget_xaf`, `report_document_id FK NULL`, `origin_node`, `version` | CK `end_at > start_at` |
| `events_event_session` | `id PK`, `event_id FK`, `title`, `date`, `start_time`, `end_time`, `room` | IX `(event_id, date)` |
| `events_speaker` | `id PK`, `full_name`, `organization`, `bio`, `phone`, `email` | — |
| `events_event_speaker` | `id PK`, `event_id FK`, `speaker_id FK`, `role` | UQ paire |
| `events_registration` | `id PK`, `event_id FK`, `member_id FK NULL`, `external_name`, `external_phone`, `status`, `registered_at`, `checked_in_at NULL`, `source` | UQ `(event_id, member_id)` ; CK membre ou externe |
| `events_attendance` | `id PK`, `session_id FK`, `registration_id FK`, `status`, `recorded_by FK`, `recorded_at` | UQ `(session_id, registration_id)` |
| `events_competition` | `id PK`, `event_id FK`, `name`, `category`, `criteria JSON`, `status` | — |
| `events_jury` | `id PK`, `competition_id FK`, `user_id FK`, `role` | UQ paire |
| `events_entry` | `id PK`, `competition_id FK`, `project_id FK NULL`, `member_id FK NULL`, `title`, `description` | CK cible |
| `events_score` | `id PK`, `entry_id FK`, `jury_id FK`, `criteria_scores JSON`, `total_score` | UQ `(entry_id, jury_id)` |
| `events_award` | `id PK`, `competition_id FK`, `entry_id FK`, `rank`, `prize_label`, `amount_xaf` | UQ `(competition_id, rank)` |
| `documents_folder` | `id PK`, `agency_id FK NULL`, `parent_id FK NULL`, `name`, `access_level`, `created_by` | UQ `(agency_id, parent_id, name)` |
| `documents_category` | `id PK`, `code`, `name_fr`, `name_en`, `is_active` | — |
| `documents_document` | `id PK`, `agency_id FK NULL`, `folder_id FK NULL`, `category_id FK`, `title`, `description`, `access_level`, `owner_id FK`, `current_version_id FK NULL`, `is_archived`, `created_at`, `updated_at`, `origin_node` | IX `(agency_id, category_id)` |
| `documents_version` | `id PK`, `document_id FK`, `version_number`, `file`, `original_filename`, `mime_type`, `size_bytes`, `sha256`, `uploaded_by FK`, `uploaded_at`, `change_note` | UQ `(document_id, version_number)` ; UQ `(document_id, sha256)` |
| `documents_link` | `id PK`, `document_id FK`, `entity_type`, `entity_id UUID` | IX `(entity_type, entity_id)` |
| `documents_access` | `id PK`, `document_id FK`, `user_id FK NULL`, `role_id FK NULL`, `can_read`, `can_write` | CK user ou role |
| `communications_notification` | `id PK`, `recipient_id FK`, `agency_id FK NULL`, `notification_type`, `priority`, `title`, `body`, `action_url`, `read_at NULL`, `created_at`, `expires_at NULL` | IX `(recipient_id, read_at)` |
| `communications_announcement` | `id PK`, `scope`, `agency_id FK NULL`, `region_id FK NULL`, `title`, `body`, `starts_at`, `ends_at`, `audience_roles JSON`, `status`, `created_by FK`, `created_at` | IX `(scope, starts_at)` |
| `communications_message_template` | `id PK`, `code`, `channel`, `subject`, `body`, `language` | UQ `(code, channel, language)` |
| `communications_outbound_message` | `id PK`, `channel`, `recipient`, `payload JSON`, `status`, `attempts`, `last_error`, `sent_at NULL`, `provider_ref`, `created_at` | IX `(status, created_at)` |
| `communications_alert` | `id PK`, `agency_id FK NULL`, `alert_type`, `severity`, `title`, `message`, `entity_type`, `entity_id`, `status`, `acknowledged_by FK NULL`, `created_at` | IX `(agency_id, status)` |

### 4.12 `sync` et `audit` et `reporting`

| Table | Colonnes | Contraintes |
|---|---|---|
| `sync_node` | `id PK`, `node_id UQ`, `role` (`CENTRAL`, `AGENCY`), `agency_id FK NULL`, `install_id`, `name`, `status`, `hmac_key_id`, `secret_hash`, `protocol_version`, `last_seen_at`, `last_push_at`, `last_pull_at`, `clock_offset_ms`, `created_at` | UQ `(role, agency_id)` pour `AGENCY` |
| `sync_outbox_event` | `id PK`, `op_id UQ`, `node_id FK`, `entity_type`, `entity_id UUID`, `op_type`, `base_version`, `payload JSON`, `occurred_at`, `created_at`, `status`, `attempts`, `next_attempt_at`, `last_error`, `prev_hash`, `hash`, `aggregate_seq` | IX `(status, next_attempt_at)`, `(node_id, aggregate_seq)` |
| `sync_inbox_event` | `id PK`, `op_id UQ`, `node_id FK`, `received_at`, `applied_at NULL`, `status`, `error`, `payload_hash`, `payload JSON` | IX `(status, received_at)` |
| `sync_change` | `seq BIGINT PK AUTO`, `entity_type`, `entity_id UUID`, `agency_id FK NULL`, `version`, `change_type`, `changed_at`, `origin_node` | IX `(agency_id, seq)`, `(entity_type, entity_id, seq)` |
| `sync_cursor` | `id PK`, `node_id FK`, `stream`, `last_seq BIGINT`, `updated_at` | UQ `(node_id, stream)` |
| `sync_conflict` | `id PK`, `entity_type`, `entity_id UUID`, `agency_id FK`, `node_id FK`, `conflict_type`, `local_version`, `remote_version`, `details JSON`, `status`, `resolution`, `resolved_by FK NULL`, `resolved_at NULL`, `op_id` | IX `(status, created_at)` |
| `sync_checkpoint` | `id PK`, `node_id FK`, `stream`, `seq`, `hash`, `signature`, `created_at` | UQ `(node_id, stream, seq)` |
| `sync_run` | `id PK`, `node_id FK`, `direction`, `started_at`, `finished_at NULL`, `sent INT`, `received INT`, `applied INT`, `conflicts INT`, `errors INT`, `status`, `message` | IX `(node_id, started_at)` |
| `sync_nonce` | `id PK`, `node_id FK`, `nonce UQ`, `seen_at` | IX `(seen_at)` (purge > 24 h) |
| `audit_audit_log` | `id PK`, `occurred_at`, `actor_id FK NULL`, `actor_label`, `agency_id FK NULL`, `action`, `entity_type`, `entity_id`, `before JSON`, `after JSON`, `ip`, `user_agent`, `correlation_id`, `node_id` | IX `(occurred_at)`, `(entity_type, entity_id)`, `(agency_id, occurred_at)` ; **append-only** |
| `reporting_dashboard_snapshot` | `id PK`, `scope`, `agency_id FK NULL`, `region_id FK NULL`, `period_start`, `period_end`, `metrics JSON`, `computed_at` | UQ `(scope, agency_id, region_id, period_start, period_end)` |
| `reporting_export_job` | `id PK`, `user_id FK`, `export_type`, `params JSON`, `file`, `status`, `created_at`, `expires_at` | IX `(user_id, created_at)` |
| `reporting_saved_filter` | `id PK`, `user_id FK`, `module`, `name`, `params JSON` | UQ `(user_id, module, name)` |

---

## 5. Règles d'intégrité transverses

| # | Règle | Mise en œuvre |
|---|---|---|
| RI-01 | Un membre appartient à une seule agence | FK `agency_id` non nulle |
| RI-02 | Un `agency_id` d'une entité ne peut pas changer après création | `save()` + contrainte applicative ; trigger PostgreSQL optionnel |
| RI-03 | Une ligne budgétaire appartient à l'agence du budget | Validation service + `CheckConstraint` impossible en SQL simple → contrôle applicatif testé |
| RI-04 | Un paiement référence exactement une cible (facture, dépense ou recette) | `CheckConstraint` sur les trois nullables |
| RI-05 | Un mouvement de stock n'est jamais modifié | Absence de `updated_at`, `save()` interdit hors création, `ImmutableRecordError` |
| RI-06 | Une décision de validation n'est jamais modifiée | Idem + `op_id` unique |
| RI-07 | Un événement financier n'est jamais modifié | Idem + chaîne de hachage |
| RI-08 | Un `op_id` est unique globalement | `UniqueConstraint` sur `op_id` (outbox, inbox, financial_event, décisions) |
| RI-09 | Un document a au moins une version si son statut est `FINAL` | Validation service |
| RI-10 | Un exercice clôturé n'accepte plus d'opération | Contrôle service + index de lecture |
| RI-11 | Un membre supprimé logiquement conserve son numéro | Le numéro reste réservé : `UniqueConstraint(member_number)` sans condition sur `deleted_at` |

---

## 6. Index et performances

### 6.1 Index systématiques

| Table type | Index |
|---|---|
| Entités d'agence | `(agency_id, deleted_at)`, `(agency_id, created_at DESC)` |
| Entités à statut | `(agency_id, status)` |
| Recherche personne | `(agency_id, last_name, first_name)`, `(agency_id, phone)` |
| Finances | `(agency_id, fiscal_year_id, status)`, `(budget_line_id)` |
| Stocks | `(item_id, occurred_at)`, `(agency_id, occurred_at)` |
| Sync | `(status, next_attempt_at)`, `(node_id, seq)`, `(agency_id, seq)` |
| Audit | `(occurred_at DESC)`, `(entity_type, entity_id)` |

### 6.2 Index partiels (portables SQLite ≥ 3.8 / PostgreSQL)

```sql
CREATE INDEX idx_member_active ON members_member (agency_id, last_name)
    WHERE deleted_at IS NULL;
CREATE INDEX idx_outbox_pending ON sync_outbox_event (next_attempt_at)
    WHERE status IN ('PENDING', 'FAILED');
CREATE INDEX idx_validation_pending ON approvals_validation_request (agency_id, requested_at)
    WHERE status = 'PENDING';
```

### 6.3 Requêtes critiques et plans attendus

| Requête | Plan attendu |
|---|---|
| Liste des membres paginée | Index `(agency_id, last_name)` + tri |
| Feuille de présence d'une séance | Index `(schedule_id, member_id)` |
| Solde budgétaire d'une ligne | Agrégat sur `finance_expense(budget_line_id, status)` + index |
| Événements en attente de sync | Index partiel `next_attempt_at` |
| Dernières opérations d'un membre (portail) | Index `(member_id, created_at DESC)` sur les tables de participation |

---

## 7. Portabilité PostgreSQL / SQLite

### 7.1 Fonctionnalités nécessitant PostgreSQL (et équivalent SQLite)

| Fonctionnalité | PostgreSQL | SQLite (V1) | Impact |
|---|---|---|---|
| Recherche plein texte | `SearchVector`, `GinIndex` | `LIKE`/`icontains` sur colonnes indexées + table FTS5 optionnelle | Recherche moins performante sur gros volumes |
| Recherche floue (fautes de frappe) | `pg_trgm`, similarité | `icontains` + normalisation (minuscules, sans accents) | Pas de tolérance aux fautes en SQLite |
| Requêtes JSON | Opérateurs `jsonb`, index GIN | `json_extract`, pas d'index GIN | Payloads non requêtés en masse |
| `SELECT ... FOR UPDATE` | Verrouillage ligne réel | Ignoré → verrou applicatif `JobLock` + transaction `IMMEDIATE` | Concurrence plus grossière |
| Vues matérialisées | Oui | Non → table `reporting_dashboard_snapshot` | Agrégats calculés par tâche |
| Index partiels | Oui | Oui (≥ 3.8) | Portable |
| Contraintes `CHECK` | Oui | Oui | Portable |
| `ON CONFLICT DO NOTHING` | Oui | Oui (≥ 3.24) | Idempotence portable |
| Colonnes générées | Oui | Oui (≥ 3.31) | Portable |
| `ArrayField` | Oui | **Non** → `JSONField` | À éviter |
| `citext` | Oui | **Non** → normalisation applicative | E-mail comparé en minuscules |
| `interval` | Oui | Stockage en secondes | Calculs de dates en Python |
| `EXPLAIN ANALYZE` | Oui | `EXPLAIN QUERY PLAN` | Revue de perf |
| Sauvegarde à chaud | `pg_dump` / PITR | `.backup` / copie WAL | Procédures distinctes |

**Décision** : aucune fonctionnalité cœur ne dépend d'une capacité PostgreSQL seule. Les écarts sont encapsulés dans `core/db/` et couverts par les tests de la CI double moteur.

### 7.2 Contraintes de concurrence SQLite

- `PRAGMA journal_mode=WAL`, `synchronous=NORMAL`, `busy_timeout=5000`, `foreign_keys=ON`.
- Un seul processus applicatif (Gunicorn 1 worker + threads, ou Waitress) par base.
- Transactions **courtes**, pas d'appel réseau dans une transaction.
- Verrou applicatif `JobLock` pour les tâches planifiées.
- Bascule PostgreSQL documentée au-delà de 15 utilisateurs simultanés ou 5 Go.

### 7.3 Migration SQLite → PostgreSQL

Procédure (détaillée dans `docs/14-migration-sqlite-postgresql.md`) :

1. Gel des écritures (mode maintenance) et sauvegarde du fichier SQLite.
2. Export par table dans l'ordre des dépendances : `manage.py export_dataset --output dump.json`.
3. Création d'une base PostgreSQL vide, `migrate` **sans données**.
4. Import : `manage.py import_dataset dump.json` (UUID conservés, `created_at` restaurés, séquences humaines recalculées).
5. Vérification : nombre de lignes par table, sommes de contrôle des montants, échantillon de 50 enregistrements par module.
6. Bascule de `DATABASE_URL`, redémarrage, tests de fumée, réactivation des écritures.
7. Conservation du dump et du fichier SQLite 30 jours.

**Pièges documentés** : fuseaux horaires (forcer UTC), `JSONField` (sérialisation stable), fichiers médias (chemins relatifs conservés), `contenttypes`/`auth.permission` régénérés par `migrate`, index recréés par les migrations.

---

## 8. Rétention et archivage

| Donnée | Durée active | Après |
|---|---|---|
| Membres | Tant qu'actifs | Archivage 5 ans après dernière activité, purge documentée |
| Visites | 3 ans | Agrégats anonymisés conservés |
| Formations/présences | 10 ans (valeur probante) | Archive froide |
| Finances | 10 ans (obligation comptable usuelle) | Archive froide, pièces conservées |
| Audit | 5 ans | Archive froide |
| Documents | Selon catégorie | Purge sur validation du responsable |
| Journaux techniques | 90 jours | Rotation |

Toute purge est **logique puis physique par tâche planifiée**, journalisée, et réversible tant que la purge physique n'a pas eu lieu.

---

## 9. Correspondance besoins → modèle

| Besoin | Tables |
|---|---|
| BF-ADM | `regions_region`, `agencies_*`, `accounts_agency_membership` |
| BF-SEC | `accounts_user`, `accounts_role*`, `accounts_login_event`, `accounts_user_session` |
| BF-MEM | `members_*` |
| BF-POR | `members_member` (lien `user_id`), `training_*`, `projects_*`, `documents_*`, `communications_notification` |
| BF-FOR | `training_*` |
| BF-PRJ | `projects_*` |
| BF-EQP | `equipment_*` |
| BF-STK | `inventory_*` |
| BF-FIN | `finance_*` |
| BF-VAL | `approvals_*` |
| BF-EVT | `events_*` |
| BF-DOC | `documents_*` |
| BF-COM | `communications_*` |
| BF-PIL | `reporting_*` |
| BF-SYN | `sync_*` |
| Audit | `audit_audit_log` |
