Compare commits

..

2 Commits

Author SHA1 Message Date
Matthieu df0fec0272 fix(notifications) : pagination réelle côté provider pour ne plus tronquer à 30 (LST-52)
NotificationProvider retournait findBy(..., 30) : limite codée en dur,
paramètre page ignoré et tableau brut (pas un Paginator). hydra:totalItems
valait donc 30 → fetchAllHydra s'arrêtait à la 1re page et les notifications
restaient tronquées à 30 malgré le correctif front.

- NotificationProvider : vraie pagination Doctrine (Pagination + DoctrinePaginator
  + TraversablePaginator), totalItems réel et hydra:view.next exposés
- NotificationRepository : createUserNotificationsQueryBuilder (filtre user + tri)
- fetchAllHydra : ne retronque plus silencieusement quand hydra:totalItems est
  absent, pagine jusqu'à une page non pleine
2026-06-15 11:21:05 +02:00
Matthieu 4d3879156d fix(pagination) : éviter la troncature silencieuse des collections paginées (LST-52)
API Platform pagine par défaut à 30 éléments/page et le helper front
extractHydraMembers ne lit que la première page (il ignore hydra:view.next),
ce qui tronque silencieusement toute liste de plus de 30 éléments.

- Back : paginationEnabled false sur les GetCollection consommées en entier
  et à volume borné/modéré (Client, Project, User, TaskTag, TaskGroup,
  TaskStatus, TaskPriority, TaskEffort, Workflow).
- Front : nouveau helper fetchAllHydra() qui parcourt toutes les pages ;
  utilisé pour /notifications (volume non borné, reste paginé côté back).
- Doc : règle anti-troncature ajoutée au CLAUDE.md.

