Étape 21 : formulaire public d'inscription des bénévoles

Retire « constructeur de formulaire » des exclusions du CLAUDE.md (§ 5) —
décision explicite prise en conversation.

Un formulaire par édition (COORDINATION choisit les champs actifs parmi
neuf : email, téléphone, vœux de poste — max 2, vœux d'artiste — un par
soir de festival, vœu de compagnon en texte libre, disponibilité/
cotisation déclaratives, photo, commentaire ; nom/prénom toujours
collectés) ouvert/fermé à volonté, avec un lien à partager
(/inscription, aucun compte requis).

Backend : FormTemplate/FormField (migration 0013), quatre nouveaux champs
sur Volunteer (photo, companion_wish_note, self_declared_available,
willing_to_pay_fee), app/api/forms.py — les deux seuls endpoints publics
de toute l'API (GET .../form/public, POST .../form/public/submit),
protégés par hCaptcha (app/forms/captcha.py, désactivé sans
HCAPTCHA_SECRET_KEY) et un filet de sécurité global par édition
(form_submission_limiter). resolve_owned_ids/set_artists/
set_wished_positions déplacés vers app/api/_common.py, partagés avec
volunteers.py.

Frontend : écran de configuration (/inscriptions) avec lien copiable et
bascule ouvert/fermé, formulaire public (/inscription, hors RequireAuth)
avec widget hCaptcha chargé dynamiquement, capture photo native
(<input capture>), vœux de poste/artiste avec les mêmes règles que le
back-end. Réponses du formulaire visibles et éditables depuis la fiche
bénévole existante (ConfigVolunteers.tsx).

