Frontend : connexion (mot de passe + lien magique) et onglets par rôle
Authentification alignée sur le back-end (Étapes 7/8) : - src/api : schema auth (AccountRead, TokenResponse…), session.ts (jeton Bearer partagé + callback 401), méthodes auth du client HTTP (POST .../auth/login, .../auth/magic-link, .../auth/verify, GET /auth/me) et du mock (comptes coordination + référents + bénévoles, tokens magiques, sessions). - src/auth : AuthProvider/useAuth (jeton en localStorage, réhydratation via /auth/me, déconnexion sur 401), RequireAuth (garde + contrôle de rôle), HomeRedirect, table ROUTE_ROLES. - Pages : /connexion (lien magique, avec lien de démo affiché en mode mock), /connexion/coordination (email + mot de passe). - Router : toutes les routes métier passées derrière <RequireAuth> ; redirection vers l'accueil du rôle. - AppShell : onglets filtrés par rôle (01/02/03/06 coordination, 04 bénévole, 05 référent), email + rôle + bouton Déconnexion. - Mobile bénévole : cible le bénévole du compte connecté ; dégradation propre quand l'API refuse le détail des créneaux à un bénévole. - Mobile référent : cible le poste dont le compte est référent. - i18n : clés auth / rôles. - Vérifs : build tsc + vite, eslint (0 problème), npm run smoke (flux login / lien magique + rendu des 6 écrans par rôle et des pages publiques). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AwswqSChc3Rwtu61pRXiY2
This commit is contained in:
co-authored by
Claude Sonnet 5
parent
464635656a
commit
6e16db4b7e
@@ -1,6 +1,7 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
|
||||
import { useAssignments, usePositions, useShifts, useVolunteers } from '@/api/hooks';
|
||||
import { useAuth } from '@/auth/auth-context';
|
||||
import { ErrorNote, Loading } from '@/components/state';
|
||||
import { DesignNote, PhoneFrame } from '@/pages/mobile/PhoneFrame';
|
||||
import { hourRangeLabel } from '@/lib/time';
|
||||
@@ -11,13 +12,17 @@ import { cx } from '@/lib/cx';
|
||||
type Presence = Record<string, 'present' | 'absent'>;
|
||||
|
||||
export function MobileLeadPage() {
|
||||
const { account } = useAuth();
|
||||
const positions = usePositions();
|
||||
const shifts = useShifts();
|
||||
const volunteers = useVolunteers();
|
||||
const [presence, setPresence] = useState<Presence>({});
|
||||
|
||||
// Poste de démonstration : le premier ; créneau le plus fourni.
|
||||
const position = (positions.data ?? [])[0];
|
||||
// Poste du référent connecté (repli : le premier, pour la démo coordination).
|
||||
const myPositions = (positions.data ?? []).filter(
|
||||
(p) => account && p.lead_account_id === account.id,
|
||||
);
|
||||
const position = myPositions[0] ?? (positions.data ?? [])[0];
|
||||
const positionShifts = useMemo(
|
||||
() => (shifts.data ?? []).filter((s) => s.position_id === position?.id),
|
||||
[shifts.data, position?.id],
|
||||
|
||||
@@ -1,26 +1,30 @@
|
||||
import { useMemo } from 'react';
|
||||
|
||||
import { useAssignments, usePositions, useShifts, useUpdateAssignment, useVolunteers } from '@/api/hooks';
|
||||
import { ApiError } from '@/api';
|
||||
import {
|
||||
useAssignments,
|
||||
usePositions,
|
||||
useShifts,
|
||||
useUpdateAssignment,
|
||||
useVolunteer,
|
||||
} from '@/api/hooks';
|
||||
import { useAuth } from '@/auth/auth-context';
|
||||
import { ErrorNote, Loading } from '@/components/state';
|
||||
import { DesignNote, PhoneFrame } from '@/pages/mobile/PhoneFrame';
|
||||
import { hourRangeLabel, hoursBetween, longDayLabel, naiveMinutes } from '@/lib/time';
|
||||
import { isActive } from '@/lib/planning';
|
||||
import { ENV } from '@/lib/env';
|
||||
import { t } from '@/i18n';
|
||||
|
||||
const DEMO_VOLUNTEER_ID = ENV.demoVolunteerId;
|
||||
|
||||
export function MobileVolunteerPage() {
|
||||
const volunteers = useVolunteers();
|
||||
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 me = useMemo(() => {
|
||||
const list = volunteers.data ?? [];
|
||||
return list.find((v) => v.id === DEMO_VOLUNTEER_ID) ?? list[0];
|
||||
}, [volunteers.data]);
|
||||
|
||||
const assignments = useAssignments(me ? { volunteerId: me.id } : undefined);
|
||||
const updateAssignment = useUpdateAssignment();
|
||||
|
||||
const shiftsById = useMemo(
|
||||
@@ -32,22 +36,39 @@ export function MobileVolunteerPage() {
|
||||
[positions.data],
|
||||
);
|
||||
|
||||
if (volunteers.isLoading || shifts.isLoading) return <Loading />;
|
||||
const error = volunteers.error ?? shifts.error ?? assignments.error;
|
||||
if (error) return <ErrorNote error={error} />;
|
||||
if (!me) return null;
|
||||
if (!volunteerId) {
|
||||
return (
|
||||
<div className="m-6 max-w-[560px] border-[3px] border-dashed border-ink bg-paper p-4 font-display text-[13px] font-bold">
|
||||
{t('mobileVol.noAccount')}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (assignments.isLoading) return <Loading />;
|
||||
if (assignments.error) return <ErrorNote error={assignments.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 ?? [])
|
||||
.filter(isActive)
|
||||
.map((a) => ({ assignment: a, shift: shiftsById.get(a.shift_id) }))
|
||||
.filter((entry): entry is { assignment: typeof entry.assignment; shift: NonNullable<typeof entry.shift> } =>
|
||||
Boolean(entry.shift),
|
||||
)
|
||||
.sort((a, b) => naiveMinutes(a.shift.starts_at) - naiveMinutes(b.shift.starts_at));
|
||||
.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 + hoursBetween(s.shift.starts_at, s.shift.ends_at), 0) * 10,
|
||||
) / 10;
|
||||
const totalHours =
|
||||
Math.round(
|
||||
slots.reduce(
|
||||
(sum, s) => sum + (s.shift ? hoursBetween(s.shift.starts_at, s.shift.ends_at) : 0),
|
||||
0,
|
||||
) * 10,
|
||||
) / 10;
|
||||
const toConfirm = slots.filter((s) => s.assignment.status !== 'CONFIRMED').length;
|
||||
|
||||
return (
|
||||
@@ -56,15 +77,17 @@ export function MobileVolunteerPage() {
|
||||
<div className="bg-ink px-4 pb-4 pt-3 text-cream">
|
||||
<div className="font-mono text-[10px] text-yellow">{t('mobileVol.kicker')}</div>
|
||||
<div className="mt-[5px] font-display text-[30px] font-black leading-tight tracking-tight">
|
||||
{t('mobileVol.greeting', { name: me.first_name.toUpperCase() })}
|
||||
{t('mobileVol.greeting', { name: firstName.toUpperCase() })}
|
||||
</div>
|
||||
<div className="mt-3 flex gap-2">
|
||||
<div className="bg-yellow px-[9px] py-[7px] font-display text-[12px] font-extrabold text-ink">
|
||||
{t('mobileVol.slots', { count: slots.length })}
|
||||
</div>
|
||||
<div className="border-2 border-cream px-[9px] py-[6px] font-display text-[12px] font-extrabold">
|
||||
{t('mobileVol.hours', { count: totalHours })}
|
||||
</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>
|
||||
</div>
|
||||
|
||||
@@ -75,22 +98,31 @@ export function MobileVolunteerPage() {
|
||||
) : null}
|
||||
|
||||
<div className="flex flex-col gap-[14px] px-[14px] pb-[26px] pt-[14px]">
|
||||
{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 = positionsById.get(shift.position_id);
|
||||
const position = shift ? positionsById.get(shift.position_id) : undefined;
|
||||
return (
|
||||
<div key={assignment.id} 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(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>
|
||||
<div className="p-[11px]">
|
||||
<div className="font-display text-[23px] font-black leading-tight tracking-tight">
|
||||
{(position?.name ?? '').toUpperCase()}
|
||||
{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}
|
||||
<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 })}
|
||||
@@ -112,6 +144,12 @@ export function MobileVolunteerPage() {
|
||||
{t('mobileVol.confirm')}
|
||||
</button>
|
||||
)}
|
||||
{updateAssignment.error instanceof ApiError &&
|
||||
updateAssignment.variables?.id === assignment.id ? (
|
||||
<div className="mt-2 border-2 border-ink bg-orange px-2 py-1 font-display text-[10px] font-bold">
|
||||
{t(updateAssignment.error.code)}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import { useState, type FormEvent } from 'react';
|
||||
import { Link, Navigate, useLocation, useNavigate } from 'react-router-dom';
|
||||
|
||||
import { API_MODE, ApiError, DEMO_COORDINATOR_EMAIL, DEMO_COORDINATOR_PASSWORD } from '@/api';
|
||||
import { useAuth } from '@/auth/auth-context';
|
||||
import { homePath } from '@/auth/roles';
|
||||
import { FieldLabel } from '@/components/ui';
|
||||
import { AuthLayout } from './AuthLayout';
|
||||
import { t } from '@/i18n';
|
||||
|
||||
export function AdminLoginPage() {
|
||||
const { status, account, loginWithPassword } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation() as { state?: { from?: string } };
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
if (status === 'authed' && account) {
|
||||
return <Navigate to={location.state?.from ?? homePath(account.role)} replace />;
|
||||
}
|
||||
|
||||
async function submit(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
setBusy(true);
|
||||
try {
|
||||
const me = await loginWithPassword(email.trim(), password);
|
||||
navigate(location.state?.from ?? homePath(me.role), { replace: true });
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.code : 'error.generic');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<AuthLayout title={t('auth.admin.title')}>
|
||||
<form onSubmit={submit} className="flex flex-col gap-3">
|
||||
<label className="block">
|
||||
<FieldLabel>{t('auth.email')}</FieldLabel>
|
||||
<input
|
||||
type="email"
|
||||
autoComplete="username"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
className="w-full border-2 border-ink bg-cream p-[10px] font-mono text-[13px]"
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
<FieldLabel>{t('auth.password')}</FieldLabel>
|
||||
<input
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
className="w-full border-2 border-ink bg-cream p-[10px] font-mono text-[13px]"
|
||||
/>
|
||||
</label>
|
||||
|
||||
{error ? (
|
||||
<div className="border-2 border-ink bg-orange px-3 py-2 font-display text-[11px] font-bold">
|
||||
{t(error)}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={busy}
|
||||
className="mt-1 cursor-pointer border-[3px] border-ink bg-yellow p-3 font-display text-[13px] font-black uppercase tracking-wide shadow-brutal-md hover:bg-green hover:text-white disabled:opacity-60"
|
||||
>
|
||||
{busy ? t('auth.signingIn') : t('auth.signIn')}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
{API_MODE === 'mock' ? (
|
||||
<div className="mt-4 border-2 border-dashed border-ink bg-yellow-soft p-3 font-mono text-[10px] leading-relaxed">
|
||||
{t('auth.demoCredentials', {
|
||||
email: DEMO_COORDINATOR_EMAIL,
|
||||
password: DEMO_COORDINATOR_PASSWORD,
|
||||
})}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="mt-4 border-t-2 border-ink pt-3 font-display text-[11px]">
|
||||
{t('auth.notAdmin')}{' '}
|
||||
<Link to="/connexion" className="font-extrabold underline">
|
||||
{t('auth.magicLinkLink')}
|
||||
</Link>
|
||||
</div>
|
||||
</AuthLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
import { API_MODE } from '@/api';
|
||||
import { t } from '@/i18n';
|
||||
|
||||
export function AuthLayout({ title, children }: { title: string; children: ReactNode }) {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-cream p-6">
|
||||
<div className="w-full max-w-[420px]">
|
||||
<div className="mb-4 flex items-baseline gap-2">
|
||||
<div className="border-[3px] border-ink bg-yellow px-3 py-2 font-display text-[15px] font-black tracking-tight shadow-brutal-md">
|
||||
{t('header.title')}
|
||||
</div>
|
||||
{API_MODE === 'mock' ? (
|
||||
<span className="border-2 border-ink bg-blue px-2 py-1 font-display text-[9px] font-extrabold uppercase">
|
||||
{t('header.mockMode')}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="border-[3px] border-ink bg-paper shadow-brutal-lg">
|
||||
<div className="bg-ink px-4 py-3 font-display text-[13px] font-black uppercase tracking-widest text-cream">
|
||||
{title}
|
||||
</div>
|
||||
<div className="p-5">{children}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
import { useEffect, useRef, useState, type FormEvent } from 'react';
|
||||
import { Link, Navigate, useNavigate, useSearchParams } from 'react-router-dom';
|
||||
|
||||
import { ApiError, devMagicToken } from '@/api';
|
||||
import { useAuth } from '@/auth/auth-context';
|
||||
import { homePath } from '@/auth/roles';
|
||||
import { FieldLabel } from '@/components/ui';
|
||||
import { AuthLayout } from './AuthLayout';
|
||||
import { t } from '@/i18n';
|
||||
|
||||
export function ConnexionPage() {
|
||||
const { status, account, requestMagicLink, verifyMagicLink } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const [params] = useSearchParams();
|
||||
const tokenParam = params.get('token');
|
||||
|
||||
const [email, setEmail] = useState('');
|
||||
const [sent, setSent] = useState(false);
|
||||
const [devLink, setDevLink] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const verifyStartedRef = useRef(false);
|
||||
|
||||
// Consommation d'un lien magique (?token=…).
|
||||
useEffect(() => {
|
||||
if (!tokenParam || verifyStartedRef.current) return;
|
||||
verifyStartedRef.current = true;
|
||||
setBusy(true);
|
||||
verifyMagicLink(tokenParam)
|
||||
.then((me) => navigate(homePath(me.role), { replace: true }))
|
||||
.catch((err) => {
|
||||
setError(err instanceof ApiError ? err.code : 'auth.invalid_token');
|
||||
setBusy(false);
|
||||
});
|
||||
}, [tokenParam, verifyMagicLink, navigate]);
|
||||
|
||||
if (status === 'authed' && account && !tokenParam) {
|
||||
return <Navigate to={homePath(account.role)} replace />;
|
||||
}
|
||||
|
||||
if (tokenParam) {
|
||||
return (
|
||||
<AuthLayout title={t('auth.magic.verifyTitle')}>
|
||||
{error ? (
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="border-2 border-ink bg-orange px-3 py-2 font-display text-[12px] font-bold">
|
||||
{t(error)}
|
||||
</div>
|
||||
<Link
|
||||
to="/connexion"
|
||||
className="cursor-pointer border-[3px] border-ink bg-yellow p-3 text-center font-display text-[12px] font-black uppercase tracking-wide shadow-brutal-md hover:bg-green hover:text-white"
|
||||
>
|
||||
{t('auth.magic.retry')}
|
||||
</Link>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-3 font-mono text-[12px] uppercase tracking-widest opacity-70">
|
||||
<span className="h-4 w-4 animate-spin border-2 border-ink border-t-transparent" />
|
||||
{t('auth.magic.verifying')}
|
||||
</div>
|
||||
)}
|
||||
</AuthLayout>
|
||||
);
|
||||
}
|
||||
|
||||
async function submit(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
setBusy(true);
|
||||
try {
|
||||
await requestMagicLink(email.trim());
|
||||
setSent(true);
|
||||
const raw = devMagicToken(email.trim());
|
||||
setDevLink(raw ? `/connexion?token=${encodeURIComponent(raw)}` : null);
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.code : 'error.generic');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<AuthLayout title={t('auth.magic.title')}>
|
||||
{sent ? (
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="border-2 border-ink bg-green px-3 py-3 font-display text-[12px] font-bold text-white">
|
||||
{t('auth.magic.sent')}
|
||||
</div>
|
||||
{devLink ? (
|
||||
<div className="border-2 border-dashed border-ink bg-yellow-soft p-3 font-mono text-[10px] leading-relaxed">
|
||||
{t('auth.magic.devHint')}
|
||||
<Link to={devLink} className="mt-2 block break-all font-bold underline">
|
||||
{devLink}
|
||||
</Link>
|
||||
</div>
|
||||
) : null}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setSent(false);
|
||||
setDevLink(null);
|
||||
}}
|
||||
className="cursor-pointer border-2 border-ink bg-cream p-2 font-display text-[11px] font-extrabold uppercase hover:bg-yellow"
|
||||
>
|
||||
{t('auth.magic.another')}
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<form onSubmit={submit} className="flex flex-col gap-3">
|
||||
<p className="font-display text-[12px] leading-relaxed">{t('auth.magic.lead')}</p>
|
||||
<label className="block">
|
||||
<FieldLabel>{t('auth.email')}</FieldLabel>
|
||||
<input
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
className="w-full border-2 border-ink bg-cream p-[10px] font-mono text-[13px]"
|
||||
/>
|
||||
</label>
|
||||
{error ? (
|
||||
<div className="border-2 border-ink bg-orange px-3 py-2 font-display text-[11px] font-bold">
|
||||
{t(error)}
|
||||
</div>
|
||||
) : null}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={busy}
|
||||
className="mt-1 cursor-pointer border-[3px] border-ink bg-yellow p-3 font-display text-[13px] font-black uppercase tracking-wide shadow-brutal-md hover:bg-green hover:text-white disabled:opacity-60"
|
||||
>
|
||||
{busy ? t('auth.magic.sending') : t('auth.magic.send')}
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
|
||||
<div className="mt-4 border-t-2 border-ink pt-3 font-display text-[11px]">
|
||||
{t('auth.isAdmin')}{' '}
|
||||
<Link to="/connexion/coordination" className="font-extrabold underline">
|
||||
{t('auth.adminLink')}
|
||||
</Link>
|
||||
</div>
|
||||
</AuthLayout>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user