MonEspacePro/pro/app/team.tsx

242 lines
11 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, 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 { smooth, Banner, Button, Card, T } from '../src/ui';
import { font, useColors } from '../src/theme';
import { Icon } from '../src/icons';
import { confirmIdentity } from '../src/biometrics';
type Role = 'MANAGER' | 'EMPLOYEE';
interface Member {
id: string;
email: string;
displayName: string;
role: Role;
active: boolean;
/** Adresse à laquelle le lien de création du mot de passe a été envoyé. */
invitationSentTo?: string | null;
}
/** Invitation envoyée : affichée en haut de la liste. */
interface Notice {
name: string;
email: string;
reset: boolean;
/** Compte créé mais e-mail non envoyé. */
failed?: boolean;
}
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 [notice, setNotice] = useState<Notice | null>(null);
const load = useCallback(async () => {
try {
const l = await api.get<Member[]>('/api/staff/team');
smooth();
setList(l);
} catch (e) {
smooth();
setError(describe(e).detail);
}
}, []);
useFocusEffect(
useCallback(() => {
load();
}, [load]),
);
async function run(fn: () => Promise<unknown>) {
setError(null);
try {
await fn();
await load();
} catch (e) {
smooth();
setError(describe(e).detail);
}
}
async function create() {
setBusy(true);
smooth();
setNotice(null);
await run(async () => {
const m = await api.post<Member>('/api/staff/team', { displayName: name.trim(), email: email.trim(), role });
setNotice({ name: m.displayName, email: m.invitationSentTo ?? m.email, reset: false, failed: m.invitationSentTo === null });
setName('');
setEmail('');
setRole('EMPLOYEE');
smooth();
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: 'Envoyer un lien de mot de passe',
onPress: () =>
run(async () => {
const r = await api.post<{ invitationSentTo: string }>(`/api/staff/team/${m.id}/reset-password`);
setNotice({ name: m.displayName, email: r.invitationSentTo, reset: true });
}),
},
{
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: async () => {
if (await confirmIdentity(`Supprimer le compte de ${m.displayName}`)) 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>}
{/* Invitation envoyée (création du compte ou nouveau mot de passe) */}
{notice && (
<View style={{ backgroundColor: notice.failed ? c.warnBg : c.okBg, borderRadius: 20, padding: 18, gap: 10 }}>
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 6 }}>
<Icon name={notice.failed ? 'alert' : 'checkCircle'} size={18} color={notice.failed ? c.warn : c.ok} />
<T v="label" style={{ color: c.ok, flex: 1 }}>{notice.reset ? 'Lien envoyé' : `Compte de ${notice.name} créé`}</T>
</View>
<View style={{ backgroundColor: c.surface, borderRadius: 14, padding: 14, gap: 4 }}>
<T v="muted" style={{ fontSize: 13 }}>{notice.failed ? 'E-mail non envoyé à' : 'E-mail envoyé à'}</T>
<T v="label" selectable>{notice.email}</T>
</View>
{notice.failed ? (
<T v="muted" style={{ fontSize: 13 }}>Le compte est créé, mais l’e-mail n’a pas pu partir. Touchez {notice.name} dans la liste, puis « Envoyer un lien de mot de passe ».</T>
) : (
<T v="muted" style={{ fontSize: 13 }}>
{notice.name} y trouvera un lien pour choisir {notice.reset ? 'un nouveau' : 'son'} mot de passe (valable 7 jours, utilisable une fois), puis se connectera à l’app avec cette adresse. Rien reçu ? Vérifiez les indésirables, ou renvoyez un lien depuis la liste.
</T>
)}
</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={() => { smooth(); setAdding(false); }} />
</Card>
) : (
<Button label="+ Nouvel employé" onPress={() => { smooth(); 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>
);
}