Compare commits

..

16 Commits

Author SHA1 Message Date
Matthieu 5fbdda1983 docs : log LST-56 socle back session learnings 2026-06-19 15:00:17 +02:00
Matthieu b301c543bb feat(shared) : add column comments catalog helper for migrations 2026-06-19 14:38:40 +02:00
Matthieu 3053c09522 feat(shared) : add timestampable/blamable trait and doctrine subscriber 2026-06-19 14:37:28 +02:00
Matthieu 52399b35d9 feat(sidebar) : expose GET /api/sidebar filtered by active modules 2026-06-19 14:35:17 +02:00
Matthieu 748289b61a feat(modules) : expose GET /api/modules and module registry 2026-06-19 14:33:53 +02:00
Matthieu 2d0e9de155 docs : add implementation plan for socle back (LST-56 / 0.1)
Plan TDD en 4 tâches : endpoints /api/modules et /api/sidebar, garde-fou Timestampable/Blamable, helper ColumnCommentsCatalog.
2026-06-19 10:56:27 +02:00
Matthieu a510b2ca73 docs : add modular monolith migration roadmap and socle design
Plan de migration complet Lesstime vers modular monolith DDD (archi Starseed) : roadmap en 14 tickets ordonnés par dépendances + design technique détaillé du socle (Shared/, contrats, endpoints modules/sidebar, plan strangler).
2026-06-19 10:50:14 +02:00
gitea-actions d0a49322e1 chore: bump version to v0.4.30
Auto Tag Develop / tag (push) Successful in 6s
Build & Push Docker Image / build (push) Successful in 2m21s
2026-06-19 07:21:59 +00:00
matthieu 3e26c12052 Merge pull request 'fix(prod) : droits www-data sur le volume de logs' (#11) from fix/prod-logs-volume-permissions into develop
Auto Tag Develop / tag (push) Successful in 7s
Reviewed-on: #11
2026-06-19 07:21:52 +00:00
Matthieu 6c32110288 fix(prod) : créer var/log dans l'image pour que le volume de logs hérite des droits www-data
Le volume nommé lesstime_logs est monté sur /var/www/html/var/log, mais ce
dossier n'existe pas dans l'image. Au premier montage d'un volume vide, Docker
crée le point de montage en root:root, ce qui empêche www-data d'écrire les
logs et fait crasher l'application. En créant var/log avant le chown -R, tout
volume de logs neuf hérite des droits www-data automatiquement.
2026-06-19 09:07:14 +02:00
gitea-actions da8beb2b2d chore: bump version to v0.4.29
Auto Tag Develop / tag (push) Successful in 6s
Build & Push Docker Image / build (push) Successful in 28s
2026-06-15 09:52:11 +00:00
matthieu 16748cce40 Merge pull request 'feat(notification) : recâbler les notifications sur les événements de tâche' (#10) from feat/task-notifications into develop
Auto Tag Develop / tag (push) Successful in 9s
Reviewed-on: #10
2026-06-15 09:52:01 +00:00
matthieu aee279eb5f Merge branch 'develop' into feat/task-notifications 2026-06-15 09:51:52 +00:00
Matthieu 1351bbf1b1 docs(notification) : spec et plan d'implémentation des notifications de tâche 2026-06-15 11:45:22 +02:00
Matthieu 9e63f3d268 feat(notification) : notifier les collaborateurs ajoutés à une tâche 2026-06-15 11:45:01 +02:00
Matthieu 390f2a40a8 feat(notification) : notifier le nouvel assigné d'une tâche 2026-06-15 11:44:12 +02:00
36 changed files with 3220 additions and 3 deletions
@@ -54,6 +54,25 @@
- **Pattern**: Retirer de composer.json + bundles.php + supprimer config YAML + templates
- **Learning**: API Platform ne requiert PAS twig, c'est juste suggéré pour Swagger UI
## Session 2026-06-19 (LST-56 / 0.1 — Socle back modular monolith)
### Contexte
- Ticket exécuté via plan TDD dédié (`docs/superpowers/plans/2026-06-19-lst-56-socle-back.md`) délégué à un sous-agent (contexte isolé), pilotage MCP/chrono/vérif depuis la session principale.
- 4 tâches, 14 nouveaux tests (110 total, 216 assertions, vert), 4 commits (un par tâche).
### Patterns
- **Strangler 100 % additif** : nouveau noyau `src/Shared/` (Domain/Contract, Domain/Module, Domain/Sidebar, Domain/Trait, Application, Infrastructure/{ApiPlatform,Doctrine,Security,Database}) sans toucher au métier — `make test` reste vert sans migration.
- **Endpoints DTO purs** : logique métier dans classes pures testées unitairement (`ModuleRegistry`, `SidebarFilter`), exposées par Providers API Platform minces (`ModulesProvider`/`SidebarProvider`) sur des Resources DTO.
- **resolve_target_entities** : contrat `Shared\Domain\Contract\UserInterface` mappé sur `App\Entity\User` (sera re-pointé vers `Module\Core\User` en 1.1). Inert tant qu'aucune entité n'utilise le trait.
### Gotchas
- **API Platform 4 découvre les Resources sous `src/Shared/...` sans config `mapping.paths`** — le 404 anticipé dans le plan ne s'est pas produit, aucun ajout dans `api_platform.yaml` nécessaire.
- **Hook pre-commit php-cs-fixer** normalise le style du code fourni dans le plan : `\DateTimeImmutable``DateTimeImmutable` importé, FQN→`use`, `static::createClient()``self::`. Pur style, tests inchangés. Ne pas lutter contre.
- **`config/reference.php`** : fichier auto-généré qui apparaît modifié dans `git status` — ne jamais le committer.
### Time tracking
- Le sous-agent a stoppé lui-même le timer d'implémentation (id 1005, 35 min) — garder le time-tracking sur la session principale pour rester maître du chrono si un sous-agent a accès aux tools MCP lesstime.
## Meta-learnings
- **Parallélisation**: Les tickets touchant des fichiers indépendants peuvent tourner en parallèle sans problème
- **MCP status**: Toujours mettre "En cours" AVANT de commencer, "Terminé" APRÈS validation
+11
View File
@@ -0,0 +1,11 @@
<?php
declare(strict_types=1);
/*
* Liste ordonnée des modules actifs (classes implémentant App\Shared\Domain\Module\ModuleInterface).
* Activer/désactiver un module = ajouter/commenter sa ligne. Exposé par GET /api/modules.
*/
return [
// Aucun module pour l'instant — les modules arrivent à partir du ticket 1.1 (Core).
];
+2
View File
@@ -13,6 +13,8 @@ doctrine:
identity_generation_preferences:
Doctrine\DBAL\Platforms\PostgreSQLPlatform: identity
auto_mapping: true
resolve_target_entities:
App\Shared\Domain\Contract\UserInterface: App\Entity\User
mappings:
App:
type: attribute
+2
View File
@@ -62,6 +62,8 @@ security:
- { path: ^/api/docs, roles: PUBLIC_ACCESS }
# Version de l'application en public
- { path: ^/api/version, roles: PUBLIC_ACCESS, methods: [ GET ] }
# Liste des modules actifs en public (consommée au boot du front)
- { path: ^/api/modules, roles: PUBLIC_ACCESS, methods: [ GET ] }
- { path: ^/_mcp, roles: PUBLIC_ACCESS, methods: [ GET ] }
- { path: ^/_mcp, roles: IS_AUTHENTICATED_FULLY }
# Mail : requiert authentification (le check ROLE_USER est dans MailAccessChecker)
+29
View File
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
/*
* Définition de la sidebar (sections + items). Filtrée par SidebarFilter selon les modules actifs.
* Un item porte une clé `module` quand il appartient à un module activable ; sans clé, il est toujours visible.
* Les labels sont des clés i18n (sidebar.<domaine>.<item>).
*/
return [
[
'label' => 'sidebar.general.section',
'icon' => 'mdi:view-dashboard-outline',
'items' => [
['label' => 'sidebar.general.dashboard', 'to' => '/', 'icon' => 'mdi:view-dashboard-outline'],
['label' => 'sidebar.general.myTasks', 'to' => '/my-tasks', 'icon' => 'mdi:checkbox-marked-circle-outline'],
['label' => 'sidebar.general.projects', 'to' => '/projects', 'icon' => 'mdi:folder-multiple-outline'],
['label' => 'sidebar.general.timeTracking', 'to' => '/time-tracking', 'icon' => 'mdi:clock-outline'],
],
],
[
'label' => 'sidebar.hr.section',
'icon' => 'mdi:calendar-account-outline',
'items' => [
['label' => 'sidebar.hr.absences', 'to' => '/absences', 'icon' => 'mdi:calendar-remove-outline'],
['label' => 'sidebar.hr.teamAbsences', 'to' => '/team-absences', 'icon' => 'mdi:account-group-outline'],
],
],
];
+1 -1
View File
@@ -1,2 +1,2 @@
parameters:
app.version: '0.4.28'
app.version: '0.4.30'
@@ -0,0 +1,438 @@
# Task Notifications Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Recréer un producteur de notifications en notifiant le nouvel assigné d'une tâche et les collaborateurs ajoutés, via un listener Doctrine couvrant tous les chemins d'écriture.
**Architecture:** Un unique `TaskNotificationListener` Doctrine écoute `onFlush` (collecte les destinataires à partir des changesets d'assignation et des ajouts de collaborateurs) et `postFlush` (persiste les `Notification` puis re-flush). L'acteur courant est lu via `Security`; on ne se notifie jamais soi-même, et sans acteur authentifié aucune notification n'est créée.
**Tech Stack:** PHP 8.4, Symfony 8, Doctrine ORM 3.6, PHPUnit (KernelTestCase).
---
## Référence spec
`docs/superpowers/specs/2026-06-15-task-notifications-design.md`
## File Structure
- **Create** `src/EventListener/TaskNotificationListener.php` — listener Doctrine, seul producteur de notifications de tâche. Responsabilité unique : traduire les changements d'assignation/collaboration en entités `Notification`.
- **Create** `tests/Functional/EventListener/TaskNotificationListenerTest.php` — tests fonctionnels (KernelTestCase) couvrant tous les cas de la spec.
- Aucune migration, aucun changement d'entité, aucun changement frontend.
### Détails de plateforme vérifiés
- Doctrine ORM 3.6 : le mapping d'une `PersistentCollection` s'obtient via `$collection->getMapping()->fieldName` (objet `AssociationMapping`, **pas** un tableau).
- `Task` non-nullables : `number` (int), `title` (string), `project` (relation). `assignee` est nullable, `collaborators` est une `Collection`.
- En test, on réutilise un `Project` existant (chargé par les fixtures) et on crée des `User` frais (isolation par `uniqid`).
- L'acteur courant : `Security::getUser()` lit le token storage. En test, on pose un token via `TokenStorageInterface::setToken()`.
---
## Task 1: Listener + notifications d'assignation
**Files:**
- Create: `src/EventListener/TaskNotificationListener.php`
- Test: `tests/Functional/EventListener/TaskNotificationListenerTest.php`
- [ ] **Step 1: Écrire les tests d'assignation (échouent)**
Créer `tests/Functional/EventListener/TaskNotificationListenerTest.php` :
```php
<?php
declare(strict_types=1);
namespace App\Tests\Functional\EventListener;
use App\Entity\Notification;
use App\Entity\Project;
use App\Entity\Task;
use App\Entity\User;
use App\Repository\NotificationRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
/**
* @internal
*/
class TaskNotificationListenerTest extends KernelTestCase
{
private EntityManagerInterface $em;
private NotificationRepository $notifications;
private TokenStorageInterface $tokenStorage;
private Project $project;
private User $actor;
private User $alice;
private User $bob;
protected function setUp(): void
{
self::bootKernel();
$c = self::getContainer();
$this->em = $c->get(EntityManagerInterface::class);
$this->notifications = $c->get(NotificationRepository::class);
$this->tokenStorage = $c->get(TokenStorageInterface::class);
$project = $this->em->getRepository(Project::class)->findOneBy([]);
self::assertNotNull($project, 'Les fixtures doivent fournir au moins un projet.');
$this->project = $project;
$this->actor = $this->makeUser('actor');
$this->alice = $this->makeUser('alice');
$this->bob = $this->makeUser('bob');
$this->em->flush();
}
public function testAssignmentToOtherUserCreatesNotification(): void
{
$this->loginAs($this->actor);
$task = $this->makeTask();
$task->setAssignee($this->alice);
$this->em->persist($task);
$this->em->flush();
$rows = $this->notifications->findBy(['user' => $this->alice]);
self::assertCount(1, $rows);
self::assertSame('task_assigned', $rows[0]->getType());
self::assertStringContainsString((string) $task->getTitle(), (string) $rows[0]->getMessage());
}
public function testSelfAssignmentCreatesNoNotification(): void
{
$this->loginAs($this->actor);
$task = $this->makeTask();
$task->setAssignee($this->actor);
$this->em->persist($task);
$this->em->flush();
self::assertCount(0, $this->notifications->findBy(['user' => $this->actor]));
}
public function testReassignmentNotifiesOnlyNewAssignee(): void
{
$this->loginAs($this->actor);
$task = $this->makeTask();
$task->setAssignee($this->alice);
$this->em->persist($task);
$this->em->flush();
$task->setAssignee($this->bob);
$this->em->flush();
self::assertCount(1, $this->notifications->findBy(['user' => $this->alice]));
self::assertCount(1, $this->notifications->findBy(['user' => $this->bob]));
}
public function testAssigneeSetToNullCreatesNoNotificationForNull(): void
{
$this->loginAs($this->actor);
$task = $this->makeTask();
$task->setAssignee($this->alice);
$this->em->persist($task);
$this->em->flush();
$task->setAssignee(null);
$this->em->flush();
// alice a reçu la 1re notif, mais le passage à null n'en crée aucune autre.
self::assertCount(1, $this->notifications->findBy(['user' => $this->alice]));
}
public function testNoActorCreatesNoNotification(): void
{
$this->tokenStorage->setToken(null);
$task = $this->makeTask();
$task->setAssignee($this->alice);
$this->em->persist($task);
$this->em->flush();
self::assertCount(0, $this->notifications->findBy(['user' => $this->alice]));
}
private function makeUser(string $prefix): User
{
$user = new User();
$user->setUsername($prefix.'-'.uniqid());
$user->setPassword('x');
$user->setRoles(['ROLE_USER']);
$this->em->persist($user);
return $user;
}
private function makeTask(): Task
{
$task = new Task();
$task->setNumber(random_int(100000, 999999));
$task->setTitle('Tâche de test '.uniqid());
$task->setProject($this->project);
return $task;
}
private function loginAs(User $user): void
{
$this->tokenStorage->setToken(
new UsernamePasswordToken($user, 'main', $user->getRoles()),
);
}
}
```
- [ ] **Step 2: Lancer les tests pour vérifier qu'ils échouent**
Run: `docker exec php-lesstime-fpm php bin/phpunit tests/Functional/EventListener/TaskNotificationListenerTest.php`
Expected: FAIL — aucune `Notification` créée (le listener n'existe pas encore), `assertCount(1, ...)` échoue.
- [ ] **Step 3: Créer le listener**
Créer `src/EventListener/TaskNotificationListener.php` :
```php
<?php
declare(strict_types=1);
namespace App\EventListener;
use App\Entity\Notification;
use App\Entity\Task;
use App\Entity\User;
use DateTimeImmutable;
use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener;
use Doctrine\ORM\Event\OnFlushEventArgs;
use Doctrine\ORM\Event\PostFlushEventArgs;
use Doctrine\ORM\Events;
use Symfony\Bundle\SecurityBundle\Security;
#[AsDoctrineListener(event: Events::onFlush)]
#[AsDoctrineListener(event: Events::postFlush)]
final class TaskNotificationListener
{
/** @var list<array{user: User, type: string, task: Task}> */
private array $pending = [];
public function __construct(private readonly Security $security)
{
}
public function onFlush(OnFlushEventArgs $args): void
{
$actor = $this->security->getUser();
if (!$actor instanceof User) {
return;
}
$uow = $args->getObjectManager()->getUnitOfWork();
// Assignation sur une tâche nouvellement créée.
foreach ($uow->getScheduledEntityInsertions() as $entity) {
if (!$entity instanceof Task) {
continue;
}
$assignee = $entity->getAssignee();
if ($assignee instanceof User && $assignee !== $actor) {
$this->pending[] = ['user' => $assignee, 'type' => 'task_assigned', 'task' => $entity];
}
}
// Changement d'assignation sur une tâche existante.
foreach ($uow->getScheduledEntityUpdates() as $entity) {
if (!$entity instanceof Task) {
continue;
}
$changeSet = $uow->getEntityChangeSet($entity);
if (!isset($changeSet['assignee'])) {
continue;
}
$new = $changeSet['assignee'][1];
if ($new instanceof User && $new !== $actor) {
$this->pending[] = ['user' => $new, 'type' => 'task_assigned', 'task' => $entity];
}
}
}
public function postFlush(PostFlushEventArgs $args): void
{
if ([] === $this->pending) {
return;
}
$pending = $this->pending;
$this->pending = [];
$em = $args->getObjectManager();
foreach ($pending as $item) {
$em->persist($this->buildNotification($item['user'], $item['type'], $item['task']));
}
$em->flush();
}
private function buildNotification(User $user, string $type, Task $task): Notification
{
[$title, $message] = $this->render($type, $task);
$notification = new Notification();
$notification->setUser($user);
$notification->setType($type);
$notification->setTitle($title);
$notification->setMessage($message);
$notification->setCreatedAt(new DateTimeImmutable());
return $notification;
}
/**
* @return array{0: string, 1: string}
*/
private function render(string $type, Task $task): array
{
$projectName = $task->getProject()?->getName() ?? '';
$suffix = '' !== $projectName ? sprintf(' — %s', $projectName) : '';
$context = sprintf('« %s »%s', (string) $task->getTitle(), $suffix);
return match ($type) {
'task_assigned' => ['Nouvelle tâche assignée', $context],
'task_collaborator_added' => ['Ajout à une tâche', $context],
default => ['Notification', $context],
};
}
}
```
- [ ] **Step 4: Lancer les tests pour vérifier qu'ils passent**
Run: `docker exec php-lesstime-fpm php bin/phpunit tests/Functional/EventListener/TaskNotificationListenerTest.php`
Expected: PASS (5 tests).
- [ ] **Step 5: Commit**
```bash
git add src/EventListener/TaskNotificationListener.php tests/Functional/EventListener/TaskNotificationListenerTest.php
git commit -m "feat(notification) : notifier le nouvel assigné d'une tâche"
```
---
## Task 2: Notifications d'ajout de collaborateur
**Files:**
- Modify: `src/EventListener/TaskNotificationListener.php` (méthode `onFlush`)
- Test: `tests/Functional/EventListener/TaskNotificationListenerTest.php` (ajout de tests)
- [ ] **Step 1: Ajouter les tests collaborateurs (échouent)**
Ajouter ces deux méthodes dans `TaskNotificationListenerTest` :
```php
public function testAddingCollaboratorCreatesNotification(): void
{
$this->loginAs($this->actor);
$task = $this->makeTask();
$this->em->persist($task);
$this->em->flush();
$task->addCollaborator($this->alice);
$this->em->flush();
$rows = $this->notifications->findBy(['user' => $this->alice]);
self::assertCount(1, $rows);
self::assertSame('task_collaborator_added', $rows[0]->getType());
}
public function testAddingSelfAsCollaboratorCreatesNoNotification(): void
{
$this->loginAs($this->actor);
$task = $this->makeTask();
$this->em->persist($task);
$this->em->flush();
$task->addCollaborator($this->actor);
$this->em->flush();
self::assertCount(0, $this->notifications->findBy(['user' => $this->actor]));
}
```
- [ ] **Step 2: Lancer les nouveaux tests pour vérifier qu'ils échouent**
Run: `docker exec php-lesstime-fpm php bin/phpunit tests/Functional/EventListener/TaskNotificationListenerTest.php --filter Collaborator`
Expected: FAIL — `testAddingCollaboratorCreatesNotification` échoue (aucune notification créée).
- [ ] **Step 3: Étendre `onFlush` pour gérer les collaborateurs**
Dans `src/EventListener/TaskNotificationListener.php`, ajouter ce bloc à la fin de `onFlush()`, juste avant la fin de méthode (après la boucle `getScheduledEntityUpdates`) :
```php
// Ajout de collaborateur(s) (tâche nouvelle ou existante).
foreach ($uow->getScheduledCollectionUpdates() as $collection) {
$owner = $collection->getOwner();
if (!$owner instanceof Task) {
continue;
}
if ('collaborators' !== $collection->getMapping()->fieldName) {
continue;
}
foreach ($collection->getInsertDiff() as $user) {
if ($user instanceof User && $user !== $actor) {
$this->pending[] = ['user' => $user, 'type' => 'task_collaborator_added', 'task' => $owner];
}
}
}
```
- [ ] **Step 4: Lancer toute la classe de tests pour vérifier qu'elle passe**
Run: `docker exec php-lesstime-fpm php bin/phpunit tests/Functional/EventListener/TaskNotificationListenerTest.php`
Expected: PASS (7 tests).
- [ ] **Step 5: Commit**
```bash
git add src/EventListener/TaskNotificationListener.php tests/Functional/EventListener/TaskNotificationListenerTest.php
git commit -m "feat(notification) : notifier les collaborateurs ajoutés à une tâche"
```
---
## Task 3: Vérification globale & style
**Files:** aucun nouveau fichier.
- [ ] **Step 1: Lancer la suite de tests complète**
Run: `make test`
Expected: PASS (aucune régression).
- [ ] **Step 2: Corriger le style PHP**
Run: `make php-cs-fixer-allow-risky`
Expected: les nouveaux fichiers sont conformes (strict types, ordre des imports).
- [ ] **Step 3: Commit si php-cs-fixer a modifié des fichiers**
```bash
git add -A
git commit -m "style(notification) : php-cs-fixer sur le listener de notifications"
```
(Sauter cette étape si php-cs-fixer n'a rien changé.)
---
## Self-review (auteur du plan)
- **Couverture spec :** assignation (création + update) ✔ Task 1 ; collaborateur ajouté ✔ Task 2 ; auto-exclusion ✔ (tests self) ; pas d'acteur → rien ✔ ; réassignation A→B ✔ ; `assignee=null` ✔ ; contenu réutilisant l'entité existante ✔ ; aucun changement front ✔.
- **Placeholders :** aucun — tout le code (listener + tests) est complet.
- **Cohérence des types :** `pending` typé `list<array{user,type,task}>` ; types `task_assigned` / `task_collaborator_added` identiques entre listener et tests ; `getMapping()->fieldName` (ORM 3) ; `addCollaborator()` confirmé sur l'entité Task.
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,126 @@
# Notifications sur événements de tâche — Design
**Date :** 2026-06-15
**Ticket lié :** (à créer) — recâblage du système de notifications
## Contexte & problème
Le système de notifications de Lesstime est aujourd'hui une **coquille vide** : toute la
plomberie consommatrice existe encore (entité `Notification`, `NotificationProvider`,
`NotificationRepository`, `NotificationUnreadCountController`, `MarkAllReadController`,
et côté front `NotificationBell.vue` + `useNotifications.ts` + `services/notifications.ts`
qui poll toutes les 2 min), **mais plus aucun producteur ne crée de notification**.
Cause : le seul producteur était `NotificationService`, déclenché par les `ClientTicket`
du portail client. Le commit `2a0b202` (« suppression du portail client ») a retiré
`ClientTicket`, `NotificationService` et les processors associés, laissant la cloche
interroger `/notifications/unread-count` dans le vide. Le compteur reste donc à 0 et le
dropdown est toujours vide.
> Le travail récent LST-52 (pagination du `NotificationProvider`) est correct mais portait
> sur une liste structurellement toujours vide.
## Objectif
Rebrancher la **création** de notifications sur des événements **réels** qui existent
encore dans l'app : les événements de **tâche**.
## Périmètre (MVP)
### Déclencheurs & destinataires
| Événement | Détection (changeset Doctrine) | Destinataire | Type |
|-----------|-------------------------------|--------------|------|
| Tâche assignée (création **ou** modif où `assignee` passe à un nouvel user) | `assignee` : `old ≠ new` et `new ≠ null` | le nouvel assigné | `task_assigned` |
| Collaborateur ajouté | `insertDiff` sur la collection `collaborators` | chaque user ajouté | `task_collaborator_added` |
Règles :
- **Auto-exclusion** : si le destinataire == l'acteur courant, aucune notification.
- Réassignation A→B : seul **B** est notifié (pas de notification « désassigné » — hors scope).
- `assignee` passe à `null` : aucune notification.
- Si plusieurs personnes deviennent destinataires dans un même flush, chacune reçoit
sa notification.
### Contenu des notifications
Réutilise l'entité `Notification` existante (`user`, `type`, `title`, `message`,
`isRead`, `createdAt`) — **aucune migration**.
- `task_assigned` → titre « Nouvelle tâche assignée », message `«{titre tâche}» — {nom projet}`.
- `task_collaborator_added` → titre « Ajout à une tâche », message `«{titre tâche}» — {nom projet}`.
### Décisions de comportement
1. **Pas d'acteur authentifié → pas de notification.** Les deux chemins utilisateurs réels
(frontend JWT, MCP token) ont toujours un user authentifié. CLI / fixtures / cron de
récurrence n'ont pas d'acteur → aucune notification. Effet de bord positif : `make fixtures`
ne génère pas de notifications parasites.
2. **Pas de lien cliquable** vers la tâche dans cette itération (l'entité `Notification`
n'a pas de champ URL ; la cloche affiche titre + message + date relative). Extension
future possible, hors scope MVP.
## Architecture
**Approche retenue : listener Doctrine `onFlush` / `postFlush`** (un seul point de vérité
qui couvre tous les chemins d'écriture — frontend API Platform, MCP, et tout futur chemin —
puisque tous persistent via `EntityManager::flush()`).
Approches écartées :
- *Décorateur de processor API Platform + hooks dans les tools MCP* : logique dupliquée sur
plusieurs endroits, risque d'oublier un chemin (c'est exactement ce type d'oubli qui a créé
le bug initial).
- *Événements de domaine + Symfony Messenger async* : surdimensionné pour 2 événements,
ajoute transport + worker (YAGNI).
### Composant : `App\EventListener\TaskNotificationListener`
Enregistré via `#[AsDoctrineListener]` sur les événements `onFlush` et `postFlush`.
Dépendances injectées : `Symfony\Bundle\SecurityBundle\Security` (acteur courant).
**`onFlush(OnFlushEventArgs $args)`** — collecte (ne persiste rien encore) :
1. `$uow = $em->getUnitOfWork();`
2. Acteur : `$actor = $this->security->getUser();` → si `null`, **on sort** (aucune notif).
3. Assignations :
- `getScheduledEntityInsertions()` : pour chaque `Task` insérée avec `assignee !== null`
et `assignee !== actor` → file `(assignee, 'task_assigned', task)`.
- `getScheduledEntityUpdates()` : pour chaque `Task`, `getEntityChangeSet($task)` ;
si `isset($cs['assignee'])` avec `[$old, $new] = $cs['assignee']`, `$new !== null`
et `$new !== actor` → file `(new, 'task_assigned', task)`.
4. Collaborateurs :
- `getScheduledCollectionUpdates()` : pour chaque `PersistentCollection` dont l'owner est
une `Task` et le champ vaut `collaborators`, `getInsertDiff()` donne les users ajoutés ;
pour chacun `!== actor` → file `(user, 'task_collaborator_added', task)`.
5. Stocke la file dans une propriété privée du listener.
**`postFlush(PostFlushEventArgs $args)`** — persiste :
1. Si la file est vide, retour immédiat.
2. Vide la file dans une variable locale puis **réinitialise la propriété** (anti-réentrance).
3. Pour chaque entrée, crée une `Notification` (user, type, title, message, createdAt),
`persist`.
4. `$em->flush()` une seconde fois. Pas de boucle infinie : les `Notification` ne sont pas
des `Task`, donc ce second flush ne reschedule aucune assignation/collaboration.
## Tests (PHPUnit, `make test`)
Cas couverts :
- Assignation d'une tâche à un user (par un autre acteur) → 1 notification `task_assigned`
pour cet user.
- Auto-assignation (acteur s'assigne la tâche) → **aucune** notification.
- Ajout d'un collaborateur → 1 notification `task_collaborator_added` pour cet user.
- Réassignation A→B → seul **B** reçoit une notification.
- `assignee` passé à `null` → aucune notification.
- Pas d'acteur authentifié (contexte CLI) → aucune notification.
## Hors périmètre
- Notifications de changement de statut, d'échéance proche, de désassignation.
- Lien cliquable / navigation vers la tâche depuis la notification.
- Préférences utilisateur (opt-in/opt-out par type), notifications e-mail.
- Modification du front (la cloche consomme déjà l'API et s'affichera dès que des
notifications existent).
## Fichiers impactés
- **Nouveau** : `src/EventListener/TaskNotificationListener.php`
- **Nouveau** : tests PHPUnit (`tests/EventListener/` ou emplacement équivalent au projet).
- **Aucune** migration, **aucun** changement d'entité, **aucun** changement front.
@@ -0,0 +1,192 @@
# LST-56 — Socle modular monolith DDD + pilote « Projets/Tâches »
> Ticket Lesstime **#56** (1/5 — groupe « Refonte / Alignement Starseed »).
> Design validé le 2026-06-19. Référence vivante : repo **Starseed** (`.claude/rules/*.md` + implémentation réelle), et `Starseed/doc/architecture-modulaire-malio.md` (vision cible théorique — **non contraignante** là où elle diverge du code réel).
## 1. Objectif & contraintes
Poser dans Lesstime l'**infrastructure d'un modular monolith DDD** calquée sur Starseed, et **migrer un premier module pilote** (Projets/Tâches) de bout en bout comme preuve que la mécanique tient sur le cœur métier.
Contraintes **non négociables** :
- **Ne rien casser de l'existant.** Migration **strangler progressive** : le code legacy (`src/Entity/…`) et les modules (`src/Module/…`) coexistent ; l'application reste fonctionnelle et `make test` vert à **chaque** étape.
- **Prod = Docker, BDD peuplée** → uniquement des migrations **additives et nullable** (aucun `DROP`, aucun `NOT NULL` rétroactif, aucun déplacement de données).
- **Profondeur DDD : pragmatique**, alignée sur le **Starseed réel** (pas la doc théorique) : ORM attributs conservés dans les entités Domain, Repository = interface (Domain) + impl Doctrine (Infrastructure), Provider/Processor API Platform, contrats `Shared/Domain/Contract` pour le cross-module. **Pas de CQRS bus systématique, pas de multi-tenant.**
### Décisions de cadrage (figées)
| Sujet | Décision |
|-------|----------|
| Périmètre #56 | Socle complet + **1 module pilote** migré de bout en bout |
| Stratégie | **Strangler progressif** (legacy + modules en parallèle) |
| Profondeur DDD | **Pragmatique** (= Starseed réel) |
| Module pilote | **Projets/Tâches** (cœur métier) |
| Dépendances du pilote (User/Client/Notification) | Restent **legacy**, câblées via **contrats `Shared/Domain/Contract`** + `resolve_target_entities` |
| Infra d'audit Starseed | **Différée** → ticket Lesstime dédié (créé séparément) |
| Périmètre front #56 | **Câblage shell/shared/middlewares + migration du pilote en layer**, sans relooking (le relooking Malio reste #60) |
| Exposition API du pilote | **Garder les `#[ApiResource]` actuels** (étendre seulement les chemins de scan) — zéro régression API |
| Tâche → Notification | **Contrat `NotifierInterface`** (impl legacy crée la `Notification`) |
| Nom/ID du module | back `ProjectManagement` / front `project-management` / ID `project_management` |
## 2. Garde-fous Starseed retenus pour #56
Repris : `declare(strict_types=1)`, `src/Module/<X>/{Domain,Application,Infrastructure}`, `Shared/Domain/Contract` + `resolve_target_entities` (zéro import inter-modules), `config/modules.php` + `config/sidebar.php`, endpoints `/api/modules` + `/api/sidebar` + `/api/version`, `TimestampableBlamableTrait` + subscriber, pagination obligatoire, `COMMENT ON COLUMN` (helper `ColumnCommentsCatalog`), front layers auto-détectés + `useSidebar`/`useModules` + `auth.global.ts`/`modules.global.ts`.
Reportés (hors #56) : **infra d'audit** (`#[Auditable]`/`#[AuditIgnore]`, table `audit_log`, listener, resource) → ticket dédié. **RBAC fin** (`module.resource.action`) → #57 ; en #56 la sidebar filtre **par module actif** (au plus un gate `ROLE_ADMIN`).
## 3. Backend — arborescence cible
```
src/Shared/
├── Domain/
│ ├── Contract/ UserInterface, UserResolverInterface, ClientInterface, NotifierInterface
│ ├── Event/ DomainEventInterface
│ └── Trait/ TimestampableBlamableTrait
├── Infrastructure/
│ ├── Doctrine/ TimestampableBlamableSubscriber
│ ├── Database/ ColumnCommentsCatalog (helper COMMENT ON COLUMN + 4 colonnes std)
│ └── ApiPlatform/
│ ├── Resource/ ModulesResource, SidebarResource
│ └── State/ ModulesProvider, SidebarProvider
src/Module/ProjectManagement/
├── ProjectManagementModule.php ID='project_management', LABEL='Projets', REQUIRED=false, permissions()=[] (stub, RBAC réel #57)
├── Domain/
│ ├── Entity/ Project, Task, Workflow, TaskStatus, TaskGroup, TaskEffort,
│ │ TaskPriority, TaskTag, TaskRecurrence, TaskDocument
│ └── Repository/ *RepositoryInterface (une interface par agrégat consommé)
├── Application/ RecurrenceCalculator/RecurrenceHandler + services task-centric déplacés
└── Infrastructure/
├── Doctrine/ Doctrine*Repository + Migrations/ (additif Timestampable)
├── ApiPlatform/ State/Provider + State/Processor déplacés (TaskNumber, TaskCalendar,
│ TaskDocument*, SwitchProjectWorkflow, WorkflowDelete, ActiveTimeEntry resté legacy…)
└── Mcp/Tool/ MCP tools Project/, Task/, TaskMeta/, Workflow/ déplacés
```
`src/Entity/` conserve **intacts** : `User`, `Client`, `Notification`, `TimeEntry`, `AbsenceRequest`/`AbsencePolicy`/`AbsenceBalance`, `Mail*`, `Gitea*`/`BookStack*`/`Zimbra*`/`Share*Configuration`. Ces domaines seront modularisés dans des tickets ultérieurs.
> **Note de découpage** : `TimeEntry` reste legacy en #56 (domaine Time tracking séparé). Le lien `Task ↔ TimeEntry` est porté côté `TimeEntry` (FK nullable vers la table `task`) ; aucune contrainte ne casse car la table `task` ne change pas de nom.
## 4. Câblage des dépendances (zéro import inter-modules)
1. Interfaces dans `src/Shared/Domain/Contract/` :
- `UserInterface` (id + identifiants nécessaires aux entités du module : assignee, collaborators, createdBy/updatedBy),
- `ClientInterface` (id + nom, pour `Project.client`),
- `UserResolverInterface` (résoudre un user par id, pour les State/MCP du module),
- `NotifierInterface` (créer une notification — impl legacy).
2. Les entités du module **type-hintent les interfaces**, jamais `App\Entity\*`.
3. `config/packages/doctrine.yaml → orm.resolve_target_entities` :
```yaml
resolve_target_entities:
App\Shared\Domain\Contract\UserInterface: App\Entity\User
App\Shared\Domain\Contract\ClientInterface: App\Entity\Client
```
4. `App\Entity\User` `implements UserInterface`, `App\Entity\Client` `implements ClientInterface` (legacy modifié à minima, additif).
5. Notifications : `App\Module\ProjectManagement\…` appelle `NotifierInterface` ; impl `App\…\LegacyNotifier` (wrappe le `NotificationService` actuel). Le `TaskNotificationListener` est déplacé/adapté pour passer par le contrat.
## 5. Config backend (toutes additives)
- **`doctrine.yaml`** — ajouter un mapping module (garder `App → src/Entity`) :
```yaml
mappings:
App: { type: attribute, is_bundle: false, dir: '%kernel.project_dir%/src/Entity', prefix: 'App\Entity', alias: App }
ProjectManagement:
type: attribute
is_bundle: false
dir: '%kernel.project_dir%/src/Module/ProjectManagement/Domain/Entity'
prefix: 'App\Module\ProjectManagement\Domain\Entity'
```
Les entités déplacées **gardent leur `#[ORM\Table(name: '…')]` actuel** (table inchangée → aucune donnée déplacée). `#[ORM\Entity(repositoryClass: DoctrineXxxRepository::class)]` mis à jour vers la nouvelle classe.
- **`doctrine_migrations.yaml`** — ajouter le namespace module (garder `DoctrineMigrations`) :
```yaml
migrations_paths:
DoctrineMigrations: '%kernel.project_dir%/migrations'
'App\Module\ProjectManagement\Infrastructure\Doctrine\Migrations': '%kernel.project_dir%/src/Module/ProjectManagement/Infrastructure/Doctrine/Migrations'
```
> ⚠️ Doctrine Migrations trie par FQCN entre namespaces : le legacy `DoctrineMigrations` (setup initial) passe avant les migrations modulaires sur base vide. Sur la prod déjà migrée, seules les **nouvelles** migrations additives s'appliquent → pas d'impact d'ordre.
- **`api_platform.yaml`** — déclarer les chemins de mapping (entités + resources legacy **et** module) pour que les `#[ApiResource]` du pilote restent découverts :
```yaml
mapping:
paths:
- '%kernel.project_dir%/src/Entity'
- '%kernel.project_dir%/src/ApiResource'
- '%kernel.project_dir%/src/Shared/Infrastructure/ApiPlatform/Resource'
- '%kernel.project_dir%/src/Module/ProjectManagement/Domain/Entity'
```
- **`services.yaml`** — mettre à jour les FQCN explicites déplacés : `App\EventListener\TaskDocumentListener`, `App\State\TaskDocumentProcessor`, `App\Controller\TaskDocumentDownloadController`, `App\Mcp\Tool\Task\AddTaskDocumentTool`, `App\Mcp\Tool\Task\UpdateTaskDocumentTool` → nouveaux namespaces module. Le glob `App\: '../src/'` continue d'autowire les classes déplacées.
## 6. Garde-fous portés dans #56
- **TimestampableBlamable** : trait `Shared/Domain/Trait/TimestampableBlamableTrait` (4 colonnes `created_at`, `updated_at`, `created_by`, `updated_by` — toutes **nullable**), rempli par `TimestampableBlamableSubscriber` (prePersist/preUpdate). Appliqué aux entités du pilote → **1 migration additive** par table concernée, avec `COMMENT ON COLUMN` via `ColumnCommentsCatalog::addStandardTimestampableBlamableComments()`.
- **Pagination** : conserver le standard API Platform actuel (les collections du pilote restent paginées comme aujourd'hui).
- **`COMMENT ON COLUMN`** : appliqué sur les colonnes ajoutées par #56 (pas de rétro-commentaire forcé sur le legacy).
## 7. Endpoints modules / sidebar / version
- `GET /api/modules` (public) — `ModulesResource` + `ModulesProvider` lisant `config/modules.php` (renvoie `{ modules: ["project_management", …] }`).
- `GET /api/sidebar` (auth) — `SidebarResource` + `SidebarProvider` lisant `config/sidebar.php` ; filtrage **par module actif** (item `module` absent de la liste active → masqué + route ajoutée à `disabledRoutes`) ; gate de section optionnel `ROLE_ADMIN`. Le filtrage par **permissions fines** est explicitement reporté à #57.
- `GET /api/version` — **déjà présent** (`AppVersion`) ; vérifier le format `{ version }`, ré-aligner si besoin (déplacement optionnel vers `Shared/`).
- `config/modules.php` : `return [ ProjectManagementModule::class ];` (Core viendra plus tard ; pas de module REQUIRED bloquant en #56).
- `config/sidebar.php` : sections « Projets » / « Mes tâches » avec `module => 'project_management'` ; les entrées des domaines encore legacy (Time tracking, Absences, Mail, Admin…) listées **sans** clé `module` (donc toujours visibles) pour ne rien masquer.
## 8. Frontend — câblage + pilote en layer (sans relooking)
```
frontend/app/
├── layouts/default.vue shell : sidebar (depuis /api/sidebar) + main
├── middleware/auth.global.ts protège routes, charge sidebar+modules après login
└── middleware/modules.global.ts redirige si route ∈ disabledRoutes
frontend/shared/
├── composables/ useApi (déplacé), useSidebar, useModules, + existants réutilisés
├── stores/ auth, ui, timer (timer reste partagé : Time tracking encore legacy)
├── utils/ api.ts (extractHydraMembers/fetchAllHydra), …
└── types/
frontend/modules/project-management/
├── nuxt.config.ts defineNuxtConfig({})
├── pages/ my-tasks.vue, projects/index.vue, projects/[id]/* (déplacés tels quels)
├── components/ task/*, project/* (déplacés)
├── services/ tasks.ts, projects.ts, task-*.ts, workflows.ts (déplacés)
└── stores/ (si spécifiques au domaine)
```
- **`nuxt.config.ts`** : auto-détection des layers `modules/*/` (scan `readdirSync` comme Starseed) ajoutés à `extends`, + dirs d'auto-import des composables/stores par layer. `extends: ['@malio/layer-ui']` conservé en tête.
- **`useSidebar`/`useModules`** : état singleton, `loadSidebar()`/`loadModules()` appelés dans `auth.global.ts`, `reset*()` au logout.
- **`modules.global.ts`** : `isRouteDisabled(to.path)` → `navigateTo('/')`.
- **Migration des pages** : déplacement **sans réécriture visuelle** ; les pages des autres domaines (time-tracking, absences, mail, admin, profile…) **restent dans `frontend/pages/`** (legacy) tant que leurs modules ne sont pas migrés. Nuxt fusionne les routes du shell + des layers → cohabitation transparente.
> Point de vigilance front : vérifier que la cohabitation `frontend/pages/` (legacy) + `frontend/modules/*/pages/` (layer) ne crée pas de collision de routes ; `my-tasks`/`projects` sont déplacés **et retirés** de `frontend/pages/` pour éviter le doublon.
## 9. Plan strangler (ordre d'exécution — app verte à chaque palier)
1. **Shared/ + garde-fous** : trait, subscriber, `ColumnCommentsCatalog`. Neutre (rien ne les consomme encore).
2. **Endpoints modules/sidebar** + `config/modules.php` + `config/sidebar.php` (toutes entrées legacy sans `module` → rien masqué). Additif.
3. **Contrats `Shared/Domain/Contract`** + `resolve_target_entities` + `User`/`Client` `implements …Interface`. Neutre.
4. **Déplacement back du module** ProjectManagement (entités → Domain/Entity, repos → Infra/Doctrine + interfaces Domain, State, MCP) + mises à jour `doctrine.yaml`/`api_platform.yaml`/`doctrine_migrations.yaml`/`services.yaml`. **`make test` vert.**
5. **Migration additive Timestampable** sur les tables du pilote (+ `COMMENT ON COLUMN`).
6. **Front shell** : `app/` + `shared/` + middlewares + auto-détection `nuxt.config.ts`. App encore en pages plates.
7. **Déplacement front du pilote** vers `modules/project-management/` (pages/components/services), retrait des doublons de `frontend/pages/`.
8. **Vérification bout-en-bout** : commenter `ProjectManagementModule::class` dans `config/modules.php` → `/api/modules` ne le liste plus, `/api/sidebar` masque ses entrées + peuple `disabledRoutes`, le front redirige `/my-tasks`→`/`. Décommenter → tout revient. Documenter le test.
## 10. Critères d'acceptation (repris du ticket, raffinés)
- [ ] `src/Shared/` + `src/Module/ProjectManagement/{Domain,Application,Infrastructure}` en place.
- [ ] `/api/modules`, `/api/sidebar` fonctionnels ; `/api/version` aligné.
- [ ] Aucun import direct `App\Entity\User`/`Client` depuis le module (contrats + `resolve_target_entities`).
- [ ] Front : layers `frontend/modules/*/` auto-détectés ; `useSidebar`/`useModules` + `auth.global.ts`/`modules.global.ts` opérationnels ; pilote migré sans régression visuelle.
- [ ] Garde-fous : TimestampableBlamable (migration additive + `COMMENT ON COLUMN`) ; pagination conservée. **Audit explicitement hors périmètre** (ticket dédié).
- [ ] `make test` vert ; activation/désactivation du module validée de bout en bout.
- [ ] Aucune migration destructive ; prod déployable sans perte.
## 11. Risques & points de vigilance
- **Prod peuplée** : seules migrations additives nullable. `created_by`/`updated_by` non backfillés (historique) — conforme Starseed.
- **Changement de namespace des entités** : sans impact DB (Doctrine mappe par table). Vérifier qu'aucun code legacy ne référence en dur `App\Entity\Task` etc. → grep + remplacement (le pilote tire Task/Project, consommés par TimeEntry/Mail/BookStack links restés legacy : ces liens passeront par les contrats ou un type-hint relâché).
- **Collision de routes front** legacy vs layer (cf. §8).
- **MCP tools** (spécificité Lesstime) : déplacés sous `Module/*/Infrastructure/Mcp/` ; confirmer que `McpSchemaGeneratorPass` les redécouvre (scan `src/`).
- **`auto_mapping: true`** : valider que l'ajout d'un mapping explicite ne perturbe pas la résolution (sinon désactiver `auto_mapping` et lister explicitement).
## 12. Suite
- Ticket **audit** dédié à créer (infra `#[Auditable]` + `audit_log` + listener + resource), prérequis souple de #57.
- #57 RBAC fin (permissions `module.resource.action`, sidebar filtrée par permission).
- #58 Répertoire (Clients/Prospects), #59 Reporting, #60 Refonte front Malio.
@@ -0,0 +1,161 @@
# Roadmap — Migration Lesstime → modular monolith DDD (archi Starseed)
> Plan de migration **complet** validé le 2026-06-19. Référence architecture : repo **Starseed**
> (`.claude/rules/*.md` + implémentation réelle). Détail technique du socle : voir
> `2026-06-19-lst-56-modular-monolith-design.md`.
## Principes directeurs
- **Strangler progressif** : legacy (`src/Entity/…`) et modules (`src/Module/…`) coexistent ; l'app
reste fonctionnelle et `make test` vert à **chaque** merge. Aucune migration destructive (prod Docker, BDD peuplée → migrations **additives nullable** uniquement).
- **DDD pragmatique** (= Starseed réel) : ORM attrs dans l'entité Domain, Repository interface (Domain)
+ impl Doctrine (Infra), Provider/Processor API Platform, contrats `Shared/Domain/Contract` pour le
cross-module. **Pas de CQRS bus, pas de multi-tenant.**
- **Tranches verticales** : chaque module de Phase 2 est livré **back + front (layer Malio) + MCP**
d'un coup → fonctionnel de bout en bout à son merge. L'ancienne idée d'un « ticket refonte front »
global est dissoute : chaque module arrive déjà en Malio ; un ticket de finition harmonise à la fin.
- **Ordre par dépendances** : socle → Core (identité/RBAC/audit) → modules métier → transverse/finition.
- **Zéro import inter-modules** : interfaces `Shared/Domain/Contract` + `resolve_target_entities`,
ou domain events / contrat `NotifierInterface`.
## Garde-fous Starseed (appliqués à chaque entité migrée)
`declare(strict_types=1)` · `TimestampableBlamableTrait` (4 colonnes nullable) + subscriber ·
pagination obligatoire · `COMMENT ON COLUMN` (helper `ColumnCommentsCatalog`) ·
`#[Auditable]`/`#[AuditIgnore]` (dès que 1.3 est livré) · front `Malio*` + `usePaginatedList` +
`useFormErrors` · RBAC `module.resource.action` (dès 1.2).
---
## Phase 0 — Socle (fondations, ne touche aucun métier)
### 0.1 · Socle back — infrastructure modulaire *(réécrit depuis #56)*
**Dépend de** : —
`src/Shared/Domain/Contract/` (UserInterface, UserResolverInterface, ClientInterface, NotifierInterface),
`Shared/Domain/Event/DomainEventInterface`, `Shared/Domain/Trait/TimestampableBlamableTrait`,
`Shared/Infrastructure/Doctrine/TimestampableBlamableSubscriber`,
`Shared/Infrastructure/Database/ColumnCommentsCatalog`,
`Shared/Infrastructure/ApiPlatform/{Resource,State}` (`ModulesResource`/`ModulesProvider`,
`SidebarResource`/`SidebarProvider`), `config/modules.php`, `config/sidebar.php`, `/api/version` aligné.
Config additive : mapping Doctrine module prêt, `migrations_paths` modulaire, `api_platform.mapping.paths`.
**AC** : `/api/modules` + `/api/sidebar` répondent ; app verte ; aucune migration destructive.
### 0.2 · Socle front — shell + auto-détection des layers
**Dépend de** : 0.1
`frontend/app/` (shell `layouts/default.vue`), `frontend/shared/` (`useApi` déplacé, `useSidebar`,
`useModules`, stores), middlewares `auth.global.ts` + `modules.global.ts`, auto-détection des layers
`modules/*/` dans `nuxt.config.ts`. **Aucune page métier déplacée** (app encore plate).
**AC** : sidebar dynamique depuis `/api/sidebar` ; routes désactivées redirigées ; app verte.
---
## Phase 1 — Module Core (identité, sécurité, traçabilité — transverse)
### 1.1 · Core — Identité & Notifications
**Dépend de** : 0.1, 0.2
Migrer `User` + Auth/JWT dans `src/Module/Core/` (Domain/Entity, Repository interface + Doctrine impl,
`MeProvider`, password hasher), `User implements UserInterface`, `resolve_target_entities → Core\User`.
`Notification` exposée via `NotifierInterface`. `CoreModule.php` (**REQUIRED=true**). Front : layer
`modules/core/` (login, profile, admin users).
**AC** : login/JWT OK ; app verte ; aucun import direct `App\Entity\User` hors Core.
### 1.2 · RBAC fin *(réécrit depuis #57)*
**Dépend de** : 1.1
`Role`/`Permission`, `permissions()` par module, commande `app:sync-permissions`, `PermissionVoter`,
`SidebarProvider` filtrant **par permission** (en plus du module actif), seed RBAC. Front : gestion des
rôles + `usePermissions`.
**AC** : permissions `module.resource.action` ; sidebar gated par permission.
### 1.3 · Audit log *(réécrit depuis #61)*
**Dépend de** : 1.1
`#[Auditable]`/`#[AuditIgnore]` (`Shared/Domain/Attribute`), table `audit_log` (migration additive +
`COMMENT ON COLUMN`), `AuditListener`/`AuditLogWriter`/`RequestIdProvider`, `AuditLogResource` +
`/api/audit-logs` paginé/filtrable, page front + labels i18n `audit.entity.*`.
**AC** : CRUD des entités `#[Auditable]` tracé ; endpoint paginé ; aucune migration destructive.
---
## Phase 2 — Modules métier (tranches verticales back + front + MCP, strangler)
### 2.1 · Module TimeTracking *(premier module — rodage)*
**Dépend de** : 1.1
Migrer `TimeEntry``src/Module/TimeTracking/` (Domain/Entity, repo, `ActiveTimeEntryProvider`,
`TimeEntryExportService`/controller, MCP TimeEntry tools), front layer `modules/time-tracking/`
(`time-tracking.vue`, components, services, store `timer`). Timestampable additif. **Rode toute la
mécanique modulaire à risque quasi nul.**
**AC** : time tracking fonctionnel en module ; activation/désactivation testée ; app verte.
### 2.2 · Module ProjectManagement *(cœur métier — réécrit depuis #56 pilote)*
**Dépend de** : 2.1, 1.1
`Project, Task, Workflow, TaskStatus, TaskGroup, TaskEffort, TaskPriority, TaskTag, TaskRecurrence,
TaskDocument``src/Module/ProjectManagement/` (vertical back + MCP Task/Project/TaskMeta/Workflow +
front layer `modules/project-management/`). User/Client via contrats (Client encore legacy jusqu'à 2.4).
Notifications via `NotifierInterface`. `#[ApiResource]` conservés (étendre le scan). Timestampable additif.
**AC** : cœur en module sans régression API ; app verte.
### 2.3 · Module Absence
**Dépend de** : 1.1
`AbsenceRequest/AbsencePolicy/AbsenceBalance` + services (`AbsenceBalanceService`, `AbsenceDayCalculator`,
`PublicHolidayProvider`) + controllers (calendar, preview, justificatif) + MCP absence tools →
`src/Module/Absence/`, front layer `modules/absence/`.
**AC** : module absences complet ; app verte.
### 2.4 · Module Directory — Clients + Prospects *(réécrit depuis #58)*
**Dépend de** : 1.1 (et après 2.2 qui référence Client via contrat)
`Client``src/Module/Directory/` + nouvelle entité `Prospect`. L'impl de `ClientInterface` migre du
legacy vers le module (`resolve_target_entities` mis à jour). Front répertoire (clients + prospects).
**AC** : Clients + Prospects en module ; contrats à jour ; app verte.
### 2.5 · Module Mail
**Dépend de** : 1.1, 2.2 (TaskMailLink → Task)
`Mail*` + `TaskMailLink` + `MailSyncService` + controllers + settings → `src/Module/Mail/`, front layer.
Intègre le WIP `feat/mail-integration`.
**AC** : mail en module ; app verte.
### 2.6 · Module Integration — Gitea / BookStack / Zimbra / Share
**Dépend de** : 1.1, 2.2 (liens Task)
Configs + services API (`GiteaApiService`, `BookStackApiService`, `CalDavService`, Share) + controllers +
liens → `src/Module/Integration/`, front (onglets admin + sections task).
**AC** : intégrations en module ; app verte.
---
## Phase 3 — Transverse & finition
### 3.1 · Module Reporting *(réécrit depuis #59)*
**Dépend de** : Phase 2 (consomme les modules)
Reporting natif transverse (agrège time tracking, tâches, absences) via contrats / API. Module
`src/Module/Reporting/` + front.
**AC** : rapports natifs ; aucune dépendance directe inter-modules.
### 3.2 · Module Portail client
**Dépend de** : 1.1, 2.2, 2.4
Portail client (accès restreint), module `src/Module/ClientPortal/` + front layer + RBAC dédié.
**AC** : portail fonctionnel ; gated RBAC.
### 3.3 · Finition Malio + nettoyage legacy *(réécrit depuis #60)*
**Dépend de** : tout
Harmonisation visuelle Malio finale, **vidage de `src/Entity/` legacy résiduel**, suppression du mapping
Doctrine legacy + des pages plates `frontend/pages/` résiduelles, durcissement `resolve_target_entities`.
**AC** : `src/Entity` vide ; 100 % modulaire ; app verte ; aucune route/legacy orpheline.
---
## Ordre d'exécution recommandé
`0.1 → 0.2 → 1.1 → 1.2 → 1.3 → 2.1 → 2.2 → 2.3 → 2.4 → 2.5 → 2.6 → 3.1 → 3.2 → 3.3`
Les tickets 1.2 et 1.3 peuvent se paralléliser après 1.1. Les modules 2.3 (Absence) et 2.4 (Directory)
peuvent se paralléliser après 2.2. Mail (2.5) et Integration (2.6) suivent 2.2.
## Mapping avec les tickets Lesstime existants
| Ancien | Devient |
|--------|---------|
| #56 (1/5 Aligner archi) | **0.1 Socle back** (le reste éclaté en 0.2 + 2.2) |
| #57 (2/5 RBAC) | **1.2 RBAC fin** |
| #58 (3/5 Répertoire) | **2.4 Directory** |
| #59 (4/5 Reporting) | **3.1 Reporting** |
| #60 (5/5 Front Malio) | **3.3 Finition Malio + nettoyage** (le front se fait par module) |
| #61 (Audit) | **1.3 Audit log** |
| *(créés)* | 0.2, 1.1, 2.1, 2.2, 2.3, 2.5, 2.6, 3.2 |
+1 -1
View File
@@ -73,7 +73,7 @@ COPY --from=frontend-build /app/frontend/.output/public /var/www/html/frontend/.
RUN echo "APP_ENV=prod" > /var/www/html/.env
# Permissions
RUN mkdir -p /var/www/html/var /var/www/html/var/uploads /var/www/html/var/mcp-sessions \
RUN mkdir -p /var/www/html/var /var/www/html/var/log /var/www/html/var/uploads /var/www/html/var/mcp-sessions \
&& chown -R www-data:www-data /var/www/html/var
WORKDIR /var/www/html
+2 -1
View File
@@ -13,6 +13,7 @@ use ApiPlatform\Metadata\Patch;
use ApiPlatform\Metadata\Post;
use App\Enum\ContractType;
use App\Repository\UserRepository;
use App\Shared\Domain\Contract\UserInterface as SharedUserInterface;
use App\State\MeProvider;
use App\State\UserPasswordHasherProcessor;
use DateTimeImmutable;
@@ -44,7 +45,7 @@ use Symfony\Component\Serializer\Attribute\Groups;
)]
#[ORM\Entity(repositoryClass: UserRepository::class)]
#[ORM\Table(name: '`user`')]
class User implements UserInterface, PasswordAuthenticatedUserInterface
class User implements UserInterface, PasswordAuthenticatedUserInterface, SharedUserInterface
{
#[ORM\Id]
#[ORM\GeneratedValue]
@@ -0,0 +1,123 @@
<?php
declare(strict_types=1);
namespace App\EventListener;
use App\Entity\Notification;
use App\Entity\Task;
use App\Entity\User;
use DateTimeImmutable;
use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener;
use Doctrine\ORM\Event\OnFlushEventArgs;
use Doctrine\ORM\Event\PostFlushEventArgs;
use Doctrine\ORM\Events;
use Symfony\Bundle\SecurityBundle\Security;
#[AsDoctrineListener(event: Events::onFlush)]
#[AsDoctrineListener(event: Events::postFlush)]
final class TaskNotificationListener
{
/** @var list<array{user: User, type: string, task: Task}> */
private array $pending = [];
public function __construct(private readonly Security $security) {}
public function onFlush(OnFlushEventArgs $args): void
{
$actor = $this->security->getUser();
if (!$actor instanceof User) {
return;
}
$uow = $args->getObjectManager()->getUnitOfWork();
// Assignation sur une tâche nouvellement créée.
foreach ($uow->getScheduledEntityInsertions() as $entity) {
if (!$entity instanceof Task) {
continue;
}
$assignee = $entity->getAssignee();
if ($assignee instanceof User && $assignee !== $actor) {
$this->pending[] = ['user' => $assignee, 'type' => 'task_assigned', 'task' => $entity];
}
}
// Changement d'assignation sur une tâche existante.
foreach ($uow->getScheduledEntityUpdates() as $entity) {
if (!$entity instanceof Task) {
continue;
}
$changeSet = $uow->getEntityChangeSet($entity);
if (!isset($changeSet['assignee'])) {
continue;
}
$new = $changeSet['assignee'][1];
if ($new instanceof User && $new !== $actor) {
$this->pending[] = ['user' => $new, 'type' => 'task_assigned', 'task' => $entity];
}
}
// Ajout de collaborateur(s) (tâche nouvelle ou existante).
foreach ($uow->getScheduledCollectionUpdates() as $collection) {
$owner = $collection->getOwner();
if (!$owner instanceof Task) {
continue;
}
if ('collaborators' !== $collection->getMapping()->fieldName) {
continue;
}
foreach ($collection->getInsertDiff() as $user) {
if ($user instanceof User && $user !== $actor) {
$this->pending[] = ['user' => $user, 'type' => 'task_collaborator_added', 'task' => $owner];
}
}
}
}
public function postFlush(PostFlushEventArgs $args): void
{
if ([] === $this->pending) {
return;
}
$pending = $this->pending;
$this->pending = [];
$em = $args->getObjectManager();
foreach ($pending as $item) {
$em->persist($this->buildNotification($item['user'], $item['type'], $item['task']));
}
$em->flush();
}
private function buildNotification(User $user, string $type, Task $task): Notification
{
[$title, $message] = $this->render($type, $task);
$notification = new Notification();
$notification->setUser($user);
$notification->setType($type);
$notification->setTitle($title);
$notification->setMessage($message);
$notification->setCreatedAt(new DateTimeImmutable());
return $notification;
}
/**
* @return array{0: string, 1: string}
*/
private function render(string $type, Task $task): array
{
$projectName = $task->getProject()?->getName() ?? '';
$suffix = '' !== $projectName ? sprintf(' — %s', $projectName) : '';
$context = sprintf('« %s »%s', (string) $task->getTitle(), $suffix);
return match ($type) {
'task_assigned' => ['Nouvelle tâche assignée', $context],
'task_collaborator_added' => ['Ajout à une tâche', $context],
default => ['Notification', $context],
};
}
}
@@ -0,0 +1,12 @@
<?php
declare(strict_types=1);
namespace App\Shared\Application;
use App\Shared\Domain\Contract\UserInterface;
interface CurrentUserProviderInterface
{
public function getCurrentUser(): ?UserInterface;
}
@@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace App\Shared\Domain\Contract;
interface BlamableInterface
{
public function getCreatedBy(): ?UserInterface;
public function setCreatedBy(?UserInterface $user): void;
public function getUpdatedBy(): ?UserInterface;
public function setUpdatedBy(?UserInterface $user): void;
}
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace App\Shared\Domain\Contract;
use DateTimeImmutable;
interface TimestampableInterface
{
public function getCreatedAt(): ?DateTimeImmutable;
public function setCreatedAt(DateTimeImmutable $createdAt): void;
public function getUpdatedAt(): ?DateTimeImmutable;
public function setUpdatedAt(DateTimeImmutable $updatedAt): void;
}
@@ -0,0 +1,10 @@
<?php
declare(strict_types=1);
namespace App\Shared\Domain\Contract;
interface UserInterface
{
public function getId(): ?int;
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace App\Shared\Domain\Module;
/**
* Implemented by every `*Module` declaration class. The set of active modules
* is listed in config/modules.php and exposed via GET /api/modules.
*/
interface ModuleInterface
{
public static function id(): string;
public static function label(): string;
public static function isRequired(): bool;
/**
* @return list<array{code: string, label: string}>
*/
public static function permissions(): array;
}
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace App\Shared\Domain\Module;
final class ModuleRegistry
{
/**
* @param list<class-string> $moduleClasses
*
* @return list<string>
*/
public static function ids(array $moduleClasses): array
{
$ids = [];
foreach ($moduleClasses as $moduleClass) {
if (is_a($moduleClass, ModuleInterface::class, true)) {
$ids[] = $moduleClass::id();
}
}
return $ids;
}
}
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace App\Shared\Domain\Sidebar;
final class SidebarFilter
{
/**
* @param list<array{label:string, icon:string, items: list<array{label:string, to:string, icon:string, module?:string}>}> $sections
* @param list<string> $activeModuleIds
*
* @return array{sections: list<array{label:string, icon:string, items: list<array{label:string, to:string, icon:string}>}>, disabledRoutes: list<string>}
*/
public static function filter(array $sections, array $activeModuleIds): array
{
$outSections = [];
$disabledRoutes = [];
foreach ($sections as $section) {
$items = [];
foreach ($section['items'] as $item) {
$module = $item['module'] ?? null;
if (null !== $module && !in_array($module, $activeModuleIds, true)) {
$disabledRoutes[] = $item['to'];
continue;
}
$items[] = ['label' => $item['label'], 'to' => $item['to'], 'icon' => $item['icon']];
}
if ([] !== $items) {
$outSections[] = ['label' => $section['label'], 'icon' => $section['icon'], 'items' => $items];
}
}
return ['sections' => $outSections, 'disabledRoutes' => $disabledRoutes];
}
}
@@ -0,0 +1,71 @@
<?php
declare(strict_types=1);
namespace App\Shared\Domain\Trait;
use App\Shared\Domain\Contract\UserInterface;
use DateTimeImmutable;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Attribute\Groups;
trait TimestampableBlamableTrait
{
#[ORM\Column(name: 'created_at', type: 'datetime_immutable', nullable: true)]
#[Groups(['timestampable:read'])]
private ?DateTimeImmutable $createdAt = null;
#[ORM\Column(name: 'updated_at', type: 'datetime_immutable', nullable: true)]
#[Groups(['timestampable:read'])]
private ?DateTimeImmutable $updatedAt = null;
#[ORM\ManyToOne(targetEntity: UserInterface::class)]
#[ORM\JoinColumn(name: 'created_by', referencedColumnName: 'id', nullable: true, onDelete: 'SET NULL')]
#[Groups(['blamable:read'])]
private ?UserInterface $createdBy = null;
#[ORM\ManyToOne(targetEntity: UserInterface::class)]
#[ORM\JoinColumn(name: 'updated_by', referencedColumnName: 'id', nullable: true, onDelete: 'SET NULL')]
#[Groups(['blamable:read'])]
private ?UserInterface $updatedBy = null;
public function getCreatedAt(): ?DateTimeImmutable
{
return $this->createdAt;
}
public function setCreatedAt(DateTimeImmutable $createdAt): void
{
$this->createdAt = $createdAt;
}
public function getUpdatedAt(): ?DateTimeImmutable
{
return $this->updatedAt;
}
public function setUpdatedAt(DateTimeImmutable $updatedAt): void
{
$this->updatedAt = $updatedAt;
}
public function getCreatedBy(): ?UserInterface
{
return $this->createdBy;
}
public function setCreatedBy(?UserInterface $user): void
{
$this->createdBy = $user;
}
public function getUpdatedBy(): ?UserInterface
{
return $this->updatedBy;
}
public function setUpdatedBy(?UserInterface $user): void
{
$this->updatedBy = $user;
}
}
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace App\Shared\Infrastructure\ApiPlatform\Resource;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use App\Shared\Infrastructure\ApiPlatform\State\ModulesProvider;
use Symfony\Component\Serializer\Attribute\Groups;
#[ApiResource(
operations: [
new Get(
uriTemplate: '/modules',
normalizationContext: ['groups' => ['modules:read']],
provider: ModulesProvider::class,
),
],
)]
final class ModulesResource
{
/**
* @var list<string>
*/
#[Groups(['modules:read'])]
public array $modules = [];
}
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace App\Shared\Infrastructure\ApiPlatform\Resource;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use App\Shared\Infrastructure\ApiPlatform\State\SidebarProvider;
use Symfony\Component\Serializer\Attribute\Groups;
#[ApiResource(
operations: [
new Get(
uriTemplate: '/sidebar',
normalizationContext: ['groups' => ['sidebar:read']],
provider: SidebarProvider::class,
),
],
)]
final class SidebarResource
{
/**
* @var list<array{label:string, icon:string, items: list<array{label:string, to:string, icon:string}>}>
*/
#[Groups(['sidebar:read'])]
public array $sections = [];
/**
* @var list<string>
*/
#[Groups(['sidebar:read'])]
public array $disabledRoutes = [];
}
@@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace App\Shared\Infrastructure\ApiPlatform\State;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Shared\Domain\Module\ModuleRegistry;
use App\Shared\Infrastructure\ApiPlatform\Resource\ModulesResource;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
final readonly class ModulesProvider implements ProviderInterface
{
public function __construct(
#[Autowire('%kernel.project_dir%')]
private string $projectDir,
) {}
public function provide(Operation $operation, array $uriVariables = [], array $context = []): ModulesResource
{
/** @var list<class-string> $classes */
$classes = require $this->projectDir.'/config/modules.php';
$dto = new ModulesResource();
$dto->modules = ModuleRegistry::ids($classes);
return $dto;
}
}
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace App\Shared\Infrastructure\ApiPlatform\State;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Shared\Domain\Module\ModuleRegistry;
use App\Shared\Domain\Sidebar\SidebarFilter;
use App\Shared\Infrastructure\ApiPlatform\Resource\SidebarResource;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
final readonly class SidebarProvider implements ProviderInterface
{
public function __construct(
#[Autowire('%kernel.project_dir%')]
private string $projectDir,
) {}
public function provide(Operation $operation, array $uriVariables = [], array $context = []): SidebarResource
{
/** @var list<class-string> $moduleClasses */
$moduleClasses = require $this->projectDir.'/config/modules.php';
/** @var list<array{label:string, icon:string, items: list<array{label:string, to:string, icon:string, module?:string}>}> $sidebar */
$sidebar = require $this->projectDir.'/config/sidebar.php';
$filtered = SidebarFilter::filter($sidebar, ModuleRegistry::ids($moduleClasses));
$dto = new SidebarResource();
$dto->sections = $filtered['sections'];
$dto->disabledRoutes = $filtered['disabledRoutes'];
return $dto;
}
}
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace App\Shared\Infrastructure\Database;
final class ColumnCommentsCatalog
{
/**
* SQL `COMMENT ON COLUMN` statements for the 4 standard Timestampable/Blamable columns.
* Call from a migration: foreach (...) { $this->addSql($statement); }.
*
* @return list<string>
*/
public static function timestampableBlamableComments(string $table): array
{
return [
"COMMENT ON COLUMN {$table}.created_at IS 'Date de creation (UTC). Rempli automatiquement (Timestampable).'",
"COMMENT ON COLUMN {$table}.updated_at IS 'Date de derniere modification (UTC). Rempli automatiquement (Timestampable).'",
"COMMENT ON COLUMN {$table}.created_by IS 'Auteur de la creation (FK user, SET NULL). Rempli automatiquement (Blamable).'",
"COMMENT ON COLUMN {$table}.updated_by IS 'Auteur de la derniere modification (FK user, SET NULL). Rempli automatiquement (Blamable).'",
];
}
}
@@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
namespace App\Shared\Infrastructure\Doctrine;
use App\Shared\Application\CurrentUserProviderInterface;
use App\Shared\Domain\Contract\BlamableInterface;
use App\Shared\Domain\Contract\TimestampableInterface;
use DateTimeImmutable;
use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener;
use Doctrine\ORM\Event\PrePersistEventArgs;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use Doctrine\ORM\Events;
#[AsDoctrineListener(event: Events::prePersist)]
#[AsDoctrineListener(event: Events::preUpdate)]
final readonly class TimestampableBlamableSubscriber
{
public function __construct(
private CurrentUserProviderInterface $currentUserProvider,
) {}
public function prePersist(PrePersistEventArgs $args): void
{
$this->applyOnCreate($args->getObject());
}
public function preUpdate(PreUpdateEventArgs $args): void
{
$this->applyOnUpdate($args->getObject());
}
public function applyOnCreate(object $entity): void
{
$now = new DateTimeImmutable();
if ($entity instanceof TimestampableInterface) {
if (null === $entity->getCreatedAt()) {
$entity->setCreatedAt($now);
}
$entity->setUpdatedAt($now);
}
if ($entity instanceof BlamableInterface) {
$user = $this->currentUserProvider->getCurrentUser();
if (null === $entity->getCreatedBy()) {
$entity->setCreatedBy($user);
}
$entity->setUpdatedBy($user);
}
}
public function applyOnUpdate(object $entity): void
{
if ($entity instanceof TimestampableInterface) {
$entity->setUpdatedAt(new DateTimeImmutable());
}
if ($entity instanceof BlamableInterface) {
$entity->setUpdatedBy($this->currentUserProvider->getCurrentUser());
}
}
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace App\Shared\Infrastructure\Security;
use App\Shared\Application\CurrentUserProviderInterface;
use App\Shared\Domain\Contract\UserInterface;
use Symfony\Bundle\SecurityBundle\Security;
final readonly class SecurityCurrentUserProvider implements CurrentUserProviderInterface
{
public function __construct(
private Security $security,
) {}
public function getCurrentUser(): ?UserInterface
{
$user = $this->security->getUser();
return $user instanceof UserInterface ? $user : null;
}
}
@@ -0,0 +1,175 @@
<?php
declare(strict_types=1);
namespace App\Tests\Functional\EventListener;
use App\Entity\Project;
use App\Entity\Task;
use App\Entity\User;
use App\Repository\NotificationRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
/**
* @internal
*/
class TaskNotificationListenerTest extends KernelTestCase
{
private EntityManagerInterface $em;
private NotificationRepository $notifications;
private TokenStorageInterface $tokenStorage;
private Project $project;
private User $actor;
private User $alice;
private User $bob;
protected function setUp(): void
{
self::bootKernel();
$c = self::getContainer();
$this->em = $c->get(EntityManagerInterface::class);
$this->notifications = $c->get(NotificationRepository::class);
$this->tokenStorage = $c->get(TokenStorageInterface::class);
$project = $this->em->getRepository(Project::class)->findOneBy([]);
self::assertNotNull($project, 'Les fixtures doivent fournir au moins un projet.');
$this->project = $project;
$this->actor = $this->makeUser('actor');
$this->alice = $this->makeUser('alice');
$this->bob = $this->makeUser('bob');
$this->em->flush();
}
public function testAssignmentToOtherUserCreatesNotification(): void
{
$this->loginAs($this->actor);
$task = $this->makeTask();
$task->setAssignee($this->alice);
$this->em->persist($task);
$this->em->flush();
$rows = $this->notifications->findBy(['user' => $this->alice]);
self::assertCount(1, $rows);
self::assertSame('task_assigned', $rows[0]->getType());
self::assertStringContainsString((string) $task->getTitle(), (string) $rows[0]->getMessage());
}
public function testSelfAssignmentCreatesNoNotification(): void
{
$this->loginAs($this->actor);
$task = $this->makeTask();
$task->setAssignee($this->actor);
$this->em->persist($task);
$this->em->flush();
self::assertCount(0, $this->notifications->findBy(['user' => $this->actor]));
}
public function testReassignmentNotifiesOnlyNewAssignee(): void
{
$this->loginAs($this->actor);
$task = $this->makeTask();
$task->setAssignee($this->alice);
$this->em->persist($task);
$this->em->flush();
$task->setAssignee($this->bob);
$this->em->flush();
self::assertCount(1, $this->notifications->findBy(['user' => $this->alice]));
self::assertCount(1, $this->notifications->findBy(['user' => $this->bob]));
}
public function testAssigneeSetToNullCreatesNoNotificationForNull(): void
{
$this->loginAs($this->actor);
$task = $this->makeTask();
$task->setAssignee($this->alice);
$this->em->persist($task);
$this->em->flush();
$task->setAssignee(null);
$this->em->flush();
// alice a reçu la 1re notif, mais le passage à null n'en crée aucune autre.
self::assertCount(1, $this->notifications->findBy(['user' => $this->alice]));
}
public function testNoActorCreatesNoNotification(): void
{
$this->tokenStorage->setToken(null);
$task = $this->makeTask();
$task->setAssignee($this->alice);
$this->em->persist($task);
$this->em->flush();
self::assertCount(0, $this->notifications->findBy(['user' => $this->alice]));
}
public function testAddingCollaboratorCreatesNotification(): void
{
$this->loginAs($this->actor);
$task = $this->makeTask();
$this->em->persist($task);
$this->em->flush();
$task->addCollaborator($this->alice);
$this->em->flush();
$rows = $this->notifications->findBy(['user' => $this->alice]);
self::assertCount(1, $rows);
self::assertSame('task_collaborator_added', $rows[0]->getType());
}
public function testAddingSelfAsCollaboratorCreatesNoNotification(): void
{
$this->loginAs($this->actor);
$task = $this->makeTask();
$this->em->persist($task);
$this->em->flush();
$task->addCollaborator($this->actor);
$this->em->flush();
self::assertCount(0, $this->notifications->findBy(['user' => $this->actor]));
}
private function makeUser(string $prefix): User
{
$user = new User();
$user->setUsername($prefix.'-'.uniqid());
$user->setPassword('x');
$user->setRoles(['ROLE_USER']);
$this->em->persist($user);
return $user;
}
private function makeTask(): Task
{
$task = new Task();
$task->setNumber(random_int(100000, 999999));
$task->setTitle('Tâche de test '.uniqid());
$task->setProject($this->project);
return $task;
}
private function loginAs(User $user): void
{
$this->tokenStorage->setToken(
new UsernamePasswordToken($user, 'main', $user->getRoles()),
);
}
}
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace App\Tests\Functional\Shared;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
/**
* @internal
*/
final class ModulesEndpointTest extends WebTestCase
{
public function testModulesEndpointIsPublicAndReturnsModulesKey(): void
{
$client = self::createClient();
$client->request('GET', '/api/modules');
self::assertResponseIsSuccessful();
$data = json_decode($client->getResponse()->getContent(), true);
self::assertArrayHasKey('modules', $data);
self::assertIsArray($data['modules']);
}
}
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace App\Tests\Functional\Shared;
use App\Entity\User;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
/**
* @internal
*/
final class SidebarEndpointTest extends WebTestCase
{
public function testSidebarRequiresAuthentication(): void
{
$client = self::createClient();
$client->request('GET', '/api/sidebar');
self::assertResponseStatusCodeSame(401);
}
public function testSidebarReturnsSectionsForAuthenticatedUser(): void
{
$client = self::createClient();
$container = self::getContainer();
$em = $container->get('doctrine.orm.entity_manager');
$user = $em->getRepository(User::class)->findOneBy(['username' => 'alice']);
$client->loginUser($user);
$client->request('GET', '/api/sidebar');
self::assertResponseIsSuccessful();
$data = json_decode($client->getResponse()->getContent(), true);
self::assertArrayHasKey('sections', $data);
self::assertArrayHasKey('disabledRoutes', $data);
self::assertNotEmpty($data['sections']);
}
}
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace App\Tests\Unit\Shared\Database;
use App\Shared\Infrastructure\Database\ColumnCommentsCatalog;
use PHPUnit\Framework\TestCase;
/**
* @internal
*/
final class ColumnCommentsCatalogTest extends TestCase
{
public function testTimestampableBlamableCommentsCoverFourColumns(): void
{
$sql = ColumnCommentsCatalog::timestampableBlamableComments('task');
self::assertCount(4, $sql);
self::assertSame(
"COMMENT ON COLUMN task.created_at IS 'Date de creation (UTC). Rempli automatiquement (Timestampable).'",
$sql[0],
);
self::assertStringContainsString('COMMENT ON COLUMN task.created_by IS', $sql[2]);
}
public function testTableNameIsInterpolatedForEveryColumn(): void
{
foreach (ColumnCommentsCatalog::timestampableBlamableComments('time_entry') as $statement) {
self::assertStringContainsString('COMMENT ON COLUMN time_entry.', $statement);
}
}
}
@@ -0,0 +1,91 @@
<?php
declare(strict_types=1);
namespace App\Tests\Unit\Shared\Doctrine;
use App\Shared\Application\CurrentUserProviderInterface;
use App\Shared\Domain\Contract\BlamableInterface;
use App\Shared\Domain\Contract\TimestampableInterface;
use App\Shared\Domain\Contract\UserInterface;
use App\Shared\Domain\Trait\TimestampableBlamableTrait;
use App\Shared\Infrastructure\Doctrine\TimestampableBlamableSubscriber;
use DateTimeImmutable;
use PHPUnit\Framework\TestCase;
use stdClass;
/**
* @internal
*/
final class TimestampableBlamableSubscriberTest extends TestCase
{
public function testApplyOnCreateSetsTimestampsAndAuthor(): void
{
$user = $this->makeUser(7);
$subscriber = new TimestampableBlamableSubscriber($this->providerReturning($user));
$entity = $this->makeEntity();
$subscriber->applyOnCreate($entity);
self::assertInstanceOf(DateTimeImmutable::class, $entity->getCreatedAt());
self::assertInstanceOf(DateTimeImmutable::class, $entity->getUpdatedAt());
self::assertSame($user, $entity->getCreatedBy());
self::assertSame($user, $entity->getUpdatedBy());
}
public function testApplyOnUpdateLeavesCreatedUntouched(): void
{
$creator = $this->makeUser(1);
$editor = $this->makeUser(2);
$entity = $this->makeEntity();
new TimestampableBlamableSubscriber($this->providerReturning($creator))->applyOnCreate($entity);
$createdAt = $entity->getCreatedAt();
new TimestampableBlamableSubscriber($this->providerReturning($editor))->applyOnUpdate($entity);
self::assertSame($createdAt, $entity->getCreatedAt());
self::assertSame($creator, $entity->getCreatedBy());
self::assertSame($editor, $entity->getUpdatedBy());
}
public function testApplyOnCreateIgnoresNonTimestampableEntities(): void
{
$subscriber = new TimestampableBlamableSubscriber($this->providerReturning(null));
// Must not throw.
$subscriber->applyOnCreate(new stdClass());
$this->addToAssertionCount(1);
}
private function providerReturning(?UserInterface $user): CurrentUserProviderInterface
{
return new class($user) implements CurrentUserProviderInterface {
public function __construct(private ?UserInterface $user) {}
public function getCurrentUser(): ?UserInterface
{
return $this->user;
}
};
}
private function makeUser(int $id): UserInterface
{
return new class($id) implements UserInterface {
public function __construct(private int $id) {}
public function getId(): ?int
{
return $this->id;
}
};
}
private function makeEntity(): object
{
return new class implements TimestampableInterface, BlamableInterface {
use TimestampableBlamableTrait;
};
}
}
@@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
namespace App\Tests\Unit\Shared\Module;
use App\Shared\Domain\Module\ModuleInterface;
use App\Shared\Domain\Module\ModuleRegistry;
use PHPUnit\Framework\TestCase;
use stdClass;
/**
* @internal
*/
final class ModuleRegistryTest extends TestCase
{
public function testIdsExtractsDeclaredModuleIds(): void
{
$classes = [FakeAlphaModule::class, FakeBetaModule::class];
self::assertSame(['alpha', 'beta'], ModuleRegistry::ids($classes));
}
public function testIdsIgnoresClassesNotImplementingModuleInterface(): void
{
$classes = [FakeAlphaModule::class, stdClass::class];
self::assertSame(['alpha'], ModuleRegistry::ids($classes));
}
public function testIdsReturnsEmptyArrayForNoModules(): void
{
self::assertSame([], ModuleRegistry::ids([]));
}
}
final class FakeAlphaModule implements ModuleInterface
{
public static function id(): string
{
return 'alpha';
}
public static function label(): string
{
return 'Alpha';
}
public static function isRequired(): bool
{
return false;
}
public static function permissions(): array
{
return [];
}
}
final class FakeBetaModule implements ModuleInterface
{
public static function id(): string
{
return 'beta';
}
public static function label(): string
{
return 'Beta';
}
public static function isRequired(): bool
{
return true;
}
public static function permissions(): array
{
return [];
}
}
@@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
namespace App\Tests\Unit\Shared\Sidebar;
use App\Shared\Domain\Sidebar\SidebarFilter;
use PHPUnit\Framework\TestCase;
/**
* @internal
*/
final class SidebarFilterTest extends TestCase
{
public function testItemWithoutModuleIsAlwaysVisible(): void
{
$sections = [
['label' => 'sidebar.core.section', 'icon' => 'mdi:home', 'items' => [
['label' => 'sidebar.core.dashboard', 'to' => '/', 'icon' => 'mdi:view-dashboard'],
]],
];
$result = SidebarFilter::filter($sections, []);
self::assertCount(1, $result['sections']);
self::assertSame('/', $result['sections'][0]['items'][0]['to']);
self::assertSame([], $result['disabledRoutes']);
self::assertArrayNotHasKey('module', $result['sections'][0]['items'][0]);
}
public function testItemWithInactiveModuleIsHiddenAndRouteDisabled(): void
{
$sections = [
['label' => 'sidebar.tt.section', 'icon' => 'mdi:clock', 'items' => [
['label' => 'sidebar.tt.timesheet', 'to' => '/time-tracking', 'icon' => 'mdi:clock', 'module' => 'time_tracking'],
]],
];
$result = SidebarFilter::filter($sections, []);
self::assertSame([], $result['sections']);
self::assertSame(['/time-tracking'], $result['disabledRoutes']);
}
public function testItemWithActiveModuleIsVisible(): void
{
$sections = [
['label' => 'sidebar.tt.section', 'icon' => 'mdi:clock', 'items' => [
['label' => 'sidebar.tt.timesheet', 'to' => '/time-tracking', 'icon' => 'mdi:clock', 'module' => 'time_tracking'],
]],
];
$result = SidebarFilter::filter($sections, ['time_tracking']);
self::assertCount(1, $result['sections']);
self::assertSame('/time-tracking', $result['sections'][0]['items'][0]['to']);
self::assertSame([], $result['disabledRoutes']);
}
}