feat(mui): migrate Dashboard (Přehled) onto MUI kit

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
BOHA
2026-06-07 01:19:49 +02:00
parent 5ca03bd662
commit 5459d8c325
7 changed files with 1205 additions and 968 deletions

View File

@@ -1,4 +1,7 @@
import { Link } from "react-router-dom"; import { Link as RouterLink } from "react-router-dom";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import { Card, Button, EmptyState } from "../../ui";
import { import {
ENTITY_TYPE_LABELS, ENTITY_TYPE_LABELS,
getActivityIconClass, getActivityIconClass,
@@ -18,6 +21,16 @@ interface DashActivityFeedProps {
activities: Activity[] | null; activities: Activity[] | null;
} }
// Maps the legacy activity-icon class to the MUI palette key used to tint the
// circular icon badge (danger → error, accent → primary, muted → default).
const ACTIVITY_BADGE_COLOR: Record<string, string> = {
success: "success",
info: "info",
danger: "error",
accent: "primary",
muted: "default",
};
function getActivityIcon(action: string) { function getActivityIcon(action: string) {
switch (action) { switch (action) {
case "create": case "create":
@@ -103,37 +116,92 @@ export default function DashActivityFeed({
} }
return ( return (
<div className="admin-card dash-activity-card"> <Card sx={{ display: "flex", flexDirection: "column" }}>
<div className="admin-card-header flex-between"> <Box
<h2 className="admin-card-title">Audit log</h2> sx={{
<Link display: "flex",
alignItems: "center",
justifyContent: "space-between",
mb: 2,
}}
>
<Typography variant="h6">Audit log</Typography>
<Button
component={RouterLink}
to="/audit-log" to="/audit-log"
className="admin-btn admin-btn-primary admin-btn-sm" size="small"
sx={{ flexShrink: 0 }}
> >
Detail &rarr; Detail &rarr;
</Link> </Button>
</div> </Box>
<div className="admin-card-body" style={{ padding: 0 }}>
{activities.map((act) => ( {activities.length === 0 ? (
<div key={act.id} className="dash-activity-row"> <EmptyState title="Žádná aktivita" />
<div ) : (
className={`dash-activity-icon ${getActivityIconClass(act.action)}`} <Box sx={{ display: "flex", flexDirection: "column" }}>
{activities.map((act) => {
const badgeColor =
ACTIVITY_BADGE_COLOR[getActivityIconClass(act.action)] ??
"default";
const isDefault = badgeColor === "default";
return (
<Box
key={act.id}
sx={{
display: "flex",
alignItems: "center",
gap: 1.5,
py: 1.25,
borderBottom: 1,
borderColor: "divider",
"&:last-of-type": { borderBottom: 0 },
}}
>
<Box
sx={{
display: "flex",
alignItems: "center",
justifyContent: "center",
width: 32,
height: 32,
borderRadius: "50%",
flexShrink: 0,
bgcolor: isDefault ? "action.hover" : `${badgeColor}.light`,
color: isDefault ? "text.secondary" : `${badgeColor}.main`,
}}
> >
{getActivityIcon(act.action)} {getActivityIcon(act.action)}
</div> </Box>
<div className="dash-activity-main"> <Box sx={{ flex: 1, minWidth: 0 }}>
<div className="dash-activity-text">{act.description}</div> <Typography
<div className="dash-activity-sub"> variant="body2"
sx={{ fontWeight: 500 }}
noWrap
title={act.description}
>
{act.description}
</Typography>
<Typography variant="caption" color="text.secondary" noWrap>
{act.username || "Systém"} ·{" "} {act.username || "Systém"} ·{" "}
{ENTITY_TYPE_LABELS[act.entity_type] || act.entity_type} {ENTITY_TYPE_LABELS[act.entity_type] || act.entity_type}
</div> </Typography>
</div> </Box>
<div className="dash-activity-time admin-mono"> <Typography
variant="caption"
color="text.secondary"
sx={{
fontFamily: "'DM Mono', Menlo, monospace",
flexShrink: 0,
}}
>
{formatActivityTime(act.created_at)} {formatActivityTime(act.created_at)}
</div> </Typography>
</div> </Box>
))} );
</div> })}
</div> </Box>
)}
</Card>
); );
} }

View File

@@ -1,9 +1,9 @@
import { Link } from "react-router-dom"; import { Link as RouterLink } from "react-router-dom";
import { import Box from "@mui/material/Box";
LEAVE_TYPE_LABELS, import Typography from "@mui/material/Typography";
STATUS_DOT_CLASS, import Avatar from "@mui/material/Avatar";
STATUS_LABELS, import { Card, Button, StatusChip, EmptyState } from "../../ui";
} from "../../utils/dashboardHelpers"; import { LEAVE_TYPE_LABELS, STATUS_LABELS } from "../../utils/dashboardHelpers";
interface AttendanceUser { interface AttendanceUser {
user_id: number | string; user_id: number | string;
@@ -22,6 +22,19 @@ interface DashAttendanceTodayProps {
attendance: AttendanceData | null; attendance: AttendanceData | null;
} }
// Maps the attendance status to the StatusChip / avatar tint color.
// Mirrors the legacy dash-status-* dot classes: in→success, away→warning,
// out→default, leave→error.
const STATUS_COLOR: Record<
string,
"default" | "success" | "warning" | "error"
> = {
in: "success",
away: "warning",
out: "default",
leave: "error",
};
export default function DashAttendanceToday({ export default function DashAttendanceToday({
attendance, attendance,
}: DashAttendanceTodayProps) { }: DashAttendanceTodayProps) {
@@ -30,42 +43,96 @@ export default function DashAttendanceToday({
} }
return ( return (
<div className="admin-card dash-attendance-card"> <Card sx={{ display: "flex", flexDirection: "column" }}>
<div className="admin-card-header flex-between"> <Box
<h2 className="admin-card-title">Docházka dnes</h2> sx={{
<Link display: "flex",
alignItems: "center",
justifyContent: "space-between",
mb: 2,
}}
>
<Typography variant="h6">Docházka dnes</Typography>
<Button
component={RouterLink}
to="/attendance/admin" to="/attendance/admin"
className="admin-btn admin-btn-primary admin-btn-sm" size="small"
sx={{ flexShrink: 0 }}
> >
Detail &rarr; Detail &rarr;
</Link> </Button>
</div> </Box>
<div className="admin-card-body" style={{ padding: 0 }}>
{attendance.users.map((u, i) => ( {attendance.users.length === 0 ? (
<div key={`${u.user_id}-${i}`} className="dash-presence-row"> <EmptyState title="Žádná docházka" />
<div ) : (
className={`dash-presence-avatar ${STATUS_DOT_CLASS[u.status]}`} <Box sx={{ display: "flex", flexDirection: "column" }}>
{attendance.users.map((u, i) => {
const color = STATUS_COLOR[u.status] ?? "default";
const isDefault = color === "default";
return (
<Box
key={`${u.user_id}-${i}`}
sx={{
display: "flex",
alignItems: "center",
gap: 1.5,
py: 1.25,
borderBottom: 1,
borderColor: "divider",
"&:last-of-type": { borderBottom: 0 },
}}
>
<Avatar
sx={{
width: 36,
height: 36,
fontSize: "0.8rem",
fontWeight: 700,
bgcolor: isDefault ? "action.hover" : `${color}.light`,
color: isDefault ? "text.secondary" : `${color}.main`,
}}
> >
{u.initials || "?"} {u.initials || "?"}
</div> </Avatar>
<div className="dash-presence-name">{u.name}</div> <Typography
<div className="dash-presence-end"> variant="body2"
<span sx={{ fontWeight: 500, flex: 1, minWidth: 0 }}
className={`dash-presence-label ${STATUS_DOT_CLASS[u.status]}`} noWrap
> >
{u.status === "leave" {u.name}
</Typography>
<Box
sx={{
display: "flex",
alignItems: "center",
gap: 1,
flexShrink: 0,
}}
>
<StatusChip
color={color}
label={
u.status === "leave"
? LEAVE_TYPE_LABELS[u.leave_type || ""] || "Nepřítomen" ? LEAVE_TYPE_LABELS[u.leave_type || ""] || "Nepřítomen"
: STATUS_LABELS[u.status]} : STATUS_LABELS[u.status]
</span> }
/>
{u.arrived_at && ( {u.arrived_at && (
<span className="admin-mono dash-presence-time"> <Typography
variant="caption"
color="text.secondary"
sx={{ fontFamily: "'DM Mono', Menlo, monospace" }}
>
{u.arrived_at} {u.arrived_at}
</span> </Typography>
)} )}
</div> </Box>
</div> </Box>
))} );
</div> })}
</div> </Box>
)}
</Card>
); );
} }

View File

@@ -1,4 +1,7 @@
import { motion } from "framer-motion"; import { motion } from "framer-motion";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import { StatCard, type StatCardColor } from "../../ui";
import { formatCurrency } from "../../utils/formatters"; import { formatCurrency } from "../../utils/formatters";
interface KpiCard { interface KpiCard {
@@ -108,11 +111,13 @@ function buildInvoiceKpi(invoices: InvoicesData): KpiCard {
}; };
} }
const KPI_CLASS_MAP: Record<number, string> = { // Maps the legacy KPI color tokens to the StatCard color palette
4: "admin-kpi-4", // (danger → error; the rest are 1:1).
3: "admin-kpi-3", const KPI_COLOR_MAP: Record<string, StatCardColor> = {
2: "admin-kpi-2", success: "success",
1: "admin-kpi-1", info: "info",
warning: "warning",
danger: "error",
}; };
export default function DashKpiCards({ dashData }: DashKpiCardsProps) { export default function DashKpiCards({ dashData }: DashKpiCardsProps) {
@@ -121,36 +126,50 @@ export default function DashKpiCards({ dashData }: DashKpiCardsProps) {
return null; return null;
} }
const kpiClass = KPI_CLASS_MAP[Math.min(kpiCards.length, 4)] || "admin-kpi-4";
return ( return (
<motion.div <Box
className={`admin-kpi-grid ${kpiClass}`} component={motion.div}
initial={{ opacity: 0, y: 12 }} initial={{ opacity: 0, y: 12 }}
animate={{ opacity: 1, y: 0 }} animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.25, delay: 0.06 }} transition={{ duration: 0.25, delay: 0.06 }}
sx={{
display: "grid",
gridTemplateColumns: {
xs: "1fr",
sm: "repeat(2, 1fr)",
lg: `repeat(${Math.min(kpiCards.length, 4)}, 1fr)`,
},
gap: 2,
mb: 3,
}}
> >
{kpiCards.map((kpi) => ( {kpiCards.map((kpi) => (
<div key={kpi.label} className={`admin-stat-card ${kpi.color}`}> <StatCard
<div className="admin-stat-label">{kpi.label}</div> key={kpi.label}
<div className="admin-stat-value admin-mono"> color={KPI_COLOR_MAP[kpi.color] ?? "default"}
label={kpi.label}
value={
<>
{kpi.value} {kpi.value}
{kpi.sub && ( {kpi.sub && (
<small <Typography
className="text-muted" component="span"
style={{ color="text.secondary"
sx={{
fontSize: "0.75em", fontSize: "0.75em",
fontWeight: 500, fontWeight: 500,
marginLeft: "0.25rem", ml: 0.5,
fontFamily: "inherit",
}} }}
> >
{kpi.sub} {kpi.sub}
</small> </Typography>
)} )}
</div> </>
{kpi.footer && <div className="admin-stat-footer">{kpi.footer}</div>} }
</div> footer={kpi.footer ?? undefined}
/>
))} ))}
</motion.div> </Box>
); );
} }

