Vœu de compagnon : être affecté avec 0 à N autres bénévoles

Nouveau vœu sur la fiche du bénévole — « je voudrais être affecté avec tel(s)
bénévole(s) » — pris en compte à la fois pour le rendre visible et par le
solveur.

Backend :
- `VolunteerCompanionWish` (`volunteer_id`, `companion_id`, à sens unique,
  `CHECK (volunteer_id <> companion_id)`) — migration 0010.
- API : `wished_companion_ids` sur `VolunteerCreate`/`Update`/`Read`, mêmes
  règles que les autres vœux (ids inconnus → 422 `volunteer.unknown` ; se
  souhaiter soi-même → 422 `volunteer.cannot_wish_self`).
- Solveur (`engine.py`) : bonus (+25 par correspondance) si un des compagnons
  souhaités du candidat est déjà affecté (décision déjà prise) au créneau —
  cumulable si plusieurs compagnons sont présents. Comme les autres termes de
  l'objectif, un bonus/malus, jamais une contrainte.
- Seed de démo : ~20 % des bénévoles ont un vœu de compagnon (couple, amis).

Frontend :
- Fiche bénévole (`ConfigVolunteers.tsx`) : sélecteur de compagnons (ajout et
  édition), avec une bulle d'aide expliquant le sens unique et l'effet sur le
  solveur — c'est ce qui « fait apparaître » le lien entre bénévoles.
- Panneau d'affectation : badge « avec N compagnon(s) souhaité(s) » sur un
  candidat, et bonus correspondant dans le classement par défaut
  (`candidateChanceScore`).
- Mock (`runSolver`) : même bonus, pour que la démonstration se comporte
  pareil que le vrai solveur.

CLAUDE.md à jour (modèle de domaine, section 4, journal).

