Vue bénévole mobile : responsable, téléphone et repère « maintenant »

La vue bénévole reprenait les infos essentielles (poste, jour, horaire,
lieu) mais affichait un badge de validation factice (« TU ES ATTENDU
SUR CE CRÉNEAU ») sans plus-value, sans jamais donner le nom ni le
téléphone du référent du poste à contacter — pourtant déjà modélisés
(`Position.lead_account_id`) depuis la gestion des référents.

Un compte VOLUNTEER n'a pas accès à `positions`/`shifts` (403, cf. § 2
matrice des accès) : ces infos ne pouvaient donc pas être jointes côté
front à partir des listes existantes. Nouvel endpoint dédié et
minimal, réservé à la lecture du planning propre du bénévole :

  GET /editions/{id}/volunteers/{vid}/planning

Renvoie, par affectation : poste, lieu, et référent (nom + téléphone,
`null` si le poste n'a pas de référent ou si son compte n'est pas
rattaché à une fiche bénévole) — sans exposer la liste complète des
postes/créneaux de l'édition. Tests : accès (soi-même / autre
bénévole 403 / COORD+LEAD), présence/absence du référent, tri par
heure de début.

Front : retrait du badge de validation, ajout des lignes responsable/
téléphone par créneau, et un repère horizontal « MAINTENANT » qui se
positionne dans la liste triée des créneaux selon l'heure réelle (juste
avant le prochain créneau à venir) pour situer le bénévole dans son
planning.