View File

@@ -1,9 +1,17 @@
import { useState, useRef } from "react"; import { useState, useRef } from "react";
import { motion } from "framer-motion"; import { motion } from "framer-motion";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import IconButton from "@mui/material/IconButton";
import Dialog from "@mui/material/Dialog";
import DialogTitle from "@mui/material/DialogTitle";
import DialogContent from "@mui/material/DialogContent";
import DialogActions from "@mui/material/DialogActions";
import { useAuth } from "../../context/AuthContext"; import { useAuth } from "../../context/AuthContext";
import { useAlert } from "../../context/AlertContext"; import { useAlert } from "../../context/AlertContext";
import apiFetch from "../../utils/api"; import apiFetch from "../../utils/api";
import FormModal from "../FormModal"; import { Card, Button, Modal, Field, TextField } from "../../ui";
import useDialogScrollLock from "../../ui/useDialogScrollLock";
const API_BASE = "/api/admin"; const API_BASE = "/api/admin";
@@ -37,6 +45,34 @@ interface ProfileFormData {
last_name: string; last_name: string;
} }
const EditIcon = (
<svg
width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
>
<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 CopyIcon = (
<svg
width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
>
<rect x="9" y="9" width="13" height="13" rx="2" ry="2" />
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
</svg>
);
export default function DashProfile({ export default function DashProfile({
totpEnabled, totpEnabled,
totpLoading, totpLoading,
@@ -61,6 +97,10 @@ export default function DashProfile({
const alert = useAlert(); const alert = useAlert();
const totpSetupRef = useRef<HTMLInputElement>(null); const totpSetupRef = useRef<HTMLInputElement>(null);
// The 2FA setup dialog is bespoke (multi-step: setup → backup codes) and
// locks <html> scroll like the kit dialogs.
useDialogScrollLock(show2FASetup);
const [showModal, setShowModal] = useState(false); const [showModal, setShowModal] = useState(false);
const [formData, setFormData] = useState<ProfileFormData>({ const [formData, setFormData] = useState<ProfileFormData>({
username: "", username: "",
@@ -133,80 +173,94 @@ export default function DashProfile({
return totpEnabled ? "Aktivní" : "Neaktivní"; return totpEnabled ? "Aktivní" : "Neaktivní";
} }
const profileItems: Array<{ label: string; value: string }> = [
{ label: "Uživatel", value: user?.username || "" },
{ label: "E-mail", value: user?.email || "" },
{ label: "Jméno", value: user?.fullName || "" },
{
label: "Role",
value: user?.roleDisplay || String(user?.role || ""),
},
];
return ( return (
<> <>
<motion.div <motion.div
className="admin-card"
initial={{ opacity: 0, y: 12 }} initial={{ opacity: 0, y: 12 }}
animate={{ opacity: 1, y: 0 }} animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.25, delay: 0.15 }} transition={{ duration: 0.25, delay: 0.15 }}
> >
<div className="admin-card-header flex-between"> <Card>
<h2 className="admin-card-title">Váš účet</h2> <Box
<button sx={{
onClick={openEditModal} display: "flex",
className="admin-btn admin-btn-secondary admin-btn-sm" alignItems: "center",
> justifyContent: "space-between",
<svg mb: 2,
width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
>
<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>
Upravit
</button>
</div>
<div className="admin-card-body">
<div className="dash-profile-grid">
<div className="dash-profile-item">
<span className="dash-profile-label">Uživatel</span>
<span className="dash-profile-value">{user?.username}</span>
</div>
<div className="dash-profile-item">
<span className="dash-profile-label">E-mail</span>
<span className="dash-profile-value">{user?.email}</span>
</div>
<div className="dash-profile-item">
<span className="dash-profile-label">Jméno</span>
<span className="dash-profile-value">{user?.fullName}</span>
</div>
<div className="dash-profile-item">
<span className="dash-profile-label">Role</span>
<span className="dash-profile-value">
{user?.roleDisplay || String(user?.role || "")}
</span>
</div>
</div>
{/* 2FA Section */}
<div
style={{
borderTop: "1px solid var(--border-color)",
marginTop: "1rem",
paddingTop: "1rem",
}} }}
> >
<div className="flex-between"> <Typography variant="h6">Váš účet</Typography>
<div className="flex-row-gap"> <Button
<div onClick={openEditModal}
style={{ variant="outlined"
color="inherit"
size="small"
startIcon={EditIcon}
>
Upravit
</Button>
</Box>
<Box
sx={{
display: "grid",
gridTemplateColumns: { xs: "1fr", sm: "1fr 1fr" },
gap: 1.5,
}}
>
{profileItems.map((item) => (
<Box key={item.label}>
<Typography
variant="caption"
color="text.secondary"
sx={{
display: "block",
textTransform: "uppercase",
letterSpacing: ".05em",
fontWeight: 600,
}}
>
{item.label}
</Typography>
<Typography variant="body2" sx={{ fontWeight: 500 }}>
{item.value}
</Typography>
</Box>
))}
</Box>
{/* 2FA Section */}
<Box sx={{ borderTop: 1, borderColor: "divider", mt: 2, pt: 2 }}>
<Box
sx={{
display: "flex",
alignItems: "center",
justifyContent: "space-between",
gap: 1.5,
}}
>
<Box sx={{ display: "flex", alignItems: "center", gap: 1.5 }}>
<Box
sx={{
width: 36, width: 36,
height: 36, height: 36,
borderRadius: "50%", borderRadius: "50%",
display: "flex", display: "flex",
alignItems: "center", alignItems: "center",
justifyContent: "center", justifyContent: "center",
background: totpEnabled flexShrink: 0,
? "var(--success-light)" bgcolor: totpEnabled ? "success.light" : "action.hover",
: "rgba(var(--text-secondary-rgb, 107, 114, 128), 0.1)", color: totpEnabled ? "success.main" : "text.secondary",
color: totpEnabled
? "var(--success)"
: "var(--text-secondary)",
}} }}
> >
<svg <svg
@@ -220,179 +274,163 @@ export default function DashProfile({
<rect x="3" y="11" width="18" height="11" rx="2" ry="2" /> <rect x="3" y="11" width="18" height="11" rx="2" ry="2" />
<path d="M7 11V7a5 5 0 0 1 10 0v4" /> <path d="M7 11V7a5 5 0 0 1 10 0v4" />
</svg> </svg>
</div> </Box>
<div> <Box>
<div style={{ fontWeight: 500, fontSize: "0.875rem" }}> <Typography variant="body2" sx={{ fontWeight: 500 }}>
Dvoufaktorové ověření (2FA) Dvoufaktorové ověření (2FA)
</div> </Typography>
<div <Typography
className={totpEnabled ? "text-success" : "text-secondary"} variant="caption"
style={{ fontSize: "0.75rem" }} sx={{
color: totpEnabled ? "success.main" : "text.secondary",
}}
> >
{getTotpStatusText()} {getTotpStatusText()}
</div> </Typography>
</div> </Box>
</div> </Box>
{!totpLoading && {!totpLoading &&
(totpEnabled ? ( (totpEnabled ? (
<button <Button
onClick={() => { onClick={() => {
setDisableCode(""); setDisableCode("");
setShow2FADisable(true); setShow2FADisable(true);
}} }}
className="admin-btn admin-btn-primary admin-btn-sm" size="small"
sx={{ flexShrink: 0 }}
> >
Deaktivovat Deaktivovat
</button> </Button>
) : ( ) : (
<button <Button
onClick={onStart2FASetup} onClick={onStart2FASetup}
disabled={totpSubmitting} disabled={totpSubmitting}
className="admin-btn admin-btn-primary admin-btn-sm" size="small"
sx={{ flexShrink: 0 }}
> >
{totpSubmitting ? "Generuji..." : "Aktivovat"} {totpSubmitting ? "Generuji..." : "Aktivovat"}
</button> </Button>
))} ))}
</div> </Box>
</div> </Box>
</div> </Card>
</motion.div> </motion.div>
{/* Edit Profile Modal */} {/* Edit Profile Modal */}
<FormModal <Modal
isOpen={showModal} isOpen={showModal}
onClose={() => setShowModal(false)} onClose={() => setShowModal(false)}
title="Upravit profil" title="Upravit profil"
size="md" maxWidth="sm"
onSubmit={handleSubmit} onSubmit={handleSubmit}
submitLabel="Uložit změny" submitText="Uložit změny"
> >
<div className="admin-form"> <Box
<div className="admin-form-row"> sx={{
<div className="admin-form-group"> display: "grid",
<label className="admin-form-label">Jméno</label> gridTemplateColumns: { xs: "1fr", sm: "1fr 1fr" },
<input gap: 2,
type="text" }}
>
<Field label="Jméno">
<TextField
value={formData.first_name} value={formData.first_name}
onChange={(e) => onChange={(e) =>
setFormData({ setFormData({ ...formData, first_name: e.target.value })
...formData,
first_name: e.target.value,
})
} }
required required
className="admin-form-input"
/> />
</div> </Field>
<div className="admin-form-group"> <Field label="Příjmení">
<label className="admin-form-label">Příjmení</label> <TextField
<input
type="text"
value={formData.last_name} value={formData.last_name}
onChange={(e) => onChange={(e) =>
setFormData({ setFormData({ ...formData, last_name: e.target.value })
...formData,
last_name: e.target.value,
})
} }
required required
className="admin-form-input"
/> />
</div> </Field>
</div> </Box>
<div className="admin-form-group"> <Field label="Uživatelské jméno">
<label className="admin-form-label">Uživatelské jméno</label> <TextField
<input
type="text"
value={formData.username} value={formData.username}
onChange={(e) => onChange={(e) =>
setFormData({ ...formData, username: e.target.value }) setFormData({ ...formData, username: e.target.value })
} }
required required
className="admin-form-input"
/> />
</div> </Field>
<div className="admin-form-group"> <Field label="E-mail">
<label className="admin-form-label">E-mail</label> <TextField
<input
type="email" type="email"
value={formData.email} value={formData.email}
onChange={(e) => onChange={(e) =>
setFormData({ ...formData, email: e.target.value }) setFormData({ ...formData, email: e.target.value })
} }
required required
className="admin-form-input"
/> />
</div> </Field>
<div className="admin-form-group"> <Field label="Aktuální heslo">
<label className="admin-form-label">Aktuální heslo</label> <TextField
<input
type="password" type="password"
value={formData.current_password} value={formData.current_password}
onChange={(e) => onChange={(e) =>
setFormData({ setFormData({ ...formData, current_password: e.target.value })
...formData,
current_password: e.target.value,
})
} }
className="admin-form-input"
placeholder="Pro změnu hesla, zadejte aktuální heslo" placeholder="Pro změnu hesla, zadejte aktuální heslo"
/> />
</div> </Field>
<div className="admin-form-group"> <Field label="Nové heslo">
<label className="admin-form-label">Nové heslo</label> <TextField
<input
type="password" type="password"
value={formData.new_password} value={formData.new_password}
onChange={(e) => onChange={(e) =>
setFormData({ setFormData({ ...formData, new_password: e.target.value })
...formData,
new_password: e.target.value,
})
} }
className="admin-form-input"
placeholder="Pro změnu hesla, zadejte nové heslo" placeholder="Pro změnu hesla, zadejte nové heslo"
/> />
</div> </Field>
</div> </Modal>
</FormModal>
{/* 2FA Setup Modal — multi-step: setup → backup codes */} {/* 2FA Setup Dialog — bespoke, multi-step: setup → backup codes.
<FormModal On the backup-codes step the footer + close are hidden and
isOpen={show2FASetup} backdrop/ESC are locked; the single deliberate exit lives in the body
onClose={() => { and also clears the codes (so unsaved codes can't be silently lost). */}
// Only reachable on the setup step (backdrop/ESC/× are locked while <Dialog
// backupCodes is set — that branch is unreachable so removed). open={show2FASetup}
onClose={
backupCodes
? undefined
: () => {
setShow2FASetup(false); setShow2FASetup(false);
setTotpCode(""); setTotpCode("");
}}
title={backupCodes ? "Záložní kódy" : "Nastavení 2FA"}
size="md"
loading={backupCodes ? false : totpSubmitting}
onSubmit={
backupCodes
? () => {
setShow2FASetup(false);
setBackupCodes(null);
} }
: onConfirm2FA
} }
submitLabel={ fullWidth
backupCodes ? "Rozumím, uložil jsem si kódy" : "Aktivovat 2FA" maxWidth="sm"
} disableScrollLock
submitDisabled={backupCodes ? false : totpCode.length !== 6} slotProps={{ paper: { sx: { borderRadius: 3 } } }}
cancelLabel="Zrušit"
// On the backup-codes step the cancel/× would silently dismiss unsaved
// codes, so hide the footer + × and lock backdrop/ESC; the explicit
// in-body primary is the single deliberate exit.
hideFooter={!!backupCodes}
hideCloseButton={!!backupCodes}
closeOnBackdrop={!backupCodes}
closeOnEsc={!backupCodes}
> >
<DialogTitle>
{backupCodes ? "Záložní kódy" : "Nastavení 2FA"}
</DialogTitle>
<DialogContent>
{backupCodes ? ( {backupCodes ? (
<div> <Box>
<div className="admin-role-locked-notice mb-4"> <Box
sx={{
display: "flex",
alignItems: "flex-start",
gap: 1,
p: 1.5,
mb: 2,
borderRadius: 2,
bgcolor: "warning.light",
color: "warning.main",
fontSize: "0.875rem",
}}
>
<Box sx={{ flexShrink: 0, mt: "2px" }}>
<svg <svg
width="16" width="16"
height="16" height="16"
@@ -405,161 +443,134 @@ export default function DashProfile({
<line x1="12" y1="9" x2="12" y2="13" /> <line x1="12" y1="9" x2="12" y2="13" />
<line x1="12" y1="17" x2="12.01" y2="17" /> <line x1="12" y1="17" x2="12.01" y2="17" />
</svg> </svg>
Uložte si tyto kódy na bezpečné místo. Každý kód lze použít pouze </Box>
jednou. Po zavření tohoto okna je již neuvidíte. <span>
</div> Uložte si tyto kódy na bezpečné místo. Každý kód lze použít
<div pouze jednou. Po zavření tohoto okna je již neuvidíte.
style={{ </span>
</Box>
<Box
sx={{
display: "grid", display: "grid",
gridTemplateColumns: "repeat(2, 1fr)", gridTemplateColumns: "repeat(2, 1fr)",
gap: "0.5rem", gap: 1,
padding: "1rem", p: 2,
background: "var(--bg-secondary)", bgcolor: "action.hover",
borderRadius: "0.5rem", borderRadius: 2,
fontFamily: "monospace", fontFamily: "'DM Mono', Menlo, monospace",
fontSize: "1rem", fontSize: "1rem",
}} }}
> >
{backupCodes.map((code) => ( {backupCodes.map((code) => (
<div <Box
key={code} key={code}
style={{ sx={{
padding: "0.25rem 0.5rem", px: 1,
py: 0.5,
textAlign: "center", textAlign: "center",
color: "var(--text-primary)", color: "text.primary",
}} }}
> >
{code} {code}
</div> </Box>
))} ))}
</div> </Box>
<div style={{ marginTop: "0.75rem" }}> <Box sx={{ mt: 1.5 }}>
<button <Button
onClick={() => { onClick={() => {
navigator.clipboard?.writeText(backupCodes.join("\n")); navigator.clipboard?.writeText(backupCodes.join("\n"));
alert.success("Kódy zkopírovány"); alert.success("Kódy zkopírovány");
}} }}
className="admin-btn admin-btn-secondary admin-btn-sm" variant="outlined"
color="inherit"
size="small"
startIcon={CopyIcon}
> >
<svg
width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
>
<rect x="9" y="9" width="13" height="13" rx="2" ry="2" />
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
</svg>
Kopírovat kódy Kopírovat kódy
</button> </Button>
</div> </Box>
{/* Footer is hidden on this step; the single deliberate exit lives </Box>
in the body and also clears the codes. */}
<div style={{ marginTop: "1.25rem", textAlign: "right" }}>
<button
onClick={() => {
setShow2FASetup(false);
setBackupCodes(null);
}}
className="admin-btn admin-btn-primary"
>
Rozumím, uložil jsem si kódy
</button>
</div>
</div>
) : ( ) : (
<div> <Box>
<p <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
className="text-secondary"
style={{ fontSize: "0.875rem", marginBottom: "1rem" }}
>
Naskenujte QR kód v autentizační aplikaci (Google Authenticator, Naskenujte QR kód v autentizační aplikaci (Google Authenticator,
Authy, Microsoft Authenticator apod.) Authy, Microsoft Authenticator apod.)
</p> </Typography>
{totpQrUri && ( {totpQrUri && (
<div style={{ textAlign: "center", marginBottom: "1rem" }}> <Box sx={{ textAlign: "center", mb: 2 }}>
<img <Box
component="img"
src={`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(totpQrUri)}`} src={`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(totpQrUri)}`}
alt="TOTP QR Code" alt="TOTP QR Code"
style={{ sx={{
width: 200, width: 200,
height: 200, height: 200,
borderRadius: "0.5rem", borderRadius: 2,
border: "1px solid var(--border-color)", border: 1,
borderColor: "divider",
}} }}
/> />
</div> </Box>
)} )}
{totpSecret && ( {totpSecret && (
<div className="mb-4"> <Box sx={{ mb: 2 }}>
<label <Typography
className="admin-form-label" component="label"
style={{ fontSize: "0.75rem" }} variant="caption"
color="text.secondary"
sx={{ display: "block", mb: 0.5 }}
> >
Nebo zadejte klíč ručně: Nebo zadejte klíč ručně:
</label> </Typography>
<div <Box
style={{ sx={{
padding: "0.5rem 0.75rem",
background: "var(--bg-secondary)",
borderRadius: "0.375rem",
fontFamily: "monospace",
fontSize: "0.875rem",
wordBreak: "break-all",
color: "var(--text-primary)",
display: "flex", display: "flex",
alignItems: "center", alignItems: "center",
justifyContent: "space-between", justifyContent: "space-between",
gap: "0.5rem", gap: 1,
px: 1.5,
py: 1,
bgcolor: "action.hover",
borderRadius: 1.5,
fontFamily: "'DM Mono', Menlo, monospace",
fontSize: "0.875rem",
wordBreak: "break-all",
color: "text.primary",
}} }}
> >
<span>{totpSecret}</span> <span>{totpSecret}</span>
<button <IconButton
onClick={() => { onClick={() => {
navigator.clipboard?.writeText(totpSecret); navigator.clipboard?.writeText(totpSecret);
alert.success("Klíč zkopírován"); alert.success("Klíč zkopírován");
}} }}
className="admin-btn-icon" size="small"
title="Kopírovat" title="Kopírovat"
aria-label="Kopírovat" aria-label="Kopírovat"
style={{ flexShrink: 0 }} sx={{ flexShrink: 0 }}
> >
<svg {CopyIcon}
width="14" </IconButton>
height="14" </Box>
viewBox="0 0 24 24" </Box>
fill="none"
stroke="currentColor"
strokeWidth="2"
>
<rect x="9" y="9" width="13" height="13" rx="2" ry="2" />
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
</svg>
</button>
</div>
</div>
)} )}
<div className="admin-form-group"> <Field label="Ověřovací kód z aplikace">
<label className="admin-form-label"> <TextField
Ověřovací kód z aplikace inputRef={totpSetupRef}
</label>
<input
ref={totpSetupRef}
type="text"
inputMode="numeric" inputMode="numeric"
pattern="[0-9]*"
maxLength={6}
value={totpCode} value={totpCode}
onChange={(e) => setTotpCode(e.target.value.replace(/\D/g, ""))} onChange={(e) =>
setTotpCode(e.target.value.replace(/\D/g, ""))
}
placeholder="000000" placeholder="000000"
className="admin-form-input" slotProps={{ htmlInput: { maxLength: 6, pattern: "[0-9]*" } }}
style={{ sx={{
"& input": {
textAlign: "center", textAlign: "center",
fontSize: "1.25rem", fontSize: "1.25rem",
letterSpacing: "0.4rem", letterSpacing: "0.4rem",
fontFamily: "monospace", fontFamily: "'DM Mono', Menlo, monospace",
},
}} }}
onKeyDown={(e) => { onKeyDown={(e) => {
if (e.key === "Enter" && totpCode.length === 6) { if (e.key === "Enter" && totpCode.length === 6) {
@@ -567,59 +578,86 @@ export default function DashProfile({
} }
}} }}
/> />
</div> </Field>
</div> </Box>
)} )}
</FormModal> </DialogContent>
{/* Footer is hidden on the backup-codes step; the single deliberate exit
lives in the body actions there. */}
<DialogActions sx={{ px: 3, pb: 2 }}>
{backupCodes ? (
<Button
onClick={() => {
setShow2FASetup(false);
setBackupCodes(null);
}}
>
Rozumím, uložil jsem si kódy
</Button>
) : (
<>
<Button
onClick={() => {
setShow2FASetup(false);
setTotpCode("");
}}
variant="text"
color="inherit"
disabled={totpSubmitting}
>
Zrušit
</Button>
<Button
onClick={onConfirm2FA}
disabled={totpSubmitting || totpCode.length !== 6}
>
{totpSubmitting ? "Ukládám…" : "Aktivovat 2FA"}
</Button>
</>
)}
</DialogActions>
</Dialog>
{/* 2FA Disable Modal */} {/* 2FA Disable Modal */}
<FormModal <Modal
isOpen={show2FADisable} isOpen={show2FADisable}
onClose={() => setShow2FADisable(false)} onClose={() => setShow2FADisable(false)}
title="Deaktivovat 2FA" title="Deaktivovat 2FA"
size="md" maxWidth="sm"
loading={totpSubmitting} loading={totpSubmitting}
onSubmit={onDisable2FA} onSubmit={onDisable2FA}
submitDisabled={disableCode.length !== 6} submitDisabled={disableCode.length !== 6}
submitLabel="Deaktivovat 2FA" submitText="Deaktivovat 2FA"
cancelLabel="Zrušit" cancelText="Zrušit"
>
<p
style={{
color: "var(--text-secondary)",
fontSize: "0.875rem",
marginBottom: "1rem",
}}
> >
<Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
Pro deaktivaci dvoufaktorového ověření zadejte aktuální kód z Pro deaktivaci dvoufaktorového ověření zadejte aktuální kód z
autentizační aplikace. autentizační aplikace.
</p> </Typography>
<div className="admin-form-group"> <Field label="Ověřovací kód">
<label className="admin-form-label">Ověřovací kód</label> <TextField
<input
type="text"
inputMode="numeric" inputMode="numeric"
pattern="[0-9]*"
maxLength={6}
value={disableCode} value={disableCode}
onChange={(e) => setDisableCode(e.target.value.replace(/\D/g, ""))} onChange={(e) => setDisableCode(e.target.value.replace(/\D/g, ""))}
placeholder="000000" placeholder="000000"
className="admin-form-input" autoFocus
style={{ slotProps={{ htmlInput: { maxLength: 6, pattern: "[0-9]*" } }}
sx={{
"& input": {
textAlign: "center", textAlign: "center",
fontSize: "1.25rem", fontSize: "1.25rem",
letterSpacing: "0.4rem", letterSpacing: "0.4rem",
fontFamily: "monospace", fontFamily: "'DM Mono', Menlo, monospace",
},
}} }}
onKeyDown={(e) => { onKeyDown={(e) => {
if (e.key === "Enter" && disableCode.length === 6) { if (e.key === "Enter" && disableCode.length === 6) {
onDisable2FA(); onDisable2FA();
} }
}} }}
autoFocus
/> />
</div> </Field>
</FormModal> </Modal>
</> </>
); );
} }

View File

@@ -1,12 +1,12 @@
import { useState } from "react"; import { useState } from "react";
import { Link } from "react-router-dom"; import { Link as RouterLink } from "react-router-dom";
import { motion } from "framer-motion"; import { motion } from "framer-motion";
import Box from "@mui/material/Box";
import { useAuth } from "../../context/AuthContext"; import { useAuth } from "../../context/AuthContext";
import { useAlert } from "../../context/AlertContext"; import { useAlert } from "../../context/AlertContext";
import { formatKm, todayLocalStr } from "../../utils/formatters"; import { formatKm, todayLocalStr } from "../../utils/formatters";
import AdminDatePicker from "../AdminDatePicker"; import { Button, Modal, Field, Select, DateField, TextField } from "../../ui";
import apiFetch from "../../utils/api"; import apiFetch from "../../utils/api";
import FormModal from "../FormModal";
const API_BASE = "/api/admin"; const API_BASE = "/api/admin";
@@ -46,6 +46,14 @@ interface DashQuickActionsProps {
onPunch: () => void; onPunch: () => void;
} }
// Maps the legacy quick-action color tokens to the MUI Button palette color.
const ACTION_COLOR: Record<string, "success" | "error" | "info" | "warning"> = {
success: "success",
danger: "error",
info: "info",
warning: "warning",
};
export default function DashQuickActions({ export default function DashQuickActions({
dashData, dashData,
punching, punching,
@@ -284,252 +292,192 @@ export default function DashQuickActions({
return ( return (
<> <>
<motion.div <Box
className="dash-quick-actions" component={motion.div}
initial={{ opacity: 0, y: 12 }} initial={{ opacity: 0, y: 12 }}
animate={{ opacity: 1, y: 0 }} animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.25, delay: 0.08 }} transition={{ duration: 0.25, delay: 0.08 }}
sx={{
display: "grid",
gridTemplateColumns: {
xs: "1fr",
sm: "repeat(2, 1fr)",
md: "repeat(4, 1fr)",
},
gap: 2,
mb: 3,
}}
> >
{quickActions.map((action) => {quickActions.map((action) => {
action.onClick ? ( const color = ACTION_COLOR[action.color] ?? "primary";
<button const common = {
variant: "contained" as const,
color,
startIcon: action.icon,
sx: { py: 1.5, justifyContent: "flex-start" },
};
return action.onClick ? (
<Button
key={action.label} key={action.label}
onClick={action.onClick} onClick={action.onClick}
disabled={action.disabled} disabled={action.disabled}
className={`dash-quick-btn dash-quick-btn-${action.color}`} {...common}
> >
{action.icon} {action.label}
<span>{action.label}</span> </Button>
</button>
) : ( ) : (
<Link <Button
key={action.label} key={action.label}
component={RouterLink}
to={action.path!} to={action.path!}
className={`dash-quick-btn dash-quick-btn-${action.color}`} {...common}
> >
{action.icon} {action.label}
<span>{action.label}</span> </Button>
</Link> );
), })}
)} </Box>
</motion.div>
<FormModal <Modal
isOpen={showTripModal} isOpen={showTripModal}
onClose={() => setShowTripModal(false)} onClose={() => setShowTripModal(false)}
title="Přidat jízdu" title="Přidat jízdu"
size="lg" maxWidth="md"
onSubmit={handleTripSubmit} onSubmit={handleTripSubmit}
submitLabel="Uložit" submitText="Uložit"
loading={tripSubmitting} loading={tripSubmitting}
> >
<div className="admin-form"> <Box
<div className="admin-form-row"> sx={{
<div display: "grid",
className={`admin-form-group${tripErrors.vehicle_id ? " has-error" : ""}`} gridTemplateColumns: { xs: "1fr", sm: "1fr 1fr" },
> gap: 2,
<label className="admin-form-label required">Vozidlo</label>
<select
value={tripForm.vehicle_id}
onChange={(e) => {
handleTripVehicleChange(e.target.value);
setTripErrors((prev) => ({
...prev,
vehicle_id: undefined,
}));
}} }}
className="admin-form-select"
> >
<option value="">Vyberte vozidlo</option> <Field label="Vozidlo" required error={tripErrors.vehicle_id}>
{tripVehicles.map((v) => ( <Select
<option key={v.id} value={v.id}> value={tripForm.vehicle_id}
{v.spz} - {v.name} onChange={(val) => {
</option> handleTripVehicleChange(val);
))} setTripErrors((prev) => ({ ...prev, vehicle_id: undefined }));
</select> }}
{tripErrors.vehicle_id && ( options={[
<span className="admin-form-error"> { value: "", label: "Vyberte vozidlo" },
{tripErrors.vehicle_id} ...tripVehicles.map((v) => ({
</span> value: String(v.id),
)} label: `${v.spz} - ${v.name}`,
</div> })),
<div ]}
className={`admin-form-group${tripErrors.trip_date ? " has-error" : ""}`} />
> </Field>
<label className="admin-form-label required">Datum jízdy</label> <Field label="Datum jízdy" required error={tripErrors.trip_date}>
<AdminDatePicker <DateField
mode="date"
value={tripForm.trip_date} value={tripForm.trip_date}
onChange={(val: string) => { onChange={(val) => {
setTripForm((prev) => ({ ...prev, trip_date: val })); setTripForm((prev) => ({ ...prev, trip_date: val }));
setTripErrors((prev) => ({ setTripErrors((prev) => ({ ...prev, trip_date: undefined }));
...prev,
trip_date: undefined,
}));
}} }}
/> />
{tripErrors.trip_date && ( </Field>
<span className="admin-form-error">{tripErrors.trip_date}</span> </Box>
)}
</div>
</div>
<div className="admin-form-row admin-form-row-3"> <Box
<div sx={{
className={`admin-form-group${tripErrors.start_km ? " has-error" : ""}`} display: "grid",
gridTemplateColumns: { xs: "1fr", sm: "repeat(3, 1fr)" },
gap: 2,
}}
> >
<label className="admin-form-label required"> <Field label="Počáteční stav km" required error={tripErrors.start_km}>
Počáteční stav km <TextField
</label>
<input
type="number" type="number"
inputMode="numeric" inputMode="numeric"
value={tripForm.start_km} value={tripForm.start_km}
onChange={(e) => { onChange={(e) => {
setTripForm((prev) => ({ setTripForm((prev) => ({ ...prev, start_km: e.target.value }));
...prev, setTripErrors((prev) => ({ ...prev, start_km: undefined }));
start_km: e.target.value,
}));
setTripErrors((prev) => ({
...prev,
start_km: undefined,
}));
}} }}
className="admin-form-input" slotProps={{ htmlInput: { min: 0 } }}
min="0"
/> />
{tripErrors.start_km && ( </Field>
<span className="admin-form-error">{tripErrors.start_km}</span> <Field label="Konečný stav km" required error={tripErrors.end_km}>
)} <TextField
</div>
<div
className={`admin-form-group${tripErrors.end_km ? " has-error" : ""}`}
>
<label className="admin-form-label required">
Konečný stav km
</label>
<input
type="number" type="number"
inputMode="numeric" inputMode="numeric"
value={tripForm.end_km} value={tripForm.end_km}
onChange={(e) => { onChange={(e) => {
setTripForm((prev) => ({ setTripForm((prev) => ({ ...prev, end_km: e.target.value }));
...prev, setTripErrors((prev) => ({ ...prev, end_km: undefined }));
end_km: e.target.value,
}));
setTripErrors((prev) => ({
...prev,
end_km: undefined,
}));
}} }}
className="admin-form-input" slotProps={{ htmlInput: { min: 0 } }}
min="0"
/> />
{tripErrors.end_km && ( </Field>
<span className="admin-form-error">{tripErrors.end_km}</span> <Field label="Vzdálenost">
)} <TextField
</div>
<div className="admin-form-group">
<label className="admin-form-label">Vzdálenost</label>
<input
type="text"
value={`${formatKm(tripDistance())} km`} value={`${formatKm(tripDistance())} km`}
className="admin-form-input" InputProps={{ readOnly: true }}
readOnly
disabled disabled
/> />
</div> </Field>
</div> </Box>
<div className="admin-form-row"> <Box
<div sx={{
className={`admin-form-group${tripErrors.route_from ? " has-error" : ""}`} display: "grid",
gridTemplateColumns: { xs: "1fr", sm: "1fr 1fr" },
gap: 2,
}}
> >
<label className="admin-form-label required">Místo odjezdu</label> <Field label="Místo odjezdu" required error={tripErrors.route_from}>
<input <TextField
type="text"
value={tripForm.route_from} value={tripForm.route_from}
onChange={(e) => { onChange={(e) => {
setTripForm((prev) => ({ setTripForm((prev) => ({
...prev, ...prev,
route_from: e.target.value, route_from: e.target.value,
})); }));
setTripErrors((prev) => ({ setTripErrors((prev) => ({ ...prev, route_from: undefined }));
...prev,
route_from: undefined,
}));
}} }}
className="admin-form-input"
placeholder="Např. Praha" placeholder="Např. Praha"
/> />
{tripErrors.route_from && ( </Field>
<span className="admin-form-error"> <Field label="Místo příjezdu" required error={tripErrors.route_to}>
{tripErrors.route_from} <TextField
</span>
)}
</div>
<div
className={`admin-form-group${tripErrors.route_to ? " has-error" : ""}`}
>
<label className="admin-form-label required">
Místo příjezdu
</label>
<input
type="text"
value={tripForm.route_to} value={tripForm.route_to}
onChange={(e) => { onChange={(e) => {
setTripForm((prev) => ({ setTripForm((prev) => ({ ...prev, route_to: e.target.value }));
...prev, setTripErrors((prev) => ({ ...prev, route_to: undefined }));
route_to: e.target.value,
}));
setTripErrors((prev) => ({
...prev,
route_to: undefined,
}));
}} }}
className="admin-form-input"
placeholder="Např. Brno" placeholder="Např. Brno"
/> />
{tripErrors.route_to && ( </Field>
<span className="admin-form-error">{tripErrors.route_to}</span> </Box>
)}
</div>
</div>
<div className="admin-form-group"> <Field label="Typ jízdy">
<label className="admin-form-label">Typ jízdy</label> <Select
<select value={String(tripForm.is_business)}
value={tripForm.is_business} onChange={(val) =>
onChange={(e) => setTripForm((prev) => ({ ...prev, is_business: parseInt(val) }))
setTripForm((prev) => ({
...prev,
is_business: parseInt(e.target.value),
}))
} }
className="admin-form-select" options={[
> { value: "1", label: "Služební" },
<option value={1}>Služební</option> { value: "0", label: "Soukromá" },
<option value={0}>Soukromá</option> ]}
</select> />
</div> </Field>
<div className="admin-form-group"> <Field label="Poznámky">
<label className="admin-form-label">Poznámky</label> <TextField
<textarea multiline
minRows={2}
value={tripForm.notes} value={tripForm.notes}
onChange={(e) => onChange={(e) =>
setTripForm((prev) => ({ setTripForm((prev) => ({ ...prev, notes: e.target.value }))
...prev,
notes: e.target.value,
}))
} }
className="admin-form-textarea"
rows={2}
placeholder="Volitelné poznámky..." placeholder="Volitelné poznámky..."
/> />
</div> </Field>
</div> </Modal>
</FormModal>
</> </>
); );
} }

View File

@@ -1,9 +1,12 @@
import { useState } from "react"; import { useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query"; import { useQuery, useQueryClient } 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 IconButton from "@mui/material/IconButton";
import CircularProgress from "@mui/material/CircularProgress";
import { useAlert } from "../../context/AlertContext"; import { useAlert } from "../../context/AlertContext";
import ConfirmModal from "../ConfirmModal"; import { Card, Button, StatusChip, ConfirmDialog } from "../../ui";
import useModalLock from "../../hooks/useModalLock";
import apiFetch from "../../utils/api"; import apiFetch from "../../utils/api";
import { formatSessionDate } from "../../utils/dashboardHelpers"; import { formatSessionDate } from "../../utils/dashboardHelpers";
import { sessionsOptions, type Session } from "../../lib/queries/dashboard"; import { sessionsOptions, type Session } from "../../lib/queries/dashboard";
@@ -76,8 +79,6 @@ export default function DashSessions() {
const [deleteAllModal, setDeleteAllModal] = useState(false); const [deleteAllModal, setDeleteAllModal] = useState(false);
const [deleting, setDeleting] = useState(false); const [deleting, setDeleting] = useState(false);
useModalLock(deleteAllModal);
const handleDeleteSession = async () => { const handleDeleteSession = async () => {
if (!deleteModal.session) { if (!deleteModal.session) {
return; return;
@@ -127,85 +128,114 @@ export default function DashSessions() {
return ( return (
<> <>
<motion.div <motion.div
className="admin-card"
initial={{ opacity: 0, y: 12 }} initial={{ opacity: 0, y: 12 }}
animate={{ opacity: 1, y: 0 }} animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.25, delay: 0.15 }} transition={{ duration: 0.25, delay: 0.15 }}
> >
<div <Card sx={{ display: "flex", flexDirection: "column" }}>
className="admin-card-header" <Box
style={{ sx={{
display: "flex", display: "flex",
alignItems: "center", alignItems: "center",
justifyContent: "space-between", justifyContent: "space-between",
gap: "0.75rem", gap: 1.5,
mb: 2,
}} }}
> >
<h2 className="admin-card-title">Přihlášená zařízení</h2> <Typography variant="h6">Přihlášená zařízení</Typography>
{sessions.filter((s) => !s.is_current).length > 0 && ( {sessions.filter((s) => !s.is_current).length > 0 && (
<button <Button
onClick={() => setDeleteAllModal(true)} onClick={() => setDeleteAllModal(true)}
className="admin-btn admin-btn-secondary admin-btn-sm" variant="outlined"
color="inherit"
size="small"
sx={{ flexShrink: 0 }}
> >
Odhlásit ostatní Odhlásit ostatní
</button> </Button>
)} )}
</div> </Box>
<div className="admin-card-body" style={{ padding: 0 }}>
{sessionsLoading ? ( {sessionsLoading ? (
<div className="admin-loading"> <Box sx={{ display: "flex", justifyContent: "center", py: 3 }}>
<div className="admin-spinner" /> <CircularProgress size={28} />
</div> </Box>
) : ( ) : sessions.length === 0 ? (
<> <Typography
{sessions.length === 0 && ( variant="body2"
<div color="text.secondary"
className="text-secondary" sx={{ textAlign: "center", py: 3 }}
style={{
padding: "1.5rem",
textAlign: "center",
fontSize: "0.875rem",
}}
> >
Žádné aktivní relace Žádné aktivní relace
</div> </Typography>
)} ) : (
{sessions.length > 0 && ( <Box sx={{ display: "flex", flexDirection: "column" }}>
<div className="dash-sessions-list">
{sessions.map((session) => ( {sessions.map((session) => (
<div <Box
key={session.id} key={session.id}
className={`dash-session-item ${session.is_current ? "dash-session-item-current" : ""}`} sx={{
display: "flex",
alignItems: "center",
gap: 1.5,
py: 1.25,
borderBottom: 1,
borderColor: "divider",
"&:last-of-type": { borderBottom: 0 },
...(session.is_current
? { bgcolor: "action.hover", borderRadius: 2, px: 1 }
: {}),
}}
>
<Box
sx={{
display: "flex",
alignItems: "center",
justifyContent: "center",
color: "text.secondary",
flexShrink: 0,
}}
> >
<div className="dash-session-icon">
{getDeviceIcon(session.device_info?.icon)} {getDeviceIcon(session.device_info?.icon)}
</div> </Box>
<div className="dash-session-info"> <Box sx={{ flex: 1, minWidth: 0 }}>
<div className="dash-session-device"> <Box
sx={{
display: "flex",
alignItems: "center",
gap: 1,
flexWrap: "wrap",
}}
>
<Typography variant="body2" sx={{ fontWeight: 500 }}>
{session.device_info?.browser} na{" "} {session.device_info?.browser} na{" "}
{session.device_info?.os} {session.device_info?.os}
</Typography>
{session.is_current && ( {session.is_current && (
<span <StatusChip color="success" label="Aktuální" />
className="admin-badge admin-badge-success"
style={{ marginLeft: "0.5rem" }}
>
Aktuální
</span>
)} )}
</div> </Box>
<div className="dash-session-meta"> <Box
sx={{
display: "flex",
alignItems: "center",
gap: 0.75,
color: "text.secondary",
fontSize: "0.75rem",
}}
>
<span>{session.ip_address}</span> <span>{session.ip_address}</span>
<span className="dash-session-meta-separator">|</span> <span>|</span>
<span>{formatSessionDate(session.created_at)}</span> <span>{formatSessionDate(session.created_at)}</span>
</div> </Box>
</div> </Box>
<div className="dash-session-actions"> <Box sx={{ flexShrink: 0 }}>
{!session.is_current && ( {!session.is_current && (
<button <IconButton
onClick={() => onClick={() =>
setDeleteModal({ isOpen: true, session }) setDeleteModal({ isOpen: true, session })
} }
className="admin-btn-icon danger" color="error"
size="small"
title="Ukončit relaci" title="Ukončit relaci"
aria-label="Ukončit relaci" aria-label="Ukončit relaci"
> >
@@ -221,19 +251,17 @@ export default function DashSessions() {
<polyline points="16 17 21 12 16 7" /> <polyline points="16 17 21 12 16 7" />
<line x1="21" y1="12" x2="9" y2="12" /> <line x1="21" y1="12" x2="9" y2="12" />
</svg> </svg>
</button> </IconButton>
)} )}
</div> </Box>
</div> </Box>
))} ))}
</div> </Box>
)} )}
</> </Card>
)}
</div>
</motion.div> </motion.div>
<ConfirmModal <ConfirmDialog
isOpen={deleteModal.isOpen} isOpen={deleteModal.isOpen}
onClose={() => setDeleteModal({ isOpen: false, session: null })} onClose={() => setDeleteModal({ isOpen: false, session: null })}
onConfirm={handleDeleteSession} onConfirm={handleDeleteSession}
@@ -241,10 +269,10 @@ export default function DashSessions() {
message={`Opravdu chcete ukončit relaci na zařízení "${deleteModal.session?.device_info?.browser} na ${deleteModal.session?.device_info?.os}"? Toto zařízení bude odhlášeno.`} message={`Opravdu chcete ukončit relaci na zařízení "${deleteModal.session?.device_info?.browser} na ${deleteModal.session?.device_info?.os}"? Toto zařízení bude odhlášeno.`}
confirmText="Ukončit" confirmText="Ukončit"
cancelText="Zrušit" cancelText="Zrušit"
type="danger" confirmVariant="danger"
loading={deleting} loading={deleting}
/> />
<ConfirmModal <ConfirmDialog
isOpen={deleteAllModal} isOpen={deleteAllModal}
onClose={() => setDeleteAllModal(false)} onClose={() => setDeleteAllModal(false)}
onConfirm={handleDeleteAllSessions} onConfirm={handleDeleteAllSessions}
@@ -252,7 +280,7 @@ export default function DashSessions() {
message="Opravdu chcete ukončit všechny ostatní relace? Budete odhlášeni ze všech zařízení kromě tohoto." message="Opravdu chcete ukončit všechny ostatní relace? Budete odhlášeni ze všech zařízení kromě tohoto."
confirmText="Odhlásit vše" confirmText="Odhlásit vše"
cancelText="Zrušit" cancelText="Zrušit"
type="warning" confirmVariant="primary"
loading={deleting} loading={deleting}
/> />
</> </>

View File

@@ -1,15 +1,18 @@
import { useState, useCallback } from "react"; import { useState, useCallback } from "react";
import { Link } from "react-router-dom"; import { Link as RouterLink } from "react-router-dom";
import { motion } from "framer-motion"; import { motion } from "framer-motion";
import { useQuery, useQueryClient } from "@tanstack/react-query"; import { useQuery, useQueryClient } from "@tanstack/react-query";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import CircularProgress from "@mui/material/CircularProgress";
import { useAuth } from "../context/AuthContext"; import { useAuth } from "../context/AuthContext";
import { useAlert } from "../context/AlertContext"; import { useAlert } from "../context/AlertContext";
import useModalLock from "../hooks/useModalLock";
import apiFetch from "../utils/api"; import apiFetch from "../utils/api";
import { dashboardOptions } from "../lib/queries/dashboard"; import { dashboardOptions } from "../lib/queries/dashboard";
import { require2FAOptions } from "../lib/queries/settings"; import { require2FAOptions } from "../lib/queries/settings";
import { getCzechDate } from "../utils/dashboardHelpers"; import { getCzechDate } from "../utils/dashboardHelpers";
import { useApiMutation } from "../lib/queries/mutations"; import { useApiMutation } from "../lib/queries/mutations";
import { Card, Button, StatusChip } from "../ui";
import DashKpiCards from "../components/dashboard/DashKpiCards"; import DashKpiCards from "../components/dashboard/DashKpiCards";
import DashQuickActions from "../components/dashboard/DashQuickActions"; import DashQuickActions from "../components/dashboard/DashQuickActions";
import DashActivityFeed from "../components/dashboard/DashActivityFeed"; import DashActivityFeed from "../components/dashboard/DashActivityFeed";
@@ -102,9 +105,6 @@ export default function Dashboard() {
const [backupCodes, setBackupCodes] = useState<string[] | null>(null); const [backupCodes, setBackupCodes] = useState<string[] | null>(null);
const [disableCode, setDisableCode] = useState(""); const [disableCode, setDisableCode] = useState("");
useModalLock(show2FASetup);
useModalLock(show2FADisable);
// Punch (prichod/odchod) primo z dashboardu // Punch (prichod/odchod) primo z dashboardu
const handleQuickPunch = useCallback(() => { const handleQuickPunch = useCallback(() => {
const action = dashData?.my_shift?.has_ongoing ? "departure" : "arrival"; const action = dashData?.my_shift?.has_ongoing ? "departure" : "arrival";
@@ -221,55 +221,58 @@ export default function Dashboard() {
}; };
return ( return (
<div className="dash"> <Box>
{/* Header */} {/* Header */}
<motion.div <Box
className="admin-page-header" component={motion.div}
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 }}
sx={{ mb: 3 }}
> >
<div> <Typography variant="h4">
<h1 className="admin-page-title">
Vítejte zpět, {user?.fullName || user?.username} Vítejte zpět, {user?.fullName || user?.username}
</h1> </Typography>
<p className="admin-page-subtitle">{getCzechDate()}</p> <Typography variant="body2" color="text.secondary" sx={{ mt: 0.5 }}>
</div> {getCzechDate()}
</motion.div> </Typography>
</Box>
{/* 2FA Required Banner */} {/* 2FA Required Banner */}
{user?.require2FA && !user?.totpEnabled && ( {user?.require2FA && !user?.totpEnabled && (
<motion.div <motion.div
className="admin-card"
initial={{ opacity: 0, y: 12 }} initial={{ opacity: 0, y: 12 }}
animate={{ opacity: 1, y: 0 }} animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.25, delay: 0.06 }} transition={{ duration: 0.25, delay: 0.06 }}
style={{ >
border: "2px solid var(--danger)", <Card
background: "var(--danger-light)", sx={{
mb: 3,
border: 2,
borderColor: "error.main",
bgcolor: "error.light",
}} }}
> >
<div <Box
className="admin-card-body" sx={{
style={{
display: "flex", display: "flex",
alignItems: "center", alignItems: "center",
justifyContent: "space-between", justifyContent: "space-between",
gap: "1rem", gap: 2,
flexWrap: "wrap", flexWrap: "wrap",
}} }}
> >
<div className="flex-row-gap"> <Box sx={{ display: "flex", alignItems: "center", gap: 1.5 }}>
<div <Box
style={{ sx={{
width: 40, width: 40,
height: 40, height: 40,
borderRadius: "50%", borderRadius: "50%",
display: "flex", display: "flex",
alignItems: "center", alignItems: "center",
justifyContent: "center", justifyContent: "center",
background: "var(--danger-light)", bgcolor: "error.light",
color: "var(--danger)", color: "error.main",
flexShrink: 0, flexShrink: 0,
}} }}
> >
@@ -285,35 +288,34 @@ export default function Dashboard() {
<line x1="12" y1="9" x2="12" y2="13" /> <line x1="12" y1="9" x2="12" y2="13" />
<line x1="12" y1="17" x2="12.01" y2="17" /> <line x1="12" y1="17" x2="12.01" y2="17" />
</svg> </svg>
</div> </Box>
<div> <Box>
<div className="fw-600">Dvoufaktorové ověření je povinné</div> <Typography sx={{ fontWeight: 600 }}>
<div Dvoufaktorové ověření je povinné
className="text-secondary" </Typography>
style={{ fontSize: "0.875rem" }} <Typography variant="body2" color="text.secondary">
>
Administrátor vyžaduje aktivaci 2FA. Dokud ji neaktivujete, Administrátor vyžaduje aktivaci 2FA. Dokud ji neaktivujete,
nemáte přístup k ostatním sekcím systému. nemáte přístup k ostatním sekcím systému.
</div> </Typography>
</div> </Box>
</div> </Box>
<button <Button
onClick={handleStart2FASetup} onClick={handleStart2FASetup}
disabled={totpSubmitting} disabled={totpSubmitting}
className="admin-btn admin-btn-primary" sx={{ flexShrink: 0 }}
style={{ flexShrink: 0 }}
> >
{totpSubmitting ? "Generuji..." : "Aktivovat 2FA nyní"} {totpSubmitting ? "Generuji..." : "Aktivovat 2FA nyní"}
</button> </Button>
</div> </Box>
</Card>
</motion.div> </motion.div>
)} )}
{/* Loading spinner */} {/* Loading spinner */}
{dashLoading && ( {dashLoading && (
<div className="admin-loading"> <Box sx={{ display: "flex", justifyContent: "center", py: 6 }}>
<div className="admin-spinner" /> <CircularProgress />
</div> </Box>
)} )}
{/* KPI cards — only show if user has any admin-level permissions */} {/* KPI cards — only show if user has any admin-level permissions */}
@@ -336,11 +338,18 @@ export default function Dashboard() {
{/* Main content grid */} {/* Main content grid */}
{!dashLoading && ( {!dashLoading && (
<motion.div <Box
className="dash-main-grid" component={motion.div}
initial={{ opacity: 0, y: 12 }} initial={{ opacity: 0, y: 12 }}
animate={{ opacity: 1, y: 0 }} animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.25, delay: 0.12 }} transition={{ duration: 0.25, delay: 0.12 }}
sx={{
display: "grid",
gridTemplateColumns: { xs: "1fr", lg: "1fr 1fr 1fr" },
gap: 3,
alignItems: "start",
mb: 3,
}}
> >
{hasPermission("settings.audit") && ( {hasPermission("settings.audit") && (
<DashActivityFeed activities={dashData?.recent_activity ?? null} /> <DashActivityFeed activities={dashData?.recent_activity ?? null} />
@@ -351,86 +360,146 @@ export default function Dashboard() {
)} )}
{/* Pravy sloupec: projekty + nabidky */} {/* Pravy sloupec: projekty + nabidky */}
<div className="dash-right-col"> <Box sx={{ display: "flex", flexDirection: "column", gap: 3 }}>
{dashData?.projects && ( {dashData?.projects && (
<div className="admin-card"> <Card sx={{ display: "flex", flexDirection: "column" }}>
<div className="admin-card-header flex-between"> <Box
<h2 className="admin-card-title">Aktivní projekty</h2> sx={{
<Link display: "flex",
alignItems: "center",
justifyContent: "space-between",
mb: 2,
}}
>
<Typography variant="h6">Aktivní projekty</Typography>
<Button
component={RouterLink}
to="/projects" to="/projects"
className="admin-btn admin-btn-primary admin-btn-sm" size="small"
sx={{ flexShrink: 0 }}
> >
Vše &rarr; Vše &rarr;
</Link> </Button>
</div> </Box>
<div className="admin-card-body" style={{ padding: 0 }}>
{dashData.projects.active_projects.length === 0 && ( {dashData.projects.active_projects.length === 0 && (
<div className="dash-empty-row">Žádné aktivní projekty</div> <Typography
)} variant="body2"
{dashData.projects.active_projects.map( color="text.secondary"
(p: { sx={{ py: 1 }}
id: number;
name: string;
customer_name: string | null;
}) => (
<Link
key={p.id}
to={`/projects/${p.id}`}
className="dash-project-row"
> >
<div className="dash-project-name">{p.name}</div> Žádné aktivní projekty
</Typography>
)}
{dashData.projects.active_projects.map((p) => (
<Box
key={p.id}
component={RouterLink}
to={`/projects/${p.id}`}
sx={{
display: "block",
py: 1.25,
textDecoration: "none",
color: "inherit",
borderBottom: 1,
borderColor: "divider",
"&:last-of-type": { borderBottom: 0 },
"&:hover": { color: "primary.main" },
}}
>
<Typography variant="body2" sx={{ fontWeight: 500 }}>
{p.name}
</Typography>
{p.customer_name && ( {p.customer_name && (
<div className="dash-project-customer"> <Typography variant="caption" color="text.secondary">
{p.customer_name} {p.customer_name}
</div> </Typography>
)} )}
</Link> </Box>
), ))}
)} </Card>
</div>
</div>
)} )}
{dashData?.offers && ( {dashData?.offers && (
<div className="admin-card"> <Card sx={{ display: "flex", flexDirection: "column" }}>
<div className="admin-card-header flex-between"> <Box
<h2 className="admin-card-title">Nabídky</h2> sx={{
<Link display: "flex",
alignItems: "center",
justifyContent: "space-between",
mb: 2,
}}
>
<Typography variant="h6">Nabídky</Typography>
<Button
component={RouterLink}
to="/offers" to="/offers"
className="admin-btn admin-btn-primary admin-btn-sm" size="small"
sx={{ flexShrink: 0 }}
> >
Zobrazit &rarr; Zobrazit &rarr;
</Link> </Button>
</div> </Box>
<div className="admin-card-body" style={{ padding: 0 }}> <Box
<div className="dash-stat-row"> sx={{
<span>Otevřené</span> display: "flex",
<span className="admin-badge admin-badge-info"> alignItems: "center",
{dashData.offers.open_count} justifyContent: "space-between",
</span> py: 1,
</div> borderBottom: 1,
<div className="dash-stat-row"> borderColor: "divider",
<span>Převedené na objednávku</span> }}
<span className="admin-badge admin-badge-success"> >
{dashData.offers.converted_count} <Typography variant="body2">Otevřené</Typography>
</span> <StatusChip color="info" label={dashData.offers.open_count} />
</div> </Box>
<div className="dash-stat-row"> <Box
<span>Zneplatněné</span> sx={{
<span className="admin-badge admin-badge-warning"> display: "flex",
{dashData.offers.expired_count} alignItems: "center",
</span> justifyContent: "space-between",
</div> py: 1,
</div> borderBottom: 1,
</div> borderColor: "divider",
}}
>
<Typography variant="body2">
Převedené na objednávku
</Typography>
<StatusChip
color="success"
label={dashData.offers.converted_count}
/>
</Box>
<Box
sx={{
display: "flex",
alignItems: "center",
justifyContent: "space-between",
py: 1,
}}
>
<Typography variant="body2">Zneplatněné</Typography>
<StatusChip
color="warning"
label={dashData.offers.expired_count}
/>
</Box>
</Card>
)} )}
</div> </Box>
</motion.div> </Box>
)} )}
{/* Profile + Sessions */} {/* Profile + Sessions */}
{!dashLoading && ( {!dashLoading && (
<div className="dash-bottom"> <Box
sx={{
display: "grid",
gridTemplateColumns: { xs: "1fr", lg: "1fr 1fr" },
gap: 3,
alignItems: "start",
}}
>
<DashProfile <DashProfile
totpEnabled={totpEnabled} totpEnabled={totpEnabled}
totpLoading={totpLoading} totpLoading={totpLoading}
@@ -452,8 +521,8 @@ export default function Dashboard() {
setDisableCode={setDisableCode} setDisableCode={setDisableCode}
/> />
<DashSessions /> <DashSessions />
</div> </Box>
)} )}
</div> </Box>
); );
} }