Déjà protégés (vérifiés) : Task, TimeEntry, TaskDocument, TaskRecurrence,
AbsenceRequest/Policy/Balance (paginationEnabled false) et /time_entries/range.
2026-06-15 11:07:59 +02:00
14 changed files with 107 additions and 16 deletions
+1
View File
@@ -95,6 +95,7 @@ Exemples : `feat : add login page`, `fix(auth) : prevent null token crash`
- Traductions dans `frontend/i18n/locales/` (le module résout `langDir` depuis `i18n/`)
- 4 espaces d'indentation
- MalioSelect : options `{ label: string, value: string | number | null }` — accepte les valeurs **string** (enums string OK, ex `category`/`StatusCategory`), pas seulement `number` (vérifié dans la source `Select.vue` : `modelValue: string | number | null`). L'option vide `null` n'est ajoutée que si `empty-option-label` est passé (ne pas le passer pour un champ requis). Largeur via `group-class` (pas de prop `minWidth`/`min-width`). ⚠️ Le `COMPONENTS.md` de la lib est inexact sur ce composant (il indique une clé `text` et une prop `minWidth` inexistantes) : la clé d'affichage réelle est `label`. Ne jamais modifier la lib `malio-layer-ui` depuis ce projet.
- **Pagination API Platform & `extractHydraMembers` (piège de troncature)** : API Platform pagine par défaut à **30 éléments/page**. Le helper `extractHydraMembers()` (`frontend/utils/api.ts`) ne lit **que la première page** (il ignore `hydra:view.next`) → toute liste > 30 éléments est tronquée **silencieusement** (bug LST-51/LST-52). Règle : toute collection consommée via `extractHydraMembers` doit **soit** être servie par une ressource non paginée (`paginationEnabled: false` sur le `GetCollection`, quand le volume est borné/modéré et qu'on veut tout afficher — c'est le cas des référentiels et de Client/Project/User/Task/TimeEntry), **soit** gérer explicitement la pagination via le helper `fetchAllHydra()` (suit toutes les pages, à réserver aux volumes non bornés comme `/notifications`), **soit** passer par une route dédiée bornée (ex `/time_entries/range`). Ne **jamais** lire une seule page d'une collection potentiellement > 30 éléments.
### Composants UI
+6 -3
View File
@@ -1,13 +1,16 @@
import type { Notification } from './dto/notification'
import type { HydraCollection } from '~/utils/api'
import { extractHydraMembers } from '~/utils/api'
import { fetchAllHydra } from '~/utils/api'
export function useNotificationService() {
const api = useApi()
async function getAll(): Promise<Notification[]> {
const data = await api.get<HydraCollection<Notification>>('/notifications')
return extractHydraMembers(data)
// La ressource /notifications reste paginée côté back (volume non borné) :
// on suit toutes les pages pour ne pas tronquer la liste à 30 éléments.
return fetchAllHydra<Notification>(page =>
api.get<HydraCollection<Notification>>('/notifications', { page }),
)
}
async function markAsRead(id: number): Promise<void> {
+57
View File
@@ -8,3 +8,60 @@ export type HydraCollection<T> = {
export function extractHydraMembers<T>(response: HydraCollection<T>): T[] {
return response['hydra:member'] ?? response['member'] ?? []
}
function extractHydraTotal<T>(response: HydraCollection<T>): number | undefined {
return response['hydra:totalItems'] ?? response['totalItems']
}
/**
* Récupère TOUS les éléments d'une collection Hydra paginée en parcourant les pages.
*
* `extractHydraMembers` ne lit que la première page (30 éléments par défaut côté
* API Platform) : toute liste plus longue est tronquée silencieusement. Utiliser
* ce helper dès qu'une collection potentiellement > 30 éléments doit être
* affichée en entier alors que sa ressource back reste paginée.
*
* `fetchPage` reçoit le numéro de page (1-indexé) et doit renvoyer la collection
* Hydra correspondante (passer `page` en query param de l'appel API).
*
* @param maxPages garde-fou anti-boucle infinie (par défaut 1000 pages).
*/
export async function fetchAllHydra<T>(
fetchPage: (page: number) => Promise<HydraCollection<T>>,
maxPages = 1000,
): Promise<T[]> {
const first = await fetchPage(1)
const all = extractHydraMembers(first)
const total = extractHydraTotal(first)
const pageSize = all.length
// 1ʳᵉ page vide → collection vide, rien de plus à récupérer.
if (pageSize === 0) {
return all
}
let page = 2
while (page <= maxPages) {
if (total !== undefined) {
// Total connu : on s'arrête dès qu'on a tout récupéré.
if (all.length >= total) {
break
}
} else if (all.length % pageSize !== 0) {
// Total inconnu (provider custom sans `hydra:totalItems`) : la dernière
// page récupérée n'était pas pleine → fin de collection. On ne s'arrête
// pas en silence sur la 1ʳᵉ page, contrairement à `extractHydraMembers`.
break
}
const next = await fetchPage(page)
const members = extractHydraMembers(next)
if (members.length === 0) {
break
}
all.push(...members)
page += 1
}
return all
}
+1 -1
View File
@@ -18,7 +18,7 @@ use Symfony\Component\Serializer\Attribute\Groups;
#[ApiResource(
operations: [
new GetCollection(security: "is_granted('ROLE_USER')"),
new GetCollection(paginationEnabled: false, security: "is_granted('ROLE_USER')"),
new Get(security: "is_granted('ROLE_USER')"),
new Post(security: "is_granted('ROLE_ADMIN')"),
new Patch(security: "is_granted('ROLE_ADMIN')"),
+1 -1
View File
@@ -25,7 +25,7 @@ use Symfony\Component\Validator\Constraints as Assert;
#[ApiResource(
operations: [
new GetCollection(security: "is_granted('ROLE_USER')"),
new GetCollection(paginationEnabled: false, security: "is_granted('ROLE_USER')"),
new Get(security: "is_granted('ROLE_USER')"),
new Post(
security: "is_granted('ROLE_ADMIN')",
+1 -1
View File
@@ -16,7 +16,7 @@ use Symfony\Component\Serializer\Attribute\Groups;
#[ApiResource(
operations: [
new GetCollection(security: "is_granted('ROLE_USER')"),
new GetCollection(paginationEnabled: false, security: "is_granted('ROLE_USER')"),
new Get(security: "is_granted('ROLE_USER')"),
new Post(security: "is_granted('ROLE_ADMIN')"),
new Patch(security: "is_granted('ROLE_ADMIN')"),
+1 -1
View File
@@ -19,7 +19,7 @@ use Symfony\Component\Serializer\Attribute\Groups;
#[ApiResource(
operations: [
new GetCollection(security: "is_granted('ROLE_USER')"),
new GetCollection(paginationEnabled: false, security: "is_granted('ROLE_USER')"),
new Get(security: "is_granted('ROLE_USER')"),
new Post(security: "is_granted('ROLE_ADMIN')"),
new Patch(security: "is_granted('ROLE_ADMIN')"),
+1 -1
View File
@@ -16,7 +16,7 @@ use Symfony\Component\Serializer\Attribute\Groups;
#[ApiResource(
operations: [
new GetCollection(security: "is_granted('ROLE_USER')"),
new GetCollection(paginationEnabled: false, security: "is_granted('ROLE_USER')"),
new Get(security: "is_granted('ROLE_USER')"),
new Post(security: "is_granted('ROLE_ADMIN')"),
new Patch(security: "is_granted('ROLE_ADMIN')"),
+1 -1
View File
@@ -18,7 +18,7 @@ use Symfony\Component\Validator\Constraints as Assert;
#[ApiResource(
operations: [
new GetCollection(security: "is_granted('ROLE_USER')"),
new GetCollection(paginationEnabled: false, security: "is_granted('ROLE_USER')"),
new Get(security: "is_granted('ROLE_USER')"),
new Post(security: "is_granted('ROLE_ADMIN')"),
new Patch(security: "is_granted('ROLE_ADMIN')"),
+1 -1
View File
@@ -16,7 +16,7 @@ use Symfony\Component\Serializer\Attribute\Groups;
#[ApiResource(
operations: [
new GetCollection(security: "is_granted('ROLE_USER')"),
new GetCollection(paginationEnabled: false, security: "is_granted('ROLE_USER')"),
new Get(security: "is_granted('ROLE_USER')"),
new Post(security: "is_granted('ROLE_ADMIN')"),
new Patch(security: "is_granted('ROLE_ADMIN')"),
+1
View File
@@ -33,6 +33,7 @@ use Symfony\Component\Serializer\Attribute\Groups;
normalizationContext: ['groups' => ['user:list']],
),
new GetCollection(
paginationEnabled: false,
normalizationContext: ['groups' => ['user:list']],
),
new Post(security: "is_granted('ROLE_ADMIN')", processor: UserPasswordHasherProcessor::class),
+1 -1
View File
@@ -21,7 +21,7 @@ use Symfony\Component\Validator\Constraints as Assert;
#[ApiResource(
operations: [
new GetCollection(security: "is_granted('ROLE_USER')"),
new GetCollection(paginationEnabled: false, security: "is_granted('ROLE_USER')"),
new Get(security: "is_granted('ROLE_USER')"),
new Post(security: "is_granted('ROLE_ADMIN')"),
new Patch(security: "is_granted('ROLE_ADMIN')"),
+11
View File
@@ -7,7 +7,9 @@ namespace App\Repository;
use App\Entity\Notification;
use App\Entity\User;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\ORM\QueryBuilder;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* @extends ServiceEntityRepository<Notification>
@@ -19,6 +21,15 @@ class NotificationRepository extends ServiceEntityRepository
parent::__construct($registry, Notification::class);
}
public function createUserNotificationsQueryBuilder(UserInterface $user): QueryBuilder
{
return $this->createQueryBuilder('n')
->where('n.user = :user')
->setParameter('user', $user)
->orderBy('n.createdAt', 'DESC')
;
}
public function countUnreadByUser(User $user): int
{
return (int) $this->createQueryBuilder('n')
+23 -5
View File
@@ -5,11 +5,17 @@ declare(strict_types=1);
namespace App\State;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\Pagination\Pagination;
use ApiPlatform\State\Pagination\TraversablePaginator;
use ApiPlatform\State\ProviderInterface;
use App\Entity\Notification;
use App\Repository\NotificationRepository;
use ArrayIterator;
use Doctrine\ORM\Tools\Pagination\Paginator as DoctrinePaginator;
use Symfony\Bundle\SecurityBundle\Security;
use function count;
/**
* @implements ProviderInterface<Notification>
*/
@@ -18,16 +24,28 @@ final readonly class NotificationProvider implements ProviderInterface
public function __construct(
private Security $security,
private NotificationRepository $notificationRepository,
private Pagination $pagination,
) {}
public function provide(Operation $operation, array $uriVariables = [], array $context = []): array|object
public function provide(Operation $operation, array $uriVariables = [], array $context = []): object
{
$user = $this->security->getUser();
return $this->notificationRepository->findBy(
['user' => $user],
['createdAt' => 'DESC'],
30,
[$page, $offset, $limit] = $this->pagination->getPagination($operation, $context);
$queryBuilder = $this->notificationRepository
->createUserNotificationsQueryBuilder($user)
->setFirstResult($offset)
->setMaxResults($limit)
;
$doctrinePaginator = new DoctrinePaginator($queryBuilder);
return new TraversablePaginator(
new ArrayIterator(iterator_to_array($doctrinePaginator, false)),
$page,
$limit,
(float) count($doctrinePaginator),
);
}
}