Non inclus dans ce commit (édités en parallèle par l'utilisateur,
laissés en l'état) : backend/app/seed.py, frontend/tailwind.config.js.

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 23:33:06 +02:00
co-authored by Claude Sonnet 5
parent 8fcc22115f
commit a78aad58e2
12 changed files with 391 additions and 78 deletions
+9
View File
@@ -83,6 +83,15 @@ export function useVolunteer(id: string | null | undefined) {
});
}
/** Planning enrichi (poste, lieu, référent) d'un bénévole — écran bénévole. */
export function useVolunteerPlanning(volunteerId: string | null | undefined) {
return useQuery({
queryKey: ['volunteer-planning', edition, volunteerId ?? null],
queryFn: () => api.volunteers.planning(edition, volunteerId as string),
enabled: Boolean(volunteerId),
});
}
export function useShifts(positionId?: string) {
return useQuery({
queryKey: queryKeys.shifts(positionId),
+2
View File
@@ -110,6 +110,8 @@ export function createHttpApi(baseUrl: string): PlanningApi {
request(`${base(editionId)}/volunteers/${id}`, { method: 'PATCH', body: JSON.stringify(body) }),
remove: (editionId, id) =>
request(`${base(editionId)}/volunteers/${id}`, { method: 'DELETE' }),
planning: (editionId, id) =>
request(`${base(editionId)}/volunteers/${id}/planning`),
},
accounts: {
list: (editionId) => request(`${base(editionId)}/accounts`),
+27
View File
@@ -835,6 +835,33 @@ export function createMockApi(): PlanningApi {
});
return delay(undefined);
},
planning: (_edition, id) => {
if (!state.volunteers.some((v) => v.id === id)) return notFound();
const entries = state.assignments
.filter((a) => a.volunteer_id === id)
.map((a) => {
const shift = state.shifts.find((s) => s.id === a.shift_id);
const position = shift ? state.positions.find((p) => p.id === shift.position_id) : undefined;
const referentAccount = position?.lead_account_id
? state.accounts.find((acc) => acc.id === position.lead_account_id)
: undefined;
const referent = referentAccount?.volunteer_id
? state.volunteers.find((v) => v.id === referentAccount.volunteer_id)
: undefined;
return {
assignment_id: a.id,
shift_id: a.shift_id,
starts_at: shift?.starts_at ?? '',
ends_at: shift?.ends_at ?? '',
position_name: position?.name ?? '',
position_location: position?.location ?? null,
referent_name: referent ? `${referent.first_name} ${referent.last_name}` : null,
referent_phone: referent?.phone ?? null,
};
})
.sort((a, b) => a.starts_at.localeCompare(b.starts_at));
return delay(entries);
},
},
accounts: {
+18
View File
@@ -135,6 +135,24 @@ export interface VolunteerUpdate {
wished_companion_ids?: string[] | null;
}
/**
* Un créneau affecté, enrichi (poste, lieu, référent à contacter) — pour
* l'écran bénévole. Évite de donner à un compte VOLUNTEER un accès en
* lecture aux postes/créneaux de toute l'édition (réservé à COORD/LEAD).
*/
export interface VolunteerPlanningEntry {
assignment_id: string;
shift_id: string;
starts_at: string;
ends_at: string;
position_name: string;
position_location: string | null;
/** null si le poste n'a pas de référent, ou si son compte n'est pas
* rattaché à une fiche bénévole (pas de téléphone à donner alors). */
referent_name: string | null;
referent_phone: string | null;
}
// --------------------------------------------------------------------------- //
// Availability (disponibilités déclarées par le bénévole) //
// --------------------------------------------------------------------------- //
+3
View File
@@ -38,6 +38,7 @@ import type {
VerifyRequest,
Violation,
VolunteerCreate,
VolunteerPlanningEntry,
VolunteerRead,
VolunteerUpdate,
} from './schema';
@@ -69,6 +70,8 @@ export interface PlanningApi {
create(editionId: string, body: VolunteerCreate): Promise<VolunteerRead>;
update(editionId: string, id: string, body: VolunteerUpdate): Promise<VolunteerRead>;
remove(editionId: string, id: string): Promise<void>;
/** Planning enrichi (poste, lieu, référent) — écran bénévole. */
planning(editionId: string, id: string): Promise<VolunteerPlanningEntry[]>;
};
accounts: {
/** Comptes de connexion (mot de passe ou lien magique) de l'édition. */
+3 -2
View File
@@ -122,10 +122,11 @@
"mobileVol.slots": "{count} CRÉNEAUX",
"mobileVol.hours": "{count} HEURES",
"mobileVol.location": "📍 {location}",
"mobileVol.slotAssigned": "✓ TU ES ATTENDU SUR CE CRÉNEAU",
"mobileVol.referent": "👤 Responsable : {name}",
"mobileVol.phone": "📞 {phone}",
"mobileVol.now": "MAINTENANT",
"mobileVol.noSlots": "Aucun créneau pour l'instant. La coordination t'affectera bientôt.",
"mobileVol.noAccount": "Ce compte n'est rattaché à aucun bénévole. Contactez la coordination.",
"mobileVol.detailsUnavailable": "Le détail des créneaux (poste, horaires) n'est pas encore exposé aux bénévoles par l'API.",
"mobileLead.statusTime": "18:07",
"mobileLead.kicker": "RÉFÉRENT DE POSTE",
"mobileLead.inProgress": "CRÉNEAU · {hours}",
+11
View File
@@ -51,3 +51,14 @@ export function longDayLabel(iso: string): string {
export function hourRangeLabel(startIso: string, endIso: string): string {
return `${timePart(startIso)} → ${timePart(endIso)}`;
}
/** Instant présent, dans la même unité que `naiveMinutes` (minutes « murales »
* sans fuseau) — suppose que l'appareil est à l'heure Europe/Paris, ce qui
* est le cas sur place pendant le festival. Sert à situer « maintenant » par
* rapport aux créneaux naïfs de l'API, jamais à un vrai instant UTC. */
export function nowNaiveMinutes(): number {
const d = new Date();
return (
Date.UTC(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes()) / 60000
);
}
+82 -74
View File
@@ -1,10 +1,9 @@
import { useMemo } from 'react';
import { Fragment, useEffect, useMemo, useState } from 'react';
import { ApiError } from '@/api';
import { useAssignments, usePositions, useShifts, useVolunteer } from '@/api/hooks';
import { useVolunteer, useVolunteerPlanning } from '@/api/hooks';
import { useAuth } from '@/auth/auth-context';
import { ErrorNote, Loading } from '@/components/state';
import { hourRangeLabel, hoursBetween, longDayLabel, naiveMinutes } from '@/lib/time';
import { hourRangeLabel, longDayLabel, naiveMinutes, nowNaiveMinutes } from '@/lib/time';
import { t } from '@/i18n';
// Page réellement consultée par le bénévole (accueil de son rôle, cf.
@@ -16,24 +15,45 @@ import { t } from '@/i18n';
// de gris clair, lisibilité plein soleil), cibles tactiles ≥ 52 px de haut,
// une seule action par créneau.
// Rafraîchit « maintenant » assez souvent pour que le repère bouge de façon
// perceptible sans re-rendre à outrance.
const NOW_REFRESH_MS = 30_000;
function useNowMinutes(): number {
const [minutes, setMinutes] = useState(() => nowNaiveMinutes());
useEffect(() => {
const id = setInterval(() => setMinutes(nowNaiveMinutes()), NOW_REFRESH_MS);
return () => clearInterval(id);
}, []);
return minutes;
}
function NowLine() {
return (
<div className="flex items-center gap-2 px-1" aria-hidden="true">
<div className="h-[3px] flex-1 bg-orange" />
<div className="bg-orange px-[7px] py-[3px] font-mono text-[10px] font-bold text-white">
{t('mobileVol.now')}
</div>
<div className="h-[3px] flex-1 bg-orange" />
</div>
);
}
export function MobileVolunteerPage() {
const { account } = useAuth();
const volunteerId = account?.volunteer_id ?? null;
const meVolunteer = useVolunteer(volunteerId);
const assignments = useAssignments(volunteerId ? { volunteerId } : undefined, {
enabled: Boolean(volunteerId),
});
const shifts = useShifts();
const positions = usePositions();
const shiftsById = useMemo(
() => new Map((shifts.data ?? []).map((s) => [s.id, s])),
[shifts.data],
);
const positionsById = useMemo(
() => new Map((positions.data ?? []).map((p) => [p.id, p])),
[positions.data],
const planning = useVolunteerPlanning(volunteerId);
const nowMinutes = useNowMinutes();
// Hooks appelés inconditionnellement avant les retours anticipés ci-dessous.
const slots = useMemo(
() =>
[...(planning.data ?? [])].sort(
(a, b) => naiveMinutes(a.starts_at) - naiveMinutes(b.starts_at),
),
[planning.data],
);
if (!volunteerId) {
@@ -45,32 +65,23 @@ export function MobileVolunteerPage() {
</div>
);
}
if (assignments.isLoading) return <Loading />;
if (assignments.error) return <ErrorNote error={assignments.error} />;
if (planning.isLoading) return <Loading />;
if (planning.error) return <ErrorNote error={planning.error} />;
const firstName = meVolunteer.data?.first_name ?? account?.email.split('@')[0] ?? '';
// shifts / positions peuvent être refusés (403) à un bénévole côté back-end réel :
// on affiche alors les créneaux sans détail plutôt que de tomber en erreur.
const detailsUnavailable =
(shifts.error instanceof ApiError && shifts.error.status === 403) ||
(positions.error instanceof ApiError && positions.error.status === 403);
const slots = (assignments.data ?? [])
.map((a) => ({ assignment: a, shift: shiftsById.get(a.shift_id) ?? null }))
.sort((a, b) => {
const av = a.shift ? naiveMinutes(a.shift.starts_at) : 0;
const bv = b.shift ? naiveMinutes(b.shift.starts_at) : 0;
return av - bv;
});
const totalHours =
Math.round(
slots.reduce(
(sum, s) => sum + (s.shift ? hoursBetween(s.shift.starts_at, s.shift.ends_at) : 0),
0,
) * 10,
slots.reduce((sum, s) => sum + (naiveMinutes(s.ends_at) - naiveMinutes(s.starts_at)) / 60, 0) *
10,
) / 10;
// Le repère « maintenant » se place juste avant le premier créneau pas
// encore commencé (le prochain à venir) ; en fin de liste si tous sont déjà
// passés.
const nowIndex = slots.findIndex((s) => naiveMinutes(s.starts_at) > nowMinutes);
const nowInsertAt = nowIndex === -1 ? slots.length : nowIndex;
return (
<div className="mx-auto flex w-full max-w-[640px] flex-1 flex-col">
<div className="bg-ink px-4 py-5 text-cream sm:px-6 sm:py-7">
@@ -82,52 +93,49 @@ export function MobileVolunteerPage() {
<div className="bg-yellow px-[9px] py-[7px] font-display text-[12px] font-extrabold text-ink">
{t('mobileVol.slots', { count: slots.length })}
</div>
{!detailsUnavailable ? (
<div className="border-2 border-cream px-[9px] py-[6px] font-display text-[12px] font-extrabold">
{t('mobileVol.hours', { count: totalHours })}
</div>
) : null}
<div className="border-2 border-cream px-[9px] py-[6px] font-display text-[12px] font-extrabold">
{t('mobileVol.hours', { count: totalHours })}
</div>
</div>
</div>
<div className="flex flex-1 flex-col gap-[14px] p-4 sm:p-6">
{detailsUnavailable ? (
<div className="border-2 border-dashed border-ink bg-yellow-soft p-3 font-mono text-[10px] leading-relaxed">
{t('mobileVol.detailsUnavailable')}
</div>
) : null}
{slots.map(({ assignment, shift }) => {
const position = shift ? positionsById.get(shift.position_id) : undefined;
return (
<div key={assignment.id} className="border-[3px] border-ink bg-paper shadow-brutal-lg">
{shift ? (
<div className="flex items-baseline gap-2 bg-ink px-[11px] py-2 text-cream">
<span className="font-display text-[15px] font-black">
{longDayLabel(shift.starts_at)}
</span>
<span className="ml-auto font-mono text-[16px] font-bold text-yellow">
{hourRangeLabel(shift.starts_at, shift.ends_at)}
</span>
</div>
) : null}
{slots.map((entry, i) => (
<Fragment key={entry.assignment_id}>
{i === nowInsertAt ? <NowLine /> : null}
<div className="border-[3px] border-ink bg-paper shadow-brutal-lg">
<div className="flex items-baseline gap-2 bg-ink px-[11px] py-2 text-cream">
<span className="font-display text-[15px] font-black">
{longDayLabel(entry.starts_at)}
</span>
<span className="ml-auto font-mono text-[16px] font-bold text-yellow">
{hourRangeLabel(entry.starts_at, entry.ends_at)}
</span>
</div>
<div className="p-[11px]">
{position ? (
<div className="font-display text-[23px] font-black leading-tight tracking-tight">
{position.name.toUpperCase()}
</div>
) : null}
{position?.location ? (
<div className="mt-[9px] border-t-2 border-ink pt-[9px] font-mono text-[12px]">
{t('mobileVol.location', { location: position.location })}
</div>
) : null}
<div className="mt-[11px] flex min-h-[52px] items-center justify-center border-[3px] border-ink bg-green font-display text-[15px] font-black text-white">
{t('mobileVol.slotAssigned')}
<div className="font-display text-[23px] font-black leading-tight tracking-tight">
{entry.position_name.toUpperCase()}
</div>
{entry.position_location ? (
<div className="mt-[9px] border-t-2 border-ink pt-[9px] font-mono text-[12px]">
{t('mobileVol.location', { location: entry.position_location })}
</div>
) : null}
{entry.referent_name ? (
<div className="mt-[9px] font-mono text-[12px]">
{t('mobileVol.referent', { name: entry.referent_name })}
</div>
) : null}
{entry.referent_phone ? (
<div className="mt-[3px] font-mono text-[12px]">
{t('mobileVol.phone', { phone: entry.referent_phone })}
</div>
) : null}
</div>
</div>
);
})}
</Fragment>
))}
{nowInsertAt === slots.length && slots.length > 0 ? <NowLine /> : null}
{slots.length === 0 ? (
<div className="border-[3px] border-dashed border-ink p-4 font-mono text-[11px] leading-relaxed opacity-70">
{t('mobileVol.noSlots')}