Vérifié : 194 tests backend (dont 13 nouveaux), ruff, alembic check ;
typecheck/lint/build/smoke frontend ; solveur testé en direct sur le jeu de
démo reseedé (0,25 s, 47 suggestions).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017uUsRg7XzopkCPWimwg9ZM
This commit is contained in:
AdamThomas
2026-09-15 21:50:30 +02:00
co-authored by Claude Sonnet 5
parent b97b95c606
commit 6a4bcf8782
23 changed files with 469 additions and 42 deletions
+5
View File
@@ -233,6 +233,10 @@ export function buildMockState(): MockState {
const artist_ids = artists.filter(() => rnd() < 0.25).map((a) => a.id);
const wished_position_ids =
rnd() < 0.4 ? [positions[Math.floor(rnd() * positions.length)].id] : [];
// Vœu de compagnon (couple, amis) : un autre bénévole de la liste, jamais
// soi-même (décalage d'au moins un cran).
const wished_companion_ids =
rnd() < 0.2 ? [`v${(i + 1 + Math.floor(rnd() * 5)) % 64}`] : [];
volunteers.push({
id,
edition_id,
@@ -243,6 +247,7 @@ export function buildMockState(): MockState {
comment: null,
artist_ids,
wished_position_ids,
wished_companion_ids,
created_at: NOW,
updated_at: NOW,
});
+39 -3
View File
@@ -120,6 +120,15 @@ function resolveWishes<T extends { id: string }>(
return wanted;
}
/** Vœux de compagnon : comme `resolveWishes`, plus le rejet de soi-même. */
function resolveCompanionWishes(ids: string[], selfId?: string): string[] {
const resolved = resolveWishes(state.volunteers, ids, 'volunteer.unknown');
if (selfId != null && resolved.includes(selfId)) {
throw new ApiError(422, 'volunteer.cannot_wish_self');
}
return resolved;
}
function shiftWindow(day: string, dp: DayPartRead): [string, string] {
const endDay = dp.end_time <= dp.start_time ? addDays(day, 1) : day;
return [`${day}T${dp.start_time}`, `${endDay}T${dp.end_time}`];
@@ -392,9 +401,12 @@ const SOLVER_AVAIL_PENALTY_PER_HALF_HOUR = 5;
const SOLVER_REST_PENALTY = 60;
const SOLVER_ARTIST_CONFLICT_PENALTY = 80;
const SOLVER_FAIRNESS_PENALTY_PER_HOUR = 2;
// Le bénévole a déjà tenu le créneau précédent de ce même poste (même jour) :
// favorise la rotation plutôt que d'enchaîner toujours la même personne.
// Le bénévole a déjà tenu le créneau immédiatement précédent (même jour,
// n'importe quel poste) : limite les enchaînements de shifts plutôt que de
// faire tourner un poste en particulier.
const SOLVER_CHAIN_PENALTY = 40;
// Par compagnon souhaité déjà affecté au créneau (0 à N vœux par bénévole).
const SOLVER_COMPANION_BONUS_PER_MATCH = 25;
type TimeWindow = { starts_at: string; ends_at: string };
@@ -408,6 +420,14 @@ function volunteerExistingShifts(volunteerId: string): ShiftRead[] {
.map((a) => shiftById(a.shift_id));
}
/** Bénévoles déjà affectés (décisions déjà prises) à un créneau — sert au
* bonus de compagnon de route (voir `solverScore`). */
function assignedVolunteerIds(shiftId: string): Set<string> {
return new Set(
state.assignments.filter((a) => a.shift_id === shiftId).map((a) => a.volunteer_id),
);
}
/** Créneau(x) — n'importe quel poste — dont la fin coïncide avec le début de
* chaque créneau, le même jour (indexé par id de créneau) — sert au malus de
* chaînage (voir `solverScore`), pour limiter les enchaînements de shifts
@@ -459,6 +479,7 @@ function solverScore(
existing: ShiftRead[],
wishedArtists: TimeWindow[],
chainedFromPredecessor: boolean,
alreadyAssignedIds: Set<string>,
): number {
let score = assignedCount < shift.min_staff ? SOLVER_URGENT_BASE : SOLVER_NORMAL_BASE;
if (volunteer.wished_position_ids.includes(shift.position_id)) score += SOLVER_WISH_BONUS;
@@ -466,6 +487,10 @@ function solverScore(
score -= SOLVER_ARTIST_CONFLICT_PENALTY;
}
if (chainedFromPredecessor) score -= SOLVER_CHAIN_PENALTY;
const companionsPresent = volunteer.wished_companion_ids.filter((id) =>
alreadyAssignedIds.has(id),
).length;
score += SOLVER_COMPANION_BONUS_PER_MATCH * companionsPresent;
const windows = state.availability.get(volunteer.id) ?? [];
const missed = uncoveredMinutes(windows, shift.starts_at, shift.ends_at);
@@ -523,6 +548,7 @@ function runSolver(): SolverRunResult {
for (const shift of ordered) {
const gap = shift.ideal_staff - (assignedCount.get(shift.id) ?? 0);
if (gap <= 0) continue;
const alreadyAssignedIds = assignedVolunteerIds(shift.id);
const picked = state.volunteers
.filter((v) => {
const busy = [
@@ -544,6 +570,7 @@ function runSolver(): SolverRunResult {
existing,
artistWindowsByVolunteer.get(v.id) ?? [],
chained,
alreadyAssignedIds,
),
};
})
@@ -729,6 +756,7 @@ export function createMockApi(): PlanningApi {
body.wished_position_ids ?? [],
'position.unknown',
),
wished_companion_ids: resolveCompanionWishes(body.wished_companion_ids ?? []),
created_at: now,
updated_at: now,
};
@@ -756,6 +784,9 @@ export function createMockApi(): PlanningApi {
),
}
: {}),
...(body.wished_companion_ids != null
? { wished_companion_ids: resolveCompanionWishes(body.wished_companion_ids, v.id) }
: {}),
updated_at: touch(),
});
return delay(v);
@@ -764,8 +795,12 @@ export function createMockApi(): PlanningApi {
state.volunteers = state.volunteers.filter((x) => x.id !== id);
state.assignments = state.assignments.filter((a) => a.volunteer_id !== id);
state.availability.delete(id);
// RGPD : effacement complet, y compris le compte de connexion éventuel.
// RGPD : effacement complet, y compris le compte de connexion éventuel
// et les vœux de compagnon dont il était la cible.
state.accounts = state.accounts.filter((a) => a.volunteer_id !== id);
state.volunteers.forEach((v) => {
v.wished_companion_ids = v.wished_companion_ids.filter((cid) => cid !== id);
});
return delay(undefined);
},
},
@@ -998,6 +1033,7 @@ export function createMockApi(): PlanningApi {
comment: null,
artist_ids: [],
wished_position_ids: [],
wished_companion_ids: [],
created_at: now,
updated_at: now,
};
+4
View File
@@ -106,6 +106,8 @@ export interface VolunteerRead {
artist_ids: string[];
/** Vœux : postes que le bénévole voudrait tenir. */
wished_position_ids: string[];
/** Vœux : bénévoles avec qui il voudrait être affecté (0 à N, à sens unique). */
wished_companion_ids: string[];
created_at: string;
updated_at: string;
}
@@ -118,6 +120,7 @@ export interface VolunteerCreate {
comment?: string | null;
artist_ids?: string[];
wished_position_ids?: string[];
wished_companion_ids?: string[];
}
export interface VolunteerUpdate {
@@ -129,6 +132,7 @@ export interface VolunteerUpdate {
/** null / absent = inchangé ; [] = vider. */
artist_ids?: string[] | null;
wished_position_ids?: string[] | null;
wished_companion_ids?: string[] | null;
}
// --------------------------------------------------------------------------- //
+6 -1
View File
@@ -288,10 +288,14 @@
"config.artists.namePlaceholder": "Nom de l'artiste",
"config.vol.field.artists": "Artistes à voir",
"config.vol.field.positions": "Postes souhaités",
"config.vol.field.companions": "Bénévoles souhaités",
"config.vol.companionsHint": "Bénévoles avec qui il voudrait être affecté (à sens unique). Le solveur privilégie un candidat dont l'un des compagnons souhaités est déjà sur le créneau.",
"config.vol.noArtists": "Aucun artiste choisi",
"config.vol.noPositions": "Aucun poste choisi",
"config.vol.noCompanions": "Aucun bénévole choisi",
"config.vol.pickArtist": "Ajouter un artiste…",
"config.vol.pickPosition": "Ajouter un poste…",
"config.vol.pickCompanion": "Ajouter un bénévole…",
"config.vol.colWishes": "VŒUX",
"config.vol.wishesCount": "{count} vœu(x)",
"config.vol.addAvailabilityHint": "Les disponibilités se renseignent sur la fiche du bénévole, une fois celui-ci créé.",
@@ -312,5 +316,6 @@
"config.artists.startTime": "Heure de début du passage",
"config.artists.endTime": "Heure de fin du passage",
"grille.panel.wishesPosition": "Vœu de poste",
"grille.panel.artistConflict": "Manquerait un artiste souhaité"
"grille.panel.artistConflict": "Manquerait un artiste souhaité",
"grille.panel.withCompanion": "Avec {count} compagnon(s) souhaité(s)"
}
+7 -3
View File
@@ -116,23 +116,27 @@ const CHANCE_WISH_POSITION_BONUS = 30;
const CHANCE_AVAIL_PENALTY_PER_HALF_HOUR = 5;
const CHANCE_ARTIST_CONFLICT_PENALTY = 80;
const CHANCE_FAIRNESS_PENALTY_PER_HOUR = 2;
const CHANCE_COMPANION_BONUS_PER_MATCH = 25;
/**
* Score de chance d'un bénévole pour un créneau : vœu de poste, disponibilité
* (y compris le conflit avec un artiste qu'il veut voir), charge déjà
* assignée. Plus haut = meilleur candidat. Sert uniquement à trier la liste
* affichée ; la validation (blocage / avertissements) reste seule juge.
* (y compris le conflit avec un artiste qu'il veut voir), compagnons
* souhaités déjà affectés au créneau, charge déjà assignée. Plus haut =
* meilleur candidat. Sert uniquement à trier la liste affichée ; la
* validation (blocage / avertissements) reste seule juge.
*/
export function candidateChanceScore(params: {
wishesPosition: boolean;
uncoveredMinutes: number;
conflictsWishedArtist: boolean;
companionMatches: number;
assignedHours: number;
}): number {
let score = 0;
if (params.wishesPosition) score += CHANCE_WISH_POSITION_BONUS;
score -= Math.floor(params.uncoveredMinutes / 30) * CHANCE_AVAIL_PENALTY_PER_HALF_HOUR;
if (params.conflictsWishedArtist) score -= CHANCE_ARTIST_CONFLICT_PENALTY;
score += CHANCE_COMPANION_BONUS_PER_MATCH * params.companionMatches;
score -= CHANCE_FAIRNESS_PENALTY_PER_HOUR * params.assignedHours;
return score;
}
+56 -4
View File
@@ -1,4 +1,4 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { ApiError } from '@/api';
import {
@@ -26,6 +26,7 @@ import type {
ImportReport,
PositionRead,
VolunteerCreate,
VolunteerRead,
} from '@/api/schema';
import { FieldLabel, HelpTip, TextInput } from '@/components/ui';
import { ErrorNote, Loading } from '@/components/state';
@@ -71,7 +72,21 @@ function positionOptions(positions: PositionRead[] | undefined): WishOption[] {
.map((p) => ({ id: p.id, label: p.name, hint: p.location ?? undefined }));
}
/** Sélecteur de vœux : liste déroulante + puces retirables. */
/** Les autres bénévoles, pour le vœu de compagnon (jamais soi-même). */
function volunteerOptions(
volunteers: VolunteerRead[] | undefined,
excludeId?: string,
): WishOption[] {
return [...(volunteers ?? [])]
.filter((v) => v.id !== excludeId)
.sort(
(a, b) =>
a.last_name.localeCompare(b.last_name, 'fr') ||
a.first_name.localeCompare(b.first_name, 'fr'),
)
.map((v) => ({ id: v.id, label: `${v.first_name} ${v.last_name}` }));
}
/**
* Accès de connexion (lien magique) du bénévole. Ajouter un email sur sa
* fiche ne crée aucun compte : sans ce geste explicite, `auth/magic-link` ne
@@ -144,7 +159,7 @@ function WishPicker({
emptyLabel,
addLabel,
}: {
label: string;
label: ReactNode;
options: WishOption[];
selected: string[];
onChange: (ids: string[]) => void;
@@ -214,6 +229,10 @@ export function ConfigVolunteers() {
const artistOpts = useMemo(() => artistOptions(artists.data), [artists.data]);
const positionOpts = useMemo(() => positionOptions(positions.data), [positions.data]);
const companionOpts = useMemo(
() => volunteerOptions(volunteers.data, selectedId ?? undefined),
[volunteers.data, selectedId],
);
const filtered = useMemo(() => {
const needle = search.trim().toLowerCase();
@@ -338,7 +357,10 @@ export function ConfigVolunteers() {
</span>
<span className="truncate font-mono text-[10px] opacity-70">
{t('config.vol.wishesCount', {
count: volunteer.artist_ids.length + volunteer.wished_position_ids.length,
count:
volunteer.artist_ids.length +
volunteer.wished_position_ids.length +
volunteer.wished_companion_ids.length,
})}
</span>
</button>
@@ -427,6 +449,19 @@ export function ConfigVolunteers() {
emptyLabel={t('config.vol.noPositions')}
addLabel={t('config.vol.pickPosition')}
/>
<WishPicker
label={
<>
{t('config.vol.field.companions')}{' '}
<HelpTip text={t('config.vol.companionsHint')} />
</>
}
options={companionOpts}
selected={selected.wished_companion_ids}
onChange={(ids) => patch({ wished_companion_ids: ids })}
emptyLabel={t('config.vol.noCompanions')}
addLabel={t('config.vol.pickCompanion')}
/>
<AvailabilityEditor volunteerId={selected.id} />
@@ -456,13 +491,16 @@ function AddVolunteerForm({ onClose }: { onClose: () => void }) {
const createVolunteer = useCreateVolunteer();
const artists = useArtists();
const positions = usePositions();
const volunteers = useVolunteers();
const [form, setForm] = useState<VolunteerCreate>({ first_name: '', last_name: '' });
const [artistIds, setArtistIds] = useState<string[]>([]);
const [wishedPositionIds, setWishedPositionIds] = useState<string[]>([]);
const [wishedCompanionIds, setWishedCompanionIds] = useState<string[]>([]);
const [localError, setLocalError] = useState<string | null>(null);
const artistOpts = useMemo(() => artistOptions(artists.data), [artists.data]);
const positionOpts = useMemo(() => positionOptions(positions.data), [positions.data]);
const companionOpts = useMemo(() => volunteerOptions(volunteers.data), [volunteers.data]);
const set = <K extends keyof VolunteerCreate>(key: K, value: VolunteerCreate[K]) =>
setForm((f) => ({ ...f, [key]: value }));
@@ -482,6 +520,7 @@ function AddVolunteerForm({ onClose }: { onClose: () => void }) {
comment: form.comment?.trim() || null,
artist_ids: artistIds,
wished_position_ids: wishedPositionIds,
wished_companion_ids: wishedCompanionIds,
});
onClose();
} catch (err) {
@@ -558,6 +597,19 @@ function AddVolunteerForm({ onClose }: { onClose: () => void }) {
emptyLabel={t('config.vol.noPositions')}
addLabel={t('config.vol.pickPosition')}
/>
<WishPicker
label={
<>
{t('config.vol.field.companions')}{' '}
<HelpTip text={t('config.vol.companionsHint')} />
</>
}
options={companionOpts}
selected={wishedCompanionIds}
onChange={setWishedCompanionIds}
emptyLabel={t('config.vol.noCompanions')}
addLabel={t('config.vol.pickCompanion')}
/>
{localError ? (
<div className="border-2 border-ink bg-orange p-[9px] font-display text-[11px] font-bold">
+30 -6
View File
@@ -127,9 +127,14 @@ export function AssignmentPanel({
const assigned = useMemo(() => shiftAssignments.data ?? [], [shiftAssignments.data]);
// Raisons du score, par bénévole : vœu de poste, conflit avec un artiste
// qu'il veut voir sur ce créneau (indépendant de sa disponibilité déclarée).
// qu'il veut voir sur ce créneau (indépendant de sa disponibilité déclarée),
// compagnons souhaités déjà affectés à ce créneau.
const detailsByVolunteer = useMemo(() => {
const map = new Map<string, { wishesPosition: boolean; conflictsWishedArtist: boolean }>();
const assignedIds = new Set(assigned.map((a) => a.volunteer_id));
const map = new Map<
string,
{ wishesPosition: boolean; conflictsWishedArtist: boolean; companionMatches: number }
>();
for (const v of volunteers.data ?? []) {
const conflictsWishedArtist = v.artist_ids.some((id) => {
const artist = artistsById.get(id);
@@ -138,14 +143,16 @@ export function AssignmentPanel({
map.set(v.id, {
wishesPosition: v.wished_position_ids.includes(positionId),
conflictsWishedArtist,
companionMatches: v.wished_companion_ids.filter((id) => assignedIds.has(id)).length,
});
}
return map;
}, [volunteers.data, artistsById, shift, positionId]);
}, [volunteers.data, artistsById, shift, positionId, assigned]);
// Score de chance de chaque candidat pour CE créneau : vœu de poste,
// disponibilité (dont conflit avec un artiste qu'il veut voir), charge déjà
// assignée — c'est ce qui classe la liste, pas juste « le moins chargé ».
// disponibilité (dont conflit avec un artiste qu'il veut voir), compagnons
// souhaités déjà présents, charge déjà assignée — c'est ce qui classe la
// liste, pas juste « le moins chargé ».
const scoreByVolunteer = useMemo(() => {
const map = new Map<string, number>();
for (const v of volunteers.data ?? []) {
@@ -160,6 +167,7 @@ export function AssignmentPanel({
shift.ends_at,
),
conflictsWishedArtist: details?.conflictsWishedArtist ?? false,
companionMatches: details?.companionMatches ?? 0,
assignedHours: hours.get(v.id) ?? 0,
}),
);
@@ -280,6 +288,7 @@ export function AssignmentPanel({
conflictsWishedArtist={
detailsByVolunteer.get(volunteer.id)?.conflictsWishedArtist ?? false
}
companionMatches={detailsByVolunteer.get(volunteer.id)?.companionMatches ?? 0}
suggested={suggestedIds.includes(volunteer.id)}
resolvePosition={resolvePosition}
/>
@@ -303,6 +312,7 @@ function CandidateRow({
coverage,
wishesPosition,
conflictsWishedArtist,
companionMatches,
suggested,
resolvePosition,
}: {
@@ -313,6 +323,7 @@ function CandidateRow({
coverage: Coverage;
wishesPosition: boolean;
conflictsWishedArtist: boolean;
companionMatches: number;
suggested: boolean;
resolvePosition: (shiftId: string) => string | undefined;
}) {
@@ -379,9 +390,14 @@ function CandidateRow({
{t('grille.panel.artistConflict')}
</span>
) : null}
{companionMatches > 0 ? (
<span className="inline-block border-[1.5px] border-ink bg-blue px-[6px] py-[3px] font-display text-[8.5px] font-extrabold uppercase tracking-wide">
{t('grille.panel.withCompanion', { count: companionMatches })}
</span>
) : null}
</div>
{blocking ? (
{/* {blocking ? (
<div className="flex items-stretch border-t-2 border-ink">
<span className="flex w-[26px] flex-none items-center justify-center border-r-2 border-ink bg-hatch-orange font-display text-[12px] font-bold">
⛔
@@ -390,6 +406,14 @@ function CandidateRow({
{t('grille.panel.blockingPrefix', { reason: violationText(blocking, resolvePosition) })}
</span>
</div>
) : null} */}
{blocking ? (
<div className="border-t-2 border-dashed border-ink bg-hatch-orange px-2 py-[6px]">
<div className="font-display text-[8.5px] font-extrabold uppercase tracking-widest text-white">
{t('grille.panel.blockingPrefix', { reason: violationText(blocking, resolvePosition) })}
</div>
</div>
) : null}
{!isBlocked && warnings.length > 0 ? (