feat(mui): migrate Audit Log onto MUI kit

Replaces admin-* CSS, FormModal, FormField, AdminDatePicker, and legacy
Pagination with PageHeader, FilterBar, Card, DataTable, Modal, Select,
DateField, TextField, StatusChip, Pagination, EmptyState, LoadingState.
All filter params, useQuery key, cleanupMutation, DELETE_ALL_AUDIT token
logic, and invalidate: ["audit-log"] preserved verbatim.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
BOHA
2026-06-06 23:40:39 +02:00
parent 4fb52e9626
commit a5103ee738

View File

@@ -1,17 +1,31 @@
import { useState } from "react"; import { useState } from "react";
import { useQuery } from "@tanstack/react-query"; import { useQuery } from "@tanstack/react-query";
import { motion } from "framer-motion"; import { motion } from "framer-motion";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import { useAuth } from "../context/AuthContext"; import { useAuth } from "../context/AuthContext";
import { useAlert } from "../context/AlertContext"; import { useAlert } from "../context/AlertContext";
import Forbidden from "../components/Forbidden"; import Forbidden from "../components/Forbidden";
import Pagination from "../components/Pagination";
import FormField from "../components/FormField";
import FormModal from "../components/FormModal";
import AdminDatePicker from "../components/AdminDatePicker";
import { czechPlural } from "../utils/formatters"; import { czechPlural } from "../utils/formatters";
import apiFetch from "../utils/api"; import apiFetch from "../utils/api";
import { useApiMutation } from "../lib/queries/mutations"; import { useApiMutation } from "../lib/queries/mutations";
import { ENTITY_TYPE_LABELS } from "../lib/entityTypeLabels"; import { ENTITY_TYPE_LABELS } from "../lib/entityTypeLabels";
import {
Button,
Card,
DataTable,
Pagination,
Modal,
Select,
DateField,
TextField,
StatusChip,
PageHeader,
FilterBar,
EmptyState,
LoadingState,
type DataColumn,
} from "../ui";
const API_BASE = "/api/admin"; const API_BASE = "/api/admin";
@@ -30,19 +44,23 @@ const ACTION_LABELS: Record<string, string> = {
access_denied: "Přístup odepřen", access_denied: "Přístup odepřen",
}; };
const ACTION_BADGE_CLASS: Record<string, string> = { // Maps legacy admin-badge-* CSS class suffixes → StatusChip color
create: "admin-badge-success", const ACTION_CHIP_COLOR: Record<
update: "admin-badge-info", string,
delete: "admin-badge-danger", "success" | "info" | "warning" | "error" | "default"
login: "admin-badge-secondary", > = {
login_failed: "admin-badge-danger", create: "success",
logout: "admin-badge-secondary", update: "info",
view: "admin-badge-info", delete: "error",
activate: "admin-badge-success", login: "default",
deactivate: "admin-badge-warning", login_failed: "error",
password_change: "admin-badge-info", logout: "default",
permission_change: "admin-badge-warning", view: "info",
access_denied: "admin-badge-danger", activate: "success",
deactivate: "warning",
password_change: "info",
permission_change: "warning",
access_denied: "error",
}; };
const ACTION_OPTIONS = Object.entries(ACTION_LABELS).map(([value, label]) => ({ const ACTION_OPTIONS = Object.entries(ACTION_LABELS).map(([value, label]) => ({
@@ -53,6 +71,29 @@ const ENTITY_OPTIONS = Object.entries(ENTITY_TYPE_LABELS).map(
([value, label]) => ({ value, label }), ([value, label]) => ({ value, label }),
); );
const CLEANUP_DAYS_OPTIONS = [
{ value: "30", label: "30 dní" },
{ value: "60", label: "60 dní" },
{ value: "90", label: "90 dní" },
{ value: "180", label: "180 dní" },
{ value: "365", label: "1 rok" },
{ value: "0", label: "Vše" },
];
const TrashIcon = (
<svg
width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
>
<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>
);
interface AuditLogEntry { interface AuditLogEntry {
id: number; id: number;
created_at: string; created_at: string;
@@ -82,9 +123,10 @@ export default function AuditLog() {
date_to: "", date_to: "",
}); });
const [page, setPage] = useState(1); const [page, setPage] = useState(1);
const [perPage, setPerPage] = useState(50); const [perPage] = useState(50);
const [showCleanup, setShowCleanup] = useState(false); const [showCleanup, setShowCleanup] = useState(false);
const [cleanupDays, setCleanupDays] = useState(90); // cleanupDays stored as string for the kit Select; converted to number at the boundary
const [cleanupDaysStr, setCleanupDaysStr] = useState("90");
const { data: logsData, isPending } = useQuery({ const { data: logsData, isPending } = useQuery({
queryKey: [ queryKey: [
@@ -154,16 +196,8 @@ export default function AuditLog() {
setPage(1); setPage(1);
}; };
const handlePageChange = (newPage: number) => {
setPage(newPage);
};
const handlePerPageChange = (newPerPage: number) => {
setPage(1);
setPerPage(newPerPage);
};
const handleCleanup = async () => { const handleCleanup = async () => {
const cleanupDays = Number(cleanupDaysStr);
try { try {
// Backend requires this literal confirmation token when wiping everything. // Backend requires this literal confirmation token when wiping everything.
await cleanupMutation.mutateAsync({ await cleanupMutation.mutateAsync({
@@ -181,229 +215,162 @@ export default function AuditLog() {
}; };
if (isPending && logs.length === 0) { if (isPending && logs.length === 0) {
return ( return <LoadingState />;
<div className="admin-loading">
<div className="admin-spinner" />
</div>
);
} }
const columns: DataColumn<AuditLogEntry>[] = [
{
key: "created_at",
header: "Čas",
width: "16%",
mono: true,
render: (log) => formatDatetime(log.created_at),
},
{
key: "username",
header: "Uživatel",
width: "14%",
bold: true,
render: (log) => log.username || "-",
},
{
key: "action",
header: "Akce",
width: "14%",
render: (log) => (
<StatusChip
label={ACTION_LABELS[log.action] || log.action}
color={ACTION_CHIP_COLOR[log.action] ?? "default"}
/>
),
},
{
key: "entity_type",
header: "Typ entity",
width: "14%",
render: (log) =>
ENTITY_TYPE_LABELS[log.entity_type || ""] || log.entity_type || "-",
},
{
key: "description",
header: "Popis",
width: "30%",
render: (log) => log.description || "-",
},
{
key: "user_ip",
header: "IP",
width: "12%",
mono: true,
render: (log) => log.user_ip || "-",
},
];
return ( return (
<div> <Box>
<motion.div <motion.div
className="admin-page-header"
initial={{ opacity: 0, y: 12 }} initial={{ opacity: 0, y: 12 }}
animate={{ opacity: 1, y: 0 }} animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.25 }} transition={{ duration: 0.25 }}
> >
<div> <PageHeader
<h1 className="admin-page-title">Audit log</h1> title="Audit log"
{pagination && ( subtitle={
<p className="admin-page-subtitle"> pagination
{pagination.total}{" "} ? `${pagination.total} ${czechPlural(pagination.total, "záznam", "záznamy", "záznamů")}`
{czechPlural(pagination.total, "záznam", "záznamy", "záznamů")} : undefined
</p> }
)} actions={
</div> <Button
<button variant="outlined"
className="admin-btn admin-btn-secondary admin-btn-sm" startIcon={TrashIcon}
onClick={() => setShowCleanup(true)} onClick={() => setShowCleanup(true)}
> >
<svg
width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
>
<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>
Vyčistit Vyčistit
</button> </Button>
}
/>
</motion.div> </motion.div>
<FormModal {/* Cleanup Modal */}
<Modal
isOpen={showCleanup} isOpen={showCleanup}
onClose={() => !cleanupMutation.isPending && setShowCleanup(false)} onClose={() => !cleanupMutation.isPending && setShowCleanup(false)}
onSubmit={handleCleanup} onSubmit={handleCleanup}
title="Vyčistit audit log" title="Vyčistit audit log"
submitLabel="Smazat" submitText="Smazat"
loading={cleanupMutation.isPending} loading={cleanupMutation.isPending}
> >
<p className="admin-confirm-message">Smazat záznamy starší než:</p> <Typography variant="body2" sx={{ mb: 1 }}>
<div style={{ margin: "0.75rem 0", maxWidth: "200px" }}> Smazat záznamy starší než:
<select </Typography>
className="admin-form-select" <Box sx={{ maxWidth: 200, mb: 1 }}>
value={cleanupDays} <Select
onChange={(e) => setCleanupDays(parseInt(e.target.value))} value={cleanupDaysStr}
> onChange={setCleanupDaysStr}
<option value={30}>30 dní</option> options={CLEANUP_DAYS_OPTIONS}
<option value={60}>60 dní</option> />
<option value={90}>90 dní</option> </Box>
<option value={180}>180 dní</option> <Typography variant="body2" sx={{ opacity: 0.6, fontSize: "0.75rem" }}>
<option value={365}>1 rok</option>
<option value={0}>Vše</option>
</select>
</div>
<p
className="admin-confirm-message"
style={{ fontSize: "12px", opacity: 0.6 }}
>
Tato akce je nevratná. Tato akce je nevratná.
</p> </Typography>
</FormModal> </Modal>
<motion.div <FilterBar>
className="admin-card mb-4" <Box sx={{ flex: "1 1 220px" }}>
initial={{ opacity: 0, y: 12 }} <TextField
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.25, delay: 0.06 }}
>
<div className="admin-card-body">
<div className="admin-form-row admin-form-row-5">
<FormField label="Hledat">
<input
type="text"
className="admin-form-input"
placeholder="Popis, uživatel..."
value={filters.search} value={filters.search}
onChange={(e) => handleFilterChange("search", e.target.value)} onChange={(e) => handleFilterChange("search", e.target.value)}
placeholder="Popis, uživatel..."
fullWidth
/> />
</FormField> </Box>
<FormField label="Akce"> <Box sx={{ flex: "0 0 170px" }}>
<select <Select
className="admin-form-select"
value={filters.action} value={filters.action}
onChange={(e) => handleFilterChange("action", e.target.value)} onChange={(val) => handleFilterChange("action", val)}
> options={[{ value: "", label: "Všechny akce" }, ...ACTION_OPTIONS]}
<option value="">Všechny</option> />
{ACTION_OPTIONS.map((opt) => ( </Box>
<option key={opt.value} value={opt.value}> <Box sx={{ flex: "0 0 200px" }}>
{opt.label} <Select
</option>
))}
</select>
</FormField>
<FormField label="Typ entity">
<select
className="admin-form-select"
value={filters.entity_type} value={filters.entity_type}
onChange={(e) => onChange={(val) => handleFilterChange("entity_type", val)}
handleFilterChange("entity_type", e.target.value) options={[
} { value: "", label: "Všechny entity" },
> ...ENTITY_OPTIONS,
<option value="">Všechny</option> ]}
{ENTITY_OPTIONS.map((opt) => ( />
<option key={opt.value} value={opt.value}> </Box>
{opt.label} <Box sx={{ flex: "0 0 150px" }}>
</option> <DateField
))}
</select>
</FormField>
<FormField label="Od">
<AdminDatePicker
mode="date"
value={filters.date_from} value={filters.date_from}
onChange={(val: string) => handleFilterChange("date_from", val)} onChange={(val) => handleFilterChange("date_from", val)}
label="Od"
/> />
</FormField> </Box>
<FormField label="Do"> <Box sx={{ flex: "0 0 150px" }}>
<AdminDatePicker <DateField
mode="date"
value={filters.date_to} value={filters.date_to}
onChange={(val: string) => handleFilterChange("date_to", val)} onChange={(val) => handleFilterChange("date_to", val)}
label="Do"
/> />
</FormField> </Box>
</div> </FilterBar>
</div>
</motion.div>
<motion.div
className="admin-card"
initial={{ opacity: 0, y: 12 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.25, delay: 0.08 }}
>
<div className="admin-card-body">
<div className="admin-table-responsive">
{isPending ? (
<div className="admin-loading">
<div className="admin-spinner" />
</div>
) : (
<table className="admin-table">
<thead>
<tr>
<th>Čas</th>
<th>Uživatel</th>
<th>Akce</th>
<th>Typ entity</th>
<th>Popis</th>
<th>IP</th>
</tr>
</thead>
<tbody>
{logs.length === 0 && (
<tr>
<td colSpan={6}>
<div className="admin-empty-state">
<div className="admin-empty-icon">
<svg
width="28"
height="28"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
>
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
<polyline points="14 2 14 8 20 8" />
<line x1="16" y1="13" x2="8" y2="13" />
<line x1="16" y1="17" x2="8" y2="17" />
</svg>
</div>
<p>Žádné záznamy k zobrazení</p>
</div>
</td>
</tr>
)}
{logs.length > 0 &&
logs.map((log) => (
<tr key={log.id}>
<td className="admin-mono">
{formatDatetime(log.created_at)}
</td>
<td className="fw-500">{log.username || "-"}</td>
<td>
<span
className={`admin-badge ${ACTION_BADGE_CLASS[log.action] || "admin-badge-secondary"}`}
>
{ACTION_LABELS[log.action] || log.action}
</span>
</td>
<td>
{ENTITY_TYPE_LABELS[log.entity_type || ""] ||
log.entity_type ||
"-"}
</td>
<td>{log.description || "-"}</td>
<td className="admin-mono">{log.user_ip || "-"}</td>
</tr>
))}
</tbody>
</table>
)}
</div>
<Card sx={{ opacity: isPending ? 0.6 : 1, transition: "opacity .2s" }}>
<DataTable<AuditLogEntry>
columns={columns}
rows={logs}
rowKey={(log) => log.id}
empty={<EmptyState title="Žádné záznamy k zobrazení" />}
/>
<Pagination <Pagination
pagination={pagination} page={page}
onPageChange={handlePageChange} pageCount={pagination?.total_pages ?? 1}
onPerPageChange={handlePerPageChange} onChange={setPage}
/> />
</div> </Card>
</motion.div> </Box>
</div>
); );
} }