Vérifié : pytest (273 passés), ruff, alembic check, tsc --noEmit, eslint,
vite build, smoke (rendu SSR de chaque écran + flux de bout en bout du
formulaire en mode démonstration) — tous verts.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
AdamThomas
2026-09-21 20:24:32 +02:00
co-authored by Claude Sonnet 5
parent 55c5d539a8
commit 82088f3b0c
41 changed files with 2197 additions and 81 deletions
+74
View File
@@ -23,10 +23,13 @@ import type {
DayPartCreate,
DayPartUpdate,
EditionUpdate,
FormFieldsSet,
FormTemplateUpdate,
ImportMapping,
PlanningNotificationRequest,
PositionCreate,
PositionUpdate,
PublicFormSubmission,
ShiftCreate,
ShiftUpdate,
VolunteerCreate,
@@ -97,6 +100,30 @@ export function useVolunteerPlanning(volunteerId: string | null | undefined) {
});
}
/** URL objet (aperçu) de la photo d'un bénévole (formulaire public), ou
* `null` si absente. */
export function useVolunteerPhotoUrl(volunteerId: string | null | undefined, hasPhoto: boolean) {
const [url, setUrl] = useState<string | null>(null);
useEffect(() => {
let objectUrl: string | null = null;
let cancelled = false;
if (!hasPhoto || !volunteerId) {
setUrl(null);
return;
}
api.volunteers.photoBlob(edition, volunteerId).then((blob) => {
if (cancelled || !blob) return;
objectUrl = URL.createObjectURL(blob);
setUrl(objectUrl);
});
return () => {
cancelled = true;
if (objectUrl) URL.revokeObjectURL(objectUrl);
};
}, [volunteerId, hasPhoto]);
return url;
}
export function useShifts(positionId?: string) {
return useQuery({
queryKey: queryKeys.shifts(positionId),
@@ -553,3 +580,50 @@ export function useGenerateBadges() {
mutationFn: (body: BadgeGenerateRequest) => api.badges.generate(edition, body),
});
}
// --------------------------------------------------------------------------- //
// Formulaire public d'inscription //
// --------------------------------------------------------------------------- //
/** Configuration du formulaire (COORDINATION). */
export function useFormTemplate() {
return useQuery({
queryKey: ['formTemplate', edition],
queryFn: () => api.forms.getTemplate(edition),
});
}
function useInvalidateFormTemplate() {
const client = useQueryClient();
return () => client.invalidateQueries({ queryKey: ['formTemplate', edition] });
}
export function useSetFormFields() {
const invalidate = useInvalidateFormTemplate();
return useMutation({
mutationFn: (body: FormFieldsSet) => api.forms.setFields(edition, body),
onSuccess: invalidate,
});
}
export function useSetFormOpen() {
const invalidate = useInvalidateFormTemplate();
return useMutation({
mutationFn: (body: FormTemplateUpdate) => api.forms.setOpen(edition, body),
onSuccess: invalidate,
});
}
/** Configuration publique du formulaire — utilisable sans compte connecté
* (écran `/inscription`, hors de `RequireAuth`). */
export function usePublicFormConfig() {
return useQuery({
queryKey: ['publicFormConfig', edition],
queryFn: () => api.forms.getPublicConfig(edition),
});
}
export function useSubmitPublicForm() {
return useMutation({
mutationFn: (body: PublicFormSubmission) => api.forms.submitPublic(edition, body),
});
}
+37
View File
@@ -13,12 +13,15 @@ import type {
DayPartCreate,
DayPartUpdate,
EditionUpdate,
FormFieldsSet,
FormTemplateUpdate,
ImportMapping,
LoginRequest,
MagicLinkRequest,
PlanningNotificationRequest,
PositionCreate,
PositionUpdate,
PublicFormSubmission,
ShiftCreate,
ShiftUpdate,
VerifyRequest,
@@ -144,6 +147,7 @@ export function createHttpApi(baseUrl: string): PlanningApi {
request(`${base(editionId)}/volunteers/${id}`, { method: 'DELETE' }),
planning: (editionId, id) =>
request(`${base(editionId)}/volunteers/${id}/planning`),
photoBlob: (editionId, id) => requestBlob(`${base(editionId)}/volunteers/${id}/photo`),
},
accounts: {
list: (editionId) => request(`${base(editionId)}/accounts`),
@@ -262,6 +266,39 @@ export function createHttpApi(baseUrl: string): PlanningApi {
return blob;
},
},
forms: {
getTemplate: (editionId) => request(`${base(editionId)}/form`),
setFields: (editionId, body: FormFieldsSet) =>
request(`${base(editionId)}/form/fields`, {
method: 'PUT',
body: JSON.stringify(body),
}),
setOpen: (editionId, body: FormTemplateUpdate) =>
request(`${base(editionId)}/form`, { method: 'PATCH', body: JSON.stringify(body) }),
getPublicConfig: (editionId) => request(`${base(editionId)}/form/public`),
submitPublic: (editionId, body: PublicFormSubmission) => {
const form = new FormData();
form.append('first_name', body.first_name);
form.append('last_name', body.last_name);
form.append('hcaptcha_token', body.hcaptcha_token);
if (body.email) form.append('email', body.email);
if (body.phone) form.append('phone', body.phone);
if (body.comment) form.append('comment', body.comment);
if (body.companion_wish_note) form.append('companion_wish_note', body.companion_wish_note);
if (body.available !== undefined) form.append('available', String(body.available));
if (body.willing_to_pay_fee !== undefined) {
form.append('willing_to_pay_fee', String(body.willing_to_pay_fee));
}
if (body.position_wish_ids) {
form.append('position_wish_ids', JSON.stringify(body.position_wish_ids));
}
if (body.artist_wish_ids) {
form.append('artist_wish_ids', JSON.stringify(body.artist_wish_ids));
}
if (body.photo) form.append('photo', body.photo);
return request(`${base(editionId)}/form/public/submit`, { method: 'POST', body: form });
},
},
solver: {
run: (editionId) =>
request(`${base(editionId)}/solver/suggestions`, { method: 'POST' }),
+13
View File
@@ -8,6 +8,7 @@ import type {
BadgeFieldRead,
DayPartRead,
EditionRead,
FormFieldType,
PositionCategory,
PositionRead,
ShiftRead,
@@ -49,6 +50,12 @@ export interface MockState {
backImageType: string | null;
fields: BadgeFieldRead[];
};
formTemplate: {
isOpen: boolean;
fields: FormFieldType[];
};
/** volunteerId -> photo (formulaire public), data URL. */
photos: Map<string, string>;
seq: number;
}
@@ -258,6 +265,10 @@ export function buildMockState(): MockState {
artist_ids,
wished_position_ids,
wished_companion_ids,
has_photo: false,
companion_wish_note: null,
self_declared_available: false,
willing_to_pay_fee: false,
created_at: NOW,
updated_at: NOW,
});
@@ -431,6 +442,8 @@ export function buildMockState(): MockState {
backImageType: null,
fields: [],
},
formTemplate: { isOpen: true, fields: [] },
photos: new Map(),
seq,
};
}
+127
View File
@@ -19,6 +19,10 @@ import type {
DayPartRead,
DayPartUpdate,
EditionUpdate,
FormFieldsSet,
FormSubmissionResult,
FormTemplateRead,
FormTemplateUpdate,
ImportAnalyzeResponse,
ImportMapping,
ImportPreviewRow,
@@ -26,6 +30,8 @@ import type {
ImportRowReport,
MatrixResponse,
PlanningNotificationRequest,
PublicFormConfig,
PublicFormSubmission,
ShiftRead,
SolverRunResult,
SolverSuggestion,
@@ -102,6 +108,11 @@ const imageSizeMm = async (file: File): Promise<{ width_mm: number; height_mm: n
return { width_mm, height_mm };
};
// Approche de `str.title()` (Python) utilisé côté back-end à la soumission
// du formulaire public — capitalise chaque mot (« - » compris).
const titleCase = (s: string): string =>
s.toLowerCase().replace(/\b\p{L}/gu, (c) => c.toUpperCase());
const fileToDataUrl = (file: File): Promise<string> =>
new Promise((resolve, reject) => {
const reader = new FileReader();
@@ -831,6 +842,10 @@ export function createMockApi(): PlanningApi {
'position.unknown',
),
wished_companion_ids: resolveCompanionWishes(body.wished_companion_ids ?? []),
has_photo: false,
companion_wish_note: null,
self_declared_available: false,
willing_to_pay_fee: false,
created_at: now,
updated_at: now,
};
@@ -861,6 +876,15 @@ export function createMockApi(): PlanningApi {
...(body.wished_companion_ids != null
? { wished_companion_ids: resolveCompanionWishes(body.wished_companion_ids, v.id) }
: {}),
...('companion_wish_note' in body
? { companion_wish_note: body.companion_wish_note ?? null }
: {}),
...('self_declared_available' in body && body.self_declared_available != null
? { self_declared_available: body.self_declared_available }
: {}),
...('willing_to_pay_fee' in body && body.willing_to_pay_fee != null
? { willing_to_pay_fee: body.willing_to_pay_fee }
: {}),
updated_at: touch(),
});
return delay(v);
@@ -869,6 +893,7 @@ 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);
state.photos.delete(id);
// 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);
@@ -877,6 +902,11 @@ export function createMockApi(): PlanningApi {
});
return delay(undefined);
},
photoBlob: async (_edition, id) => {
const dataUrl = state.photos.get(id);
if (!dataUrl) return null;
return (await fetch(dataUrl)).blob();
},
planning: (_edition, id) => {
if (!state.volunteers.some((v) => v.id === id)) return notFound();
const entries = state.assignments
@@ -1147,6 +1177,10 @@ export function createMockApi(): PlanningApi {
artist_ids: [],
wished_position_ids: [],
wished_companion_ids: [],
has_photo: false,
companion_wish_note: null,
self_declared_available: false,
willing_to_pay_fee: false,
created_at: now,
updated_at: now,
};
@@ -1430,6 +1464,99 @@ export function createMockApi(): PlanningApi {
},
},
forms: {
getTemplate: (): Promise<FormTemplateRead> =>
delay({
edition_id: state.edition.id,
is_open: state.formTemplate.isOpen,
fields: state.formTemplate.fields,
}),
setFields: (_edition, body: FormFieldsSet) => {
state.formTemplate.fields = [...new Set(body.fields)];
return delay<FormTemplateRead>({
edition_id: state.edition.id,
is_open: state.formTemplate.isOpen,
fields: state.formTemplate.fields,
});
},
setOpen: (_edition, body: FormTemplateUpdate) => {
state.formTemplate.isOpen = body.is_open;
return delay<FormTemplateRead>({
edition_id: state.edition.id,
is_open: state.formTemplate.isOpen,
fields: state.formTemplate.fields,
});
},
getPublicConfig: (): Promise<PublicFormConfig> => {
const fields = state.formTemplate.fields;
return delay({
is_open: state.formTemplate.isOpen,
fields,
positions: fields.includes('POSITION_WISHES')
? state.positions.map((p) => ({ id: p.id, name: p.name }))
: [],
artists: fields.includes('ARTIST_WISHES')
? state.artists.map((a) => ({
id: a.id,
name: a.name,
performance_date: a.performance_date,
}))
: [],
});
},
submitPublic: async (_edition, body: PublicFormSubmission) => {
if (!state.formTemplate.isOpen) throw new ApiError(422, 'form.closed');
if (!body.hcaptcha_token) throw new ApiError(422, 'form.captcha_failed');
if (!body.first_name.trim() || !body.last_name.trim()) {
throw new ApiError(422, 'import.row.missing_required_field');
}
const fields = new Set(state.formTemplate.fields);
const positionIds = fields.has('POSITION_WISHES') ? (body.position_wish_ids ?? []) : [];
if (positionIds.length > 2) throw new ApiError(422, 'form.too_many_position_wishes');
const artistIds = fields.has('ARTIST_WISHES') ? (body.artist_wish_ids ?? []) : [];
const artistDates = artistIds.map(
(id) => state.artists.find((a) => a.id === id)?.performance_date,
);
if (new Set(artistDates).size !== artistDates.length) {
throw new ApiError(422, 'form.too_many_artists_same_day');
}
const now = touch();
const volunteer: VolunteerRead = {
id: `v${state.seq++}`,
edition_id: state.edition.id,
first_name: titleCase(body.first_name.trim()),
last_name: titleCase(body.last_name.trim()),
email: fields.has('EMAIL') ? body.email?.trim() || null : null,
phone: fields.has('PHONE') ? body.phone?.trim() || null : null,
comment: fields.has('COMMENT') ? body.comment?.trim() || null : null,
artist_ids: resolveWishes(state.artists, artistIds, 'artist.unknown'),
wished_position_ids: resolveWishes(state.positions, positionIds, 'position.unknown'),
wished_companion_ids: [],
has_photo: false,
companion_wish_note: fields.has('COMPANION_WISH')
? body.companion_wish_note?.trim() || null
: null,
self_declared_available: fields.has('AVAILABLE') ? Boolean(body.available) : false,
willing_to_pay_fee: fields.has('WILLING_TO_PAY_FEE')
? Boolean(body.willing_to_pay_fee)
: false,
created_at: now,
updated_at: now,
};
if (fields.has('PHOTO') && body.photo) {
volunteer.has_photo = true;
state.photos.set(volunteer.id, await fileToDataUrl(body.photo));
}
state.volunteers.push(volunteer);
state.availability.set(volunteer.id, []);
return delay<FormSubmissionResult>({ volunteer_id: volunteer.id });
},
},
solver: {
run: () => delay(runSolver()),
},
+78
View File
@@ -108,6 +108,11 @@ export interface VolunteerRead {
wished_position_ids: string[];
/** Vœux : bénévoles avec qui il voudrait être affecté (0 à N, à sens unique). */
wished_companion_ids: string[];
/** Renseignés par le formulaire public d'inscription (voir schema forms). */
has_photo: boolean;
companion_wish_note: string | null;
self_declared_available: boolean;
willing_to_pay_fee: boolean;
created_at: string;
updated_at: string;
}
@@ -133,6 +138,9 @@ export interface VolunteerUpdate {
artist_ids?: string[] | null;
wished_position_ids?: string[] | null;
wished_companion_ids?: string[] | null;
companion_wish_note?: string | null;
self_declared_available?: boolean | null;
willing_to_pay_fee?: boolean | null;
}
/**
@@ -532,3 +540,73 @@ export interface PlanningNotificationResult {
skipped_no_email: number;
recipients: string[];
}
// --------------------------------------------------------------------------- //
// Formulaire public d'inscription //
// --------------------------------------------------------------------------- //
// Nom/prénom toujours collectés, pas dans cette liste (voir app/api/forms.py).
export type FormFieldType =
| 'EMAIL'
| 'PHONE'
| 'POSITION_WISHES'
| 'ARTIST_WISHES'
| 'COMPANION_WISH'
| 'AVAILABLE'
| 'WILLING_TO_PAY_FEE'
| 'PHOTO'
| 'COMMENT';
export interface FormFieldsSet {
fields: FormFieldType[];
}
export interface FormTemplateRead {
edition_id: string;
is_open: boolean;
fields: FormFieldType[];
}
export interface FormTemplateUpdate {
is_open: boolean;
}
export interface PublicPositionOption {
id: string;
name: string;
}
export interface PublicArtistOption {
id: string;
name: string;
performance_date: string;
}
/** Tout ce qu'il faut pour afficher le formulaire public — jamais plus. */
export interface PublicFormConfig {
is_open: boolean;
fields: FormFieldType[];
positions: PublicPositionOption[];
artists: PublicArtistOption[];
}
export interface FormSubmissionResult {
volunteer_id: string;
}
/** Champs du formulaire public — envoyés en `multipart/form-data` (photo
* possible). `position_wish_ids`/`artist_wish_ids` : JSON stringifié
* (`'["id1","id2"]'`), pas de tableau natif possible en multipart. */
export interface PublicFormSubmission {
first_name: string;
last_name: string;
hcaptcha_token: string;
email?: string;
phone?: string;
comment?: string;
companion_wish_note?: string;
available?: boolean;
willing_to_pay_fee?: boolean;
position_wish_ids?: string[];
artist_wish_ids?: string[];
photo?: File | null;
}
+17
View File
@@ -23,6 +23,10 @@ import type {
DayPartUpdate,
EditionRead,
EditionUpdate,
FormFieldsSet,
FormSubmissionResult,
FormTemplateRead,
FormTemplateUpdate,
GenerateShiftsResult,
ImportAnalyzeResponse,
ImportMapping,
@@ -35,6 +39,8 @@ import type {
PositionCreate,
PositionRead,
PositionUpdate,
PublicFormConfig,
PublicFormSubmission,
ShiftCreate,
ShiftRead,
ShiftUpdate,
@@ -77,6 +83,8 @@ export interface PlanningApi {
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[]>;
/** Photo transmise via le formulaire public, `null` si absente. */
photoBlob(editionId: string, id: string): Promise<Blob | null>;
};
accounts: {
/** Comptes de connexion (mot de passe ou lien magique) de l'édition. */
@@ -153,6 +161,15 @@ export interface PlanningApi {
/** Génère la planche PDF (recto personnalisé + verso fixe). */
generate(editionId: string, body: BadgeGenerateRequest): Promise<Blob>;
};
forms: {
/** Configuration (COORDINATION uniquement). */
getTemplate(editionId: string): Promise<FormTemplateRead>;
setFields(editionId: string, body: FormFieldsSet): Promise<FormTemplateRead>;
setOpen(editionId: string, body: FormTemplateUpdate): Promise<FormTemplateRead>;
/** Publics — aucune authentification, utilisables sans compte connecté. */
getPublicConfig(editionId: string): Promise<PublicFormConfig>;
submitPublic(editionId: string, body: PublicFormSubmission): Promise<FormSubmissionResult>;
};
solver: {
/** Calcule des suggestions (CP-SAT) ; ne persiste jamais d'affectation. */
run(editionId: string): Promise<SolverRunResult>;