201 lines
9.5 KiB
TypeScript
201 lines
9.5 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 [sent, setSent] = useState<{ name: string; email: string | null; reset: boolean } | null>(null);
|
||
const formDialog = useRef<HTMLDialogElement>(null);
|
||
const sentDialog = useRef<HTMLDialogElement>(null);
|
||
|
||
const reload = useCallback(() => {
|
||
api.get<StaffUser[]>(base).then(setStaff).catch((e) => setError(e.message));
|
||
}, [base]);
|
||
useEffect(reload, [reload]);
|
||
|
||
/** Invitation envoyée par e-mail (création ou nouveau mot de passe). */
|
||
function showSent(name: string, email: string | null, reset: boolean) {
|
||
setSent({ name, email, reset });
|
||
sentDialog.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(`Envoyer à ${u.displayName} (${u.email}) un lien pour choisir un nouveau mot de passe ?`)) return;
|
||
try {
|
||
const r = await api.post<{ invitationSentTo: string }>(`${base}/${u.id}/reset-password`);
|
||
showSent(u.displayName, r.invitationSentTo, true);
|
||
} catch (e) {
|
||
setError((e as Error).message);
|
||
}
|
||
}
|
||
|
||
async function switchRole(u: StaffUser) {
|
||
const next: StaffRole = u.role === 'MANAGER' ? 'EMPLOYEE' : 'MANAGER';
|
||
if (!window.confirm(`${u.displayName} devient ${ROLE_LABEL[next]}. Ses sessions ouvertes seront fermées.`)) return;
|
||
try {
|
||
await api.patch(`${base}/${u.id}`, { role: next });
|
||
reload();
|
||
} catch (e) {
|
||
setError((e as Error).message);
|
||
}
|
||
}
|
||
|
||
const active = staff.filter((u) => u.active);
|
||
const managers = active.filter((u) => u.role === 'MANAGER').length;
|
||
// Actifs d'abord, Dirigeants en tête.
|
||
const sorted = [...staff].sort((a, b) => Number(b.active) - Number(a.active) || a.role.localeCompare(b.role) || a.displayName.localeCompare(b.displayName));
|
||
|
||
return (
|
||
<>
|
||
<div className="row between">
|
||
<div>
|
||
<h2>Employés</h2>
|
||
<p className="muted" style={{ margin: 0 }}>
|
||
{active.length} compte{active.length > 1 ? 's' : ''} actif{active.length > 1 ? 's' : ''} · {managers} dirigeant{managers > 1 ? 's' : ''}
|
||
</p>
|
||
</div>
|
||
<button className="btn" onClick={() => formDialog.current?.showModal()}>+ Nouvel employé</button>
|
||
</div>
|
||
{error && <div className="alert error" role="alert">{error}</div>}
|
||
{staff.length > 0 && managers === 0 && (
|
||
<div className="alert warn">Aucun Dirigeant actif : personne ne peut configurer le magasin depuis l’app. Créez un compte Dirigeant ou changez le rôle d’un employé.</div>
|
||
)}
|
||
|
||
{staff.length === 0 ? (
|
||
<section className="card" style={{ textAlign: 'center', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12, padding: 40 }}>
|
||
<span className="staff-avatar big" aria-hidden="true">👥</span>
|
||
<h3 style={{ margin: 0 }}>Aucun compte pour l’instant</h3>
|
||
<p className="muted" style={{ margin: 0, maxWidth: 420 }}>Créez au moins un Dirigeant : il pourra ensuite ajouter lui-même son équipe depuis l’app MonEspacePro.</p>
|
||
<button className="btn" onClick={() => formDialog.current?.showModal()}>Créer le premier compte</button>
|
||
</section>
|
||
) : (
|
||
<div className="staff-grid">
|
||
{sorted.map((u) => (
|
||
<article key={u.id} className={`card staff-card${u.active ? '' : ' off'}`}>
|
||
<div className="row" style={{ gap: 12, flexWrap: 'nowrap' }}>
|
||
<span className={`staff-avatar${u.role === 'MANAGER' ? ' mgr' : ''}`} aria-hidden="true">{u.displayName.charAt(0).toUpperCase()}</span>
|
||
<div style={{ minWidth: 0 }}>
|
||
<strong style={{ display: 'block', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{u.displayName}</strong>
|
||
<span className="muted" style={{ fontSize: 14, display: 'block', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{u.email}</span>
|
||
</div>
|
||
</div>
|
||
<div className="row" style={{ gap: 6 }}>
|
||
<span className={`role-pill${u.role === 'MANAGER' ? ' mgr' : ''}`}>{ROLE_LABEL[u.role]}</span>
|
||
{u.active ? <span className="badge ACTIVE">Actif</span> : <span className="badge DRAFT">Désactivé</span>}
|
||
<span className="muted" style={{ fontSize: 13 }}>depuis le {new Date(u.createdAt).toLocaleDateString('fr-FR', { day: 'numeric', month: 'short', year: 'numeric' })}</span>
|
||
</div>
|
||
<div className="row" style={{ gap: 8 }}>
|
||
<button className="btn secondary small" onClick={() => switchRole(u)}>{u.role === 'MANAGER' ? 'Passer Employé' : 'Passer Dirigeant'}</button>
|
||
<button className="btn secondary small" onClick={() => reset(u)}>Envoyer un lien de mot de passe</button>
|
||
<button className="btn secondary small" onClick={() => toggle(u)}>{u.active ? 'Désactiver' : 'Réactiver'}</button>
|
||
</div>
|
||
</article>
|
||
))}
|
||
</div>
|
||
)}
|
||
|
||
<dialog ref={formDialog} aria-labelledby="new-staff-title">
|
||
<NewStaffForm
|
||
base={base}
|
||
onCancel={() => formDialog.current?.close()}
|
||
onCreated={(u) => {
|
||
formDialog.current?.close();
|
||
showSent(u.displayName, u.invitationSentTo ?? null, false);
|
||
}}
|
||
/>
|
||
</dialog>
|
||
|
||
<dialog ref={sentDialog} aria-labelledby="sent-title">
|
||
<div className="dialog-body">
|
||
<h2 id="sent-title">{sent?.email ? (sent.reset ? 'Lien envoyé' : 'Compte créé') : 'Compte créé, e-mail non envoyé'}</h2>
|
||
{sent?.email ? (
|
||
<p style={{ margin: 0 }}>
|
||
<strong>{sent.name}</strong> a reçu à <strong>{sent.email}</strong> un lien pour choisir {sent.reset ? 'un nouveau' : 'son'} mot de passe (valable 7 jours, utilisable une fois).
|
||
</p>
|
||
) : (
|
||
<div className="alert warn" style={{ margin: 0 }}>
|
||
L’e-mail d’invitation n’a pas pu partir. Utilisez « Envoyer un lien de mot de passe » sur la fiche de {sent?.name} pour réessayer.
|
||
</div>
|
||
)}
|
||
<div className="row" style={{ justifyContent: 'flex-end' }}>
|
||
<button className="btn" onClick={() => sentDialog.current?.close()}>OK</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 }}>La personne recevra un e-mail pour choisir son mot de passe.</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>
|
||
);
|
||
}
|