MonEspacePro/pro/app/team.tsx

210 lines
9.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useCallback, useState } from 'react';
import { Alert, Pressable, ScrollView, Share, TextInput, View } from 'react-native';
import { useFocusEffect } from 'expo-router';
import { api } from '../src/api';
import { describe } from '../src/errors';
import { useSession } from '../src/session';
import { Banner, Button, Card, T } from '../src/ui';
import { font, useColors } from '../src/theme';
type Role = 'MANAGER' | 'EMPLOYEE';
interface Member {
id: string;
email: string;
displayName: string;
role: Role;
active: boolean;
provisionalPassword?: string;
}
const ROLE: Record<Role, [string, string]> = {
EMPLOYEE: ['Employé', 'Scanne les cartes et crédite les points'],
MANAGER: ['Dirigeant', 'Toute la configuration : modules, campagnes, employés, statistiques'],
};
/** Employés du magasin (Dirigeant) : création avec rôle, désactivation, nouveau mot de passe. */
export default function Team() {
const c = useColors();
const { me } = useSession();
const [list, setList] = useState<Member[] | null>(null);
const [error, setError] = useState<string | null>(null);
const [adding, setAdding] = useState(false);
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [role, setRole] = useState<Role>('EMPLOYEE');
const [busy, setBusy] = useState(false);
const [created, setCreated] = useState<Member | null>(null);
const load = useCallback(async () => {
try {
setList(await api.get<Member[]>('/api/staff/team'));
} catch (e) {
setError(describe(e).detail);
}
}, []);
useFocusEffect(
useCallback(() => {
load();
}, [load]),
);
async function run(fn: () => Promise<unknown>) {
setError(null);
try {
await fn();
await load();
} catch (e) {
setError(describe(e).detail);
}
}
async function create() {
setBusy(true);
setCreated(null);
await run(async () => {
setCreated(await api.post<Member>('/api/staff/team', { displayName: name.trim(), email: email.trim(), role }));
setName('');
setEmail('');
setRole('EMPLOYEE');
setAdding(false);
});
setBusy(false);
}
/** Actions d'un compte, regroupées dans un menu pour garder la liste lisible. */
function actions(m: Member) {
Alert.alert(m.displayName, m.email, [
{
text: m.role === 'MANAGER' ? 'Passer Employé' : 'Passer Dirigeant',
onPress: () => run(() => api.patch(`/api/staff/team/${m.id}`, { role: m.role === 'MANAGER' ? 'EMPLOYEE' : 'MANAGER' })),
},
{
text: 'Nouveau mot de passe',
onPress: () => run(async () => setCreated(await api.post<Member>(`/api/staff/team/${m.id}/reset-password`))),
},
{
text: m.active ? 'Désactiver le compte' : 'Réactiver le compte',
style: m.active ? 'destructive' : 'default',
onPress: () => run(() => api.patch(`/api/staff/team/${m.id}`, { active: !m.active })),
},
{ text: 'Supprimer le compte', style: 'destructive', onPress: () => confirmRemove(m) },
{ text: 'Annuler', style: 'cancel' },
]);
}
/** Suppression définitive : le compte est anonymisé, ses opérations restent dans l'historique. */
function confirmRemove(m: Member) {
Alert.alert(
`Supprimer le compte de ${m.displayName} ?`,
'Suppression définitive : la personne ne pourra plus se connecter et son nom et son e-mail sont effacés. Ses opérations restent dans l’historique sous le nom « Employé supprimé ».',
[
{ text: 'Annuler', style: 'cancel' },
{ text: 'Supprimer', style: 'destructive', onPress: () => run(() => api.del(`/api/staff/team/${m.id}`)) },
],
);
}
const input = { borderWidth: 1, borderColor: c.border, borderRadius: 14, padding: 14, backgroundColor: c.bg, color: c.text, fontFamily: font.regular, fontSize: 16 } as const;
const activeCount = list?.filter((m) => m.active).length ?? 0;
const sorted = [...(list ?? [])].sort((a, b) => Number(b.active) - Number(a.active) || a.role.localeCompare(b.role) || a.displayName.localeCompare(b.displayName));
return (
<ScrollView contentContainerStyle={{ padding: 20, gap: 16 }} keyboardShouldPersistTaps="handled" bounces={false} overScrollMode="never">
{error && <Banner tone="error">{error}</Banner>}
{/* Identifiants à transmettre (création ou nouveau mot de passe) */}
{created?.provisionalPassword && (
<View style={{ backgroundColor: c.okBg, borderRadius: 20, padding: 18, gap: 10 }}>
<T v="label" style={{ color: c.ok }}>✓ Identifiants de {created.displayName}</T>
<View style={{ backgroundColor: c.surface, borderRadius: 14, padding: 14, gap: 4 }}>
<T v="muted" style={{ fontSize: 13 }}>Identifiant</T>
<T v="label" selectable>{created.email}</T>
<T v="muted" style={{ fontSize: 13, marginTop: 6 }}>Mot de passe provisoire</T>
<T style={{ fontFamily: font.extrabold, fontSize: 24, letterSpacing: 1.5 }} selectable>{created.provisionalPassword}</T>
</View>
<T v="muted" style={{ fontSize: 13 }}>Il ne sera plus affiché ensuite : transmettez-le maintenant.</T>
<Button
label="Partager les identifiants"
onPress={() => Share.share({ message: `MonEspacePro\nIdentifiant : ${created.email}\nMot de passe : ${created.provisionalPassword}` })}
/>
</View>
)}
{/* Nouveau compte : formulaire déplié à la demande */}
{adding ? (
<Card style={{ gap: 12 }}>
<T v="h2">Nouvel employé</T>
<TextInput value={name} onChangeText={setName} placeholder="Prénom Nom" placeholderTextColor={c.text3} accessibilityLabel="Prénom et nom" style={input} maxLength={80} />
<TextInput
value={email}
onChangeText={setEmail}
placeholder="prenom@exemple.fr"
placeholderTextColor={c.text3}
accessibilityLabel="E-mail"
autoCapitalize="none"
autoCorrect={false}
keyboardType="email-address"
style={input}
/>
<T v="label">Rôle</T>
{(['EMPLOYEE', 'MANAGER'] as const).map((r) => (
<Pressable key={r} accessibilityRole="radio" accessibilityState={{ checked: role === r }} onPress={() => setRole(r)}>
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 12, padding: 14, borderRadius: 14, borderWidth: 2, borderColor: role === r ? c.primary : c.border, backgroundColor: role === r ? c.primarySoft : c.surface }}>
<View style={{ width: 22, height: 22, borderRadius: 11, borderWidth: 2, borderColor: role === r ? c.primary : c.border, alignItems: 'center', justifyContent: 'center' }}>
{role === r && <View style={{ width: 10, height: 10, borderRadius: 5, backgroundColor: c.primary }} />}
</View>
<View style={{ flex: 1 }}>
<T v="label">{ROLE[r][0]}</T>
<T v="muted" style={{ fontSize: 13 }}>{ROLE[r][1]}</T>
</View>
</View>
</Pressable>
))}
<Button label="Créer le compte" onPress={create} loading={busy} disabled={name.trim().length < 2 || !email.includes('@')} />
<Button label="Annuler" variant="secondary" onPress={() => setAdding(false)} />
</Card>
) : (
<Button label="+ Nouvel employé" onPress={() => setAdding(true)} />
)}
{/* Comptes */}
{list && (
<T v="label" style={{ color: c.text3, marginTop: 4 }}>
{activeCount} compte{activeCount > 1 ? 's' : ''} actif{activeCount > 1 ? 's' : ''}
</T>
)}
{sorted.map((m) => {
const self = m.id === me?.id;
return (
<Pressable key={m.id} accessibilityRole="button" disabled={self} onPress={() => actions(m)}>
{({ pressed }) => (
<Card style={{ padding: 14, flexDirection: 'row', alignItems: 'center', gap: 12, opacity: pressed ? 0.7 : m.active ? 1 : 0.55 }}>
<View style={{ width: 46, height: 46, borderRadius: 23, backgroundColor: m.role === 'MANAGER' ? c.primarySoft : c.surface2, alignItems: 'center', justifyContent: 'center' }}>
<T style={{ fontFamily: font.extrabold, fontSize: 18, color: m.role === 'MANAGER' ? c.primary : c.text3 }}>{m.displayName.charAt(0).toUpperCase()}</T>
</View>
<View style={{ flex: 1, gap: 2 }}>
<T v="label" numberOfLines={1}>
{m.displayName}
{self ? ' (vous)' : ''}
</T>
<T v="muted" style={{ fontSize: 13 }} numberOfLines={1}>{m.email}</T>
<View style={{ flexDirection: 'row', gap: 6, marginTop: 2 }}>
<View style={{ paddingHorizontal: 8, paddingVertical: 2, borderRadius: 999, backgroundColor: m.role === 'MANAGER' ? c.primarySoft : c.surface2 }}>
<T style={{ fontSize: 12, fontFamily: font.semibold, color: m.role === 'MANAGER' ? c.primary : c.text3 }}>{ROLE[m.role][0]}</T>
</View>
{!m.active && (
<View style={{ paddingHorizontal: 8, paddingVertical: 2, borderRadius: 999, backgroundColor: c.errBg }}>
<T style={{ fontSize: 12, fontFamily: font.semibold, color: c.err }}>Désactivé</T>
</View>
)}
</View>
</View>
{!self && <T style={{ color: c.text3, fontSize: 22 }}>⋯</T>}
</Card>
)}
</Pressable>
);
})}
</ScrollView>
);
}