MonEspacePro/admin/src/pages/StaffTab.tsx
Tony AVERTY 226f3cedb8 Espace web du Dirigeant, inscription en ligne, employés et cadeaux dans l'app Pro
- Admin : /inscription (formule, magasin, mot de passe, paiement Stripe) et
  /espace (connexion Dirigeant, état de l'abonnement, conception de la carte)
- Admin : formule obligatoire à la création d'un magasin, plus d'essai gratuit,
  lien d'abonnement permanent, titre des campagnes
- App Pro : écran Employés (création avec rôle Employé / Dirigeant), Mon compte
  (mot de passe), titre des campagnes, remise des cadeaux en caisse, accueil
  avant la conception de la carte
- Site : boutons « Choisir » vers l'inscription, avec la périodicité choisie

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 11:52:09 +02:00

173 lines
7 KiB
TypeScript

import { FormEvent, useCallback, useEffect, useRef, useState } from 'react';
import { api, StaffRole, StaffUser } from '../api';
const ROLE_LABEL: Record<StaffRole, string> = { MANAGER: 'Dirigeant', EMPLOYEE: 'Employé' };
export function StaffTab({ storeId }: { storeId: string }) {
const base = `/api/admin/stores/${storeId}/staff`;
const [staff, setStaff] = useState<StaffUser[]>([]);
const [error, setError] = useState<string | null>(null);
const [created, setCreated] = useState<StaffUser | null>(null);
const formDialog = useRef<HTMLDialogElement>(null);
const passwordDialog = useRef<HTMLDialogElement>(null);
const reload = useCallback(() => {
api.get<StaffUser[]>(base).then(setStaff).catch((e) => setError(e.message));
}, [base]);
useEffect(reload, [reload]);
function showPassword(user: StaffUser) {
setCreated(user);
passwordDialog.current?.showModal();
reload();
}
async function toggle(u: StaffUser) {
try {
await api.patch(`${base}/${u.id}`, { active: !u.active });
reload();
} catch (e) {
setError((e as Error).message);
}
}
async function reset(u: StaffUser) {
if (!window.confirm(`Générer un nouveau mot de passe pour ${u.displayName} ? Ses sessions seront fermées.`)) return;
try {
showPassword(await api.post<StaffUser>(`${base}/${u.id}/reset-password`));
} catch (e) {
setError((e as Error).message);
}
}
return (
<>
<div className="row between">
<h2>Employés</h2>
<button className="btn" onClick={() => formDialog.current?.showModal()}>+ Nouvel employé</button>
</div>
{error && <div className="alert error" role="alert">{error}</div>}
<div className="table-wrap">
<div className="table-scroll">
<table style={{ minWidth: 720 }}>
<thead>
<tr>
<th scope="col" style={{ paddingLeft: 24 }}>Nom</th>
<th scope="col">E-mail</th>
<th scope="col">Rôle</th>
<th scope="col">Statut</th>
<th scope="col"><span className="sr-only">Actions</span></th>
</tr>
</thead>
<tbody>
{staff.map((u) => (
<tr key={u.id} style={{ opacity: u.active ? 1 : 0.6 }}>
<td style={{ paddingLeft: 24, fontWeight: 600 }}>{u.displayName}</td>
<td>{u.email}</td>
<td>{ROLE_LABEL[u.role]}</td>
<td>{u.active ? <span className="badge ACTIVE">Actif</span> : <span className="badge DRAFT">Désactivé</span>}</td>
<td style={{ textAlign: 'right', whiteSpace: 'nowrap' }}>
<button className="btn secondary small" onClick={() => reset(u)}>Nouveau mot de passe</button>{' '}
<button className="btn secondary small" onClick={() => toggle(u)}>{u.active ? 'Désactiver' : 'Réactiver'}</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
{staff.length === 0 && (
<p className="muted" style={{ padding: 24, margin: 0, textAlign: 'center' }}>
Aucun employé. Créez au moins un dirigeant pour que le magasin puisse utiliser l'app Pro.
</p>
)}
</div>
<dialog ref={formDialog} aria-labelledby="new-staff-title">
<NewStaffForm
base={base}
onCancel={() => formDialog.current?.close()}
onCreated={(u) => {
formDialog.current?.close();
showPassword(u);
}}
/>
</dialog>
<dialog ref={passwordDialog} aria-labelledby="pwd-title">
<div className="dialog-body">
<h2 id="pwd-title">Mot de passe provisoire</h2>
<p style={{ margin: 0 }}>
Communiquez-le à <strong>{created?.displayName}</strong> ({created?.email}). Il ne sera plus affiché ensuite.
</p>
<div className="password-box">{created?.provisionalPassword}</div>
<div className="row" style={{ justifyContent: 'flex-end' }}>
<button className="btn secondary" onClick={() => navigator.clipboard?.writeText(created?.provisionalPassword ?? '')}>Copier</button>
<button className="btn" onClick={() => passwordDialog.current?.close()}>J'ai noté le mot de passe</button>
</div>
</div>
</dialog>
</>
);
}
function NewStaffForm({ base, onCancel, onCreated }: { base: string; onCancel: () => void; onCreated: (u: StaffUser) => void }) {
const [displayName, setDisplayName] = useState('');
const [email, setEmail] = useState('');
const [role, setRole] = useState<StaffRole>('EMPLOYEE');
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
async function submit(e: FormEvent) {
e.preventDefault();
setBusy(true);
setError(null);
try {
onCreated(await api.post<StaffUser>(base, { displayName, email, role }));
setDisplayName('');
setEmail('');
setRole('EMPLOYEE');
} catch (err) {
setError((err as Error).message);
} finally {
setBusy(false);
}
}
return (
<form className="dialog-body" onSubmit={submit}>
<h2 id="new-staff-title">Nouvel employé</h2>
{error && <div className="alert error" role="alert">{error}</div>}
<div className="field">
<label htmlFor="staff-name">Prénom et nom *</label>
<input id="staff-name" className="input" required placeholder="Prénom Nom" value={displayName} onChange={(e) => setDisplayName(e.target.value)} />
</div>
<div className="field">
<label htmlFor="staff-email">E-mail *</label>
<input id="staff-email" className="input" type="email" required placeholder="prenom@exemple.fr" value={email} onChange={(e) => setEmail(e.target.value)} />
</div>
<fieldset style={{ border: 0, padding: 0, margin: 0 }} className="field">
<legend style={{ fontWeight: 600, marginBottom: 6 }}>Rôle *</legend>
<div className="mode-cards">
{(['EMPLOYEE', 'MANAGER'] as const).map((r) => (
<label key={r} className="mode-card">
<input type="radio" name="role" checked={role === r} onChange={() => setRole(r)} />
<span>
<strong>{ROLE_LABEL[r]}</strong>
<br />
<span className="muted" style={{ fontSize: 14 }}>
{r === 'MANAGER' ? 'Toute la configuration : carte, modules, campagnes, employés, statistiques' : 'Scanne les cartes et crédite les points, voit ses opérations'}
</span>
</span>
</label>
))}
</div>
</fieldset>
<p className="muted" style={{ margin: 0, fontSize: 14 }}>Un mot de passe provisoire sera généré à la création.</p>
<div className="row" style={{ justifyContent: 'flex-end' }}>
<button type="button" className="btn secondary" onClick={onCancel}>Annuler</button>
<button className="btn" disabled={busy}>Créer le compte</button>
</div>
</form>
);
}