feat(mui): migrate Users (Uživatelé) page onto MUI kit

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
BOHA
2026-06-06 21:42:08 +02:00
parent 55a2de3a04
commit 094c190ae1

View File

@@ -1,18 +1,32 @@
import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { motion } from "framer-motion";
import Avatar from "@mui/material/Avatar";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import IconButton from "@mui/material/IconButton";
import { useAuth } from "../context/AuthContext";
import { useAlert } from "../context/AlertContext";
import ConfirmModal from "../components/ConfirmModal";
import FormField from "../components/FormField";
import Forbidden from "../components/Forbidden";
import FormModal from "../components/FormModal";
import { useApiMutation } from "../lib/queries/mutations";
import {
userListOptions,
roleListOptions,
type User,
} from "../lib/queries/users";
import {
Button,
Card,
DataTable,
Modal,
ConfirmDialog,
Field,
TextField,
SwitchField,
Select,
StatusChip,
type DataColumn,
} from "../ui";
const API_BASE = "/api/admin";
@@ -22,10 +36,59 @@ interface FormData {
password: string;
first_name: string;
last_name: string;
role_id: number | string;
role_id: string;
is_active: boolean;
}
// Payload sent to the API. The kit Select is string-based, so the form keeps
// role_id as a string and we convert it to a number at the submit boundary
// (the server expects a numeric role_id).
type UserPayload = Omit<FormData, "role_id"> & { role_id: number };
const PlusIcon = (
<svg
width="20"
height="20"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
>
<line x1="12" y1="5" x2="12" y2="19" />
<line x1="5" y1="12" x2="19" y2="12" />
</svg>
);
const EditIcon = (
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" />
<path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" />
</svg>
);
const DeleteIcon = (
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<polyline points="3 6 5 6 21 6" />
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
</svg>
);
export default function Users() {
const { user: currentUser, updateUser, hasPermission } = useAuth();
const alert = useAlert();
@@ -39,6 +102,7 @@ export default function Users() {
user: User | null;
}>({ isOpen: false, user: null });
const [saving, setSaving] = useState(false);
const [errors, setErrors] = useState<Record<string, string>>({});
const [formData, setFormData] = useState<FormData>({
username: "",
email: "",
@@ -58,8 +122,8 @@ export default function Users() {
"projects",
];
const saveUser = useApiMutation<FormData, void>({
url: (input) =>
const saveUser = useApiMutation<UserPayload, void>({
url: () =>
editingUser ? `${API_BASE}/users/${editingUser.id}` : `${API_BASE}/users`,
method: () => (editingUser ? "PUT" : "POST"),
invalidate: USER_INVALIDATE,
@@ -115,9 +179,10 @@ export default function Users() {
password: "",
first_name: "",
last_name: "",
role_id: roles[0]?.id || "",
role_id: roles[0]?.id ? String(roles[0].id) : "",
is_active: true,
});
setErrors({});
setShowModal(true);
};
@@ -129,9 +194,10 @@ export default function Users() {
password: "",
first_name: user.first_name,
last_name: user.last_name,
role_id: user.role_id,
role_id: String(user.role_id),
is_active: user.is_active,
});
setErrors({});
setShowModal(true);
};
@@ -141,9 +207,22 @@ export default function Users() {
};
const handleSubmit = async () => {
const newErrors: Record<string, string> = {};
if (!formData.first_name) newErrors.first_name = "Zadejte jméno";
if (!formData.last_name) newErrors.last_name = "Zadejte příjmení";
if (!formData.username) newErrors.username = "Zadejte uživatelské jméno";
if (!formData.email) newErrors.email = "Zadejte e-mail";
if (!editingUser && !formData.password)
newErrors.password = "Zadejte heslo";
setErrors(newErrors);
if (Object.keys(newErrors).length > 0) return;
setSaving(true);
try {
await saveUser.mutateAsync(formData);
await saveUser.mutateAsync({
...formData,
role_id: Number(formData.role_id),
});
} catch (e) {
alert.error(e instanceof Error ? e.message : "Chyba připojení");
} finally {
@@ -151,14 +230,6 @@ export default function Users() {
}
};
const openDeleteModal = (user: User) => {
setDeleteModal({ isOpen: true, user });
};
const closeDeleteModal = () => {
setDeleteModal({ isOpen: false, user: null });
};
const handleDelete = async () => {
if (!deleteModal.user) return;
try {
@@ -175,15 +246,6 @@ export default function Users() {
});
};
const getRoleBadgeClass = (roleName: string): string => {
switch (roleName) {
case "admin":
return "admin-badge admin-badge-admin";
default:
return "admin-badge admin-badge-viewer";
}
};
if (isPending) {
return (
<div className="admin-loading">
@@ -192,278 +254,231 @@ export default function Users() {
);
}
const columns: DataColumn<User>[] = [
{
key: "user",
header: "Uživatel",
render: (u) => (
<Box sx={{ display: "flex", alignItems: "center", gap: 1.5 }}>
<Avatar sx={{ bgcolor: "primary.main", width: 36, height: 36 }}>
{(u.first_name || u.username).charAt(0).toUpperCase()}
</Avatar>
<Box>
<Typography variant="body2" sx={{ fontWeight: 600 }}>
{u.first_name} {u.last_name}
</Typography>
<Typography variant="caption" color="text.secondary">
@{u.username}
</Typography>
</Box>
</Box>
),
},
{ key: "email", header: "E-mail", render: (u) => u.email },
{
key: "role",
header: "Role",
render: (u) => (
<StatusChip
label={u.roles?.display_name || u.roles?.name || "—"}
color={u.roles?.name === "admin" ? "warning" : "default"}
/>
),
},
{
key: "status",
header: "Stav",
render: (u) => (
<StatusChip
label={u.is_active ? "Aktivní" : "Neaktivní"}
color={u.is_active ? "success" : "default"}
onClick={u.id === currentUser?.id ? undefined : () => toggleActive(u)}
/>
),
},
{
key: "actions",
header: "Akce",
align: "right",
render: (u) => (
<Box sx={{ display: "flex", gap: 0.5, justifyContent: "flex-end" }}>
<IconButton
size="small"
onClick={() => openEditModal(u)}
aria-label="Upravit"
title="Upravit"
>
{EditIcon}
</IconButton>
{u.id !== currentUser?.id && (
<IconButton
size="small"
color="error"
onClick={() => setDeleteModal({ isOpen: true, user: u })}
aria-label="Smazat"
title="Smazat"
>
{DeleteIcon}
</IconButton>
)}
</Box>
),
},
];
return (
<div>
<Box>
<motion.div
className="admin-page-header"
initial={{ opacity: 0, y: 12 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.25 }}
>
<div>
<h1 className="admin-page-title">Uživatelé</h1>
<p className="admin-page-subtitle">
Správa uživatelských úč a oprávnění
</p>
</div>
<button
onClick={openCreateModal}
className="admin-btn admin-btn-primary"
<Box
sx={{
display: "flex",
alignItems: "center",
justifyContent: "space-between",
mb: 3,
flexWrap: "wrap",
gap: 2,
}}
>
<svg
width="20"
height="20"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
>
<line x1="12" y1="5" x2="12" y2="19" />
<line x1="5" y1="12" x2="19" y2="12" />
</svg>
Přidat uživatele
</button>
<Typography variant="h4">Správa uživatelů</Typography>
<Button startIcon={PlusIcon} onClick={openCreateModal}>
Přidat uživatele
</Button>
</Box>
</motion.div>
<motion.div
className="admin-card"
initial={{ opacity: 0, y: 12 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.25, delay: 0.06 }}
>
<div className="admin-card-body">
<div className="admin-table-responsive">
<table className="admin-table">
<thead>
<tr>
<th>Uživatel</th>
<th>E-mail</th>
<th>Role</th>
<th>Stav</th>
<th>Akce</th>
</tr>
</thead>
<tbody>
{users.map((user) => (
<tr key={user.id}>
<td>
<div className="admin-table-user">
<div className="admin-table-avatar">
{(user.first_name || user.username)
.charAt(0)
.toUpperCase()}
</div>
<div>
<div className="admin-table-name">
{user.first_name} {user.last_name}
</div>
<div className="admin-table-username">
@{user.username}
</div>
</div>
</div>
</td>
<td>{user.email}</td>
<td>
<span
className={getRoleBadgeClass(user.roles?.name ?? "")}
>
{user.roles?.display_name || user.roles?.name || "—"}
</span>
</td>
<td>
<button
onClick={() =>
user.id !== currentUser?.id && toggleActive(user)
}
disabled={user.id === currentUser?.id}
className={`admin-badge ${user.is_active ? "admin-badge-active" : "admin-badge-inactive"}`}
style={{
cursor:
user.id === currentUser?.id
? "not-allowed"
: "pointer",
}}
>
{user.is_active ? "Aktivní" : "Neaktivní"}
</button>
</td>
<td>
<div className="admin-table-actions">
<button
onClick={() => openEditModal(user)}
className="admin-btn-icon"
title="Upravit"
aria-label="Upravit"
>
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" />
<path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" />
</svg>
</button>
{user.id !== currentUser?.id && (
<button
onClick={() => openDeleteModal(user)}
className="admin-btn-icon danger"
title="Smazat"
aria-label="Smazat"
>
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<polyline points="3 6 5 6 21 6" />
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
</svg>
</button>
)}
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
<Card>
<DataTable<User>
columns={columns}
rows={users}
rowKey={(u) => u.id}
rowInactive={(u) => !u.is_active}
empty={
<Box sx={{ textAlign: "center", py: 6 }}>
<Typography color="text.secondary" gutterBottom>
Zatím nejsou žádní uživatelé.
</Typography>
<Button startIcon={PlusIcon} onClick={openCreateModal}>
Přidat prvního uživatele
</Button>
</Box>
}
/>
</Card>
</motion.div>
<FormModal
<Modal
isOpen={showModal}
onClose={closeModal}
onSubmit={handleSubmit}
title={editingUser ? "Upravit uživatele" : "Přidat nového uživatele"}
submitLabel={editingUser ? "Uložit změny" : "Vytvořit uživatele"}
loading={saving}
>
<div className="admin-form">
<div className="admin-form-row">
<FormField label="Jméno">
<input
type="text"
<Box sx={{ display: "flex", gap: 2, flexWrap: "wrap" }}>
<Box sx={{ flex: "1 1 200px" }}>
<Field label="Jméno" required error={errors.first_name}>
<TextField
value={formData.first_name}
onChange={(e) =>
setFormData({
...formData,
first_name: e.target.value,
})
}
required
className="admin-form-input"
error={!!errors.first_name}
onChange={(e) => {
setFormData({ ...formData, first_name: e.target.value });
setErrors((prev) => ({ ...prev, first_name: "" }));
}}
/>
</FormField>
<FormField label="Příjmení">
<input
type="text"
</Field>
</Box>
<Box sx={{ flex: "1 1 200px" }}>
<Field label="Příjmení" required error={errors.last_name}>
<TextField
value={formData.last_name}
onChange={(e) =>
setFormData({
...formData,
last_name: e.target.value,
})
}
required
className="admin-form-input"
error={!!errors.last_name}
onChange={(e) => {
setFormData({ ...formData, last_name: e.target.value });
setErrors((prev) => ({ ...prev, last_name: "" }));
}}
/>
</FormField>
</div>
</Field>
</Box>
</Box>
<FormField label="Uživatelské jméno">
<input
type="text"
value={formData.username}
onChange={(e) =>
setFormData({ ...formData, username: e.target.value })
}
required
className="admin-form-input"
/>
</FormField>
<Field label="Uživatelské jméno" required error={errors.username}>
<TextField
value={formData.username}
error={!!errors.username}
onChange={(e) => {
setFormData({ ...formData, username: e.target.value });
setErrors((prev) => ({ ...prev, username: "" }));
}}
/>
</Field>
<FormField label="E-mail">
<input
type="email"
value={formData.email}
onChange={(e) =>
setFormData({ ...formData, email: e.target.value })
}
required
className="admin-form-input"
/>
</FormField>
<Field label="E-mail" required error={errors.email}>
<TextField
type="email"
value={formData.email}
error={!!errors.email}
onChange={(e) => {
setFormData({ ...formData, email: e.target.value });
setErrors((prev) => ({ ...prev, email: "" }));
}}
/>
</Field>
<FormField
label={`Heslo ${editingUser ? "(ponechte prázdné pro zachování stávajícího)" : ""}`}
>
<input
type="password"
value={formData.password}
onChange={(e) =>
setFormData({ ...formData, password: e.target.value })
}
required={!editingUser}
className="admin-form-input"
/>
</FormField>
<Field
label={`Heslo${editingUser ? " (ponechte prázdné pro zachování stávajícího)" : ""}`}
required={!editingUser}
error={errors.password}
>
<TextField
type="password"
value={formData.password}
error={!!errors.password}
onChange={(e) => {
setFormData({ ...formData, password: e.target.value });
setErrors((prev) => ({ ...prev, password: "" }));
}}
/>
</Field>
<FormField label="Role">
<select
value={formData.role_id}
onChange={(e) =>
setFormData({ ...formData, role_id: e.target.value })
}
required
className="admin-form-select"
>
{roles.map((role) => (
<option key={role.id} value={role.id}>
{role.display_name}
</option>
))}
</select>
</FormField>
<Field label="Role">
<Select
value={formData.role_id}
onChange={(value) => setFormData({ ...formData, role_id: value })}
options={roles.map((role) => ({
value: String(role.id),
label: role.display_name || role.name,
}))}
/>
</Field>
<label className="admin-form-checkbox">
<input
type="checkbox"
checked={formData.is_active}
onChange={(e) =>
setFormData({
...formData,
is_active: e.target.checked,
})
}
/>
<span>Účet je aktivní</span>
</label>
</div>
</FormModal>
<SwitchField
label="Účet je aktivní"
checked={formData.is_active}
onChange={(v) => setFormData({ ...formData, is_active: v })}
/>
</Modal>
<ConfirmModal
<ConfirmDialog
isOpen={deleteModal.isOpen}
onClose={closeDeleteModal}
onClose={() => setDeleteModal({ isOpen: false, user: null })}
onConfirm={handleDelete}
title="Smazat uživatele"
message={`Opravdu chcete smazat uživatele "${deleteModal.user?.first_name} ${deleteModal.user?.last_name}"? Tato akce je nevratná.`}
message={
deleteModal.user
? `Opravdu chcete smazat uživatele "${deleteModal.user.first_name} ${deleteModal.user.last_name}"? Tato akce je nevratná.`
: ""
}
confirmText="Smazat"
cancelText="Zrušit"
type="danger"
loading={deleteUser.isPending}
confirmVariant="danger"
/>
</div>
</Box>
);
}