Files
parking_solution/apps/web/src/UsersManager.tsx
T
julian ae736a9e3e feat(shift): current shift in the list + modal actions; full-width layout everywhere
Shift screen:
- The standalone ShiftControl block is gone from /shift. The open/CURRENT shift now
  appears at the TOP of the shift list (CURRENT badge, live figures synthesized from
  the X-report), unified with history. Selecting it shows its live activity log.
- Shift ACTIONS moved into the current shift's detail pane, each opening a MODAL:
  End shift (confirm → signed Z-report result), drawer voucher (Mandat in/out),
  takings-so-far (X-report). When no shift is open, a Start-shift button shows.
- The current shift's log auto-refreshes (5s); a closed shift is bounded by its
  window. /setup/shifts stays read-only history (no manage props). Deleted the now-
  orphaned ShiftControl.tsx.

Layout:
- Every screen is now full-width like /booth — stripped the per-screen
  `mx-auto max-w-*` caps (Logs, Subscriptions, Plans, Tariff, Users, Roles, Setup
  layout, Shifts). The shell <main> already provides padding.

Build+lint 12/12 (i18n parity). Verified a live open shift surfaces as the CURRENT
list entry.

Claude-Session: https://claude.ai/code/session_01Xcm6ikLgGoCxxHrxtjkk5V
2026-06-20 23:44:27 +02:00

321 lines
11 KiB
TypeScript

import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
ApiError,
can,
createUser,
deleteUser,
fetchRoles,
fetchUsers,
resetUserPassword,
updateUser,
type ManagedRole,
type ManagedUser,
type SessionUser,
} from "./api.js";
import { Modal } from "./ui/Modal.js";
// User management (admin). List users, create one (username + password + role),
// change a user's role, reset a password, delete. The server enforces the same
// permissions and the no-lockout rule (the last admin can't be removed). See
// wiki/entities/local-jwt-auth.md.
export function UsersManager({ user }: { user: SessionUser | null }) {
const { t } = useTranslation();
const qc = useQueryClient();
const usersQ = useQuery({ queryKey: ["users"], queryFn: fetchUsers });
const rolesQ = useQuery({ queryKey: ["roles"], queryFn: fetchRoles });
const canCreate = can(user, "user:create");
const canUpdate = can(user, "user:update");
const canDelete = can(user, "user:delete");
const roles: ManagedRole[] = rolesQ.data?.roles ?? [];
const [error, setError] = useState<string | null>(null);
const [adding, setAdding] = useState(false);
const [editingUser, setEditingUser] = useState<ManagedUser | null>(null);
const invalidate = () => void qc.invalidateQueries({ queryKey: ["users"] });
const onError = (e: unknown) =>
setError(e instanceof ApiError ? e.message : (e as Error).message);
return (
<div className="">
<div className="mb-3 flex items-center justify-between">
<h1 className="text-sm font-bold uppercase tracking-widest text-term-amber">{t("users.title")}</h1>
{canCreate && roles.length > 0 && (
<button type="button" className="btn btn-go btn-sm" onClick={() => { setAdding(true); setError(null); }}>
{t("users.add")}
</button>
)}
</div>
{error && <div className="mb-2 rounded-term border border-term-red px-3 py-2 text-[12px] text-term-red">{error}</div>}
<Modal open={adding} onClose={() => setAdding(false)} title={t("users.new")} width="max-w-2xl">
<UserForm
roles={roles}
onCancel={() => setAdding(false)}
onSubmit={async (v) => {
try {
await createUser({
username: v.username,
password: v.password!,
roleId: v.roleId,
fullName: v.fullName,
phone: v.phone,
email: v.email,
address: v.address,
});
setAdding(false);
invalidate();
} catch (e) { onError(e); }
}}
/>
</Modal>
<Modal open={editingUser != null} onClose={() => setEditingUser(null)} title={t("users.editTitle")} width="max-w-2xl">
{editingUser && (
<UserForm
roles={roles}
editing={editingUser}
onCancel={() => setEditingUser(null)}
onSubmit={async (v) => {
try {
await updateUser(editingUser.id, {
username: v.username,
roleId: v.roleId,
fullName: v.fullName,
phone: v.phone,
email: v.email,
address: v.address,
});
setEditingUser(null);
invalidate();
} catch (e) { onError(e); }
}}
/>
)}
</Modal>
<div className="overflow-hidden rounded-term border border-term-border">
<table className="w-full text-[12px]">
<thead className="bg-term-panel-2 text-[11px] uppercase tracking-wider text-term-muted">
<tr>
<th className="px-3 py-1.5 text-left">{t("users.username")}</th>
<th className="px-3 py-1.5 text-left">{t("users.role")}</th>
<th className="px-3 py-1.5 text-right">{t("common.none")}</th>
</tr>
</thead>
<tbody>
{(usersQ.data?.users ?? []).map((u) => (
<UserRow
key={u.id}
u={u}
roles={roles}
canUpdate={canUpdate}
canDelete={canDelete}
onEdit={() => { setEditingUser(u); setError(null); }}
onChanged={invalidate}
onError={onError}
/>
))}
{usersQ.data?.users.length === 0 && (
<tr><td colSpan={3} className="px-3 py-3 text-term-muted">{t("users.none")}</td></tr>
)}
</tbody>
</table>
</div>
</div>
);
}
function UserRow({
u, roles, canUpdate, canDelete, onEdit, onChanged, onError,
}: {
u: ManagedUser;
roles: ManagedRole[];
canUpdate: boolean;
canDelete: boolean;
onEdit: () => void;
onChanged: () => void;
onError: (e: unknown) => void;
}) {
const { t } = useTranslation();
const [resetting, setResetting] = useState(false);
const [pw, setPw] = useState("");
const roleMut = useMutation({
mutationFn: (roleId: string) => updateUser(u.id, { roleId }),
onSuccess: onChanged,
onError,
});
const pwMut = useMutation({
mutationFn: () => resetUserPassword(u.id, pw),
onSuccess: () => { setResetting(false); setPw(""); },
onError,
});
const delMut = useMutation({
mutationFn: () => deleteUser(u.id),
onSuccess: onChanged,
onError,
});
return (
<tr className="border-t border-term-border">
<td className="px-3 py-1.5">
{u.username}
{u.fullName && <span className="ml-2 text-term-muted">{u.fullName}</span>}
</td>
<td className="px-3 py-1.5">
{canUpdate ? (
<select
value={u.roleId}
onChange={(e) => roleMut.mutate(e.target.value)}
className="select input-sm w-auto"
>
{roles.map((r) => <option key={r.id} value={r.id}>{r.name}</option>)}
</select>
) : (
u.roleName
)}
</td>
<td className="px-3 py-1.5 text-right">
<div className="flex justify-end gap-2">
{canUpdate && !resetting && (
<button type="button" className="btn btn-ghost btn-sm" onClick={onEdit}>
{t("users.edit")}
</button>
)}
{canUpdate && !resetting && (
<button type="button" className="btn btn-ghost btn-sm" onClick={() => setResetting(true)}>
{t("users.resetPassword")}
</button>
)}
{canUpdate && resetting && (
<span className="flex items-center gap-1">
<input
type="password" value={pw} autoFocus
onChange={(e) => setPw(e.target.value)}
placeholder={t("users.newPassword")}
className="input input-sm w-32"
/>
<button type="button" className="btn btn-go btn-sm" disabled={pw.length < 8 || pwMut.isPending} onClick={() => pwMut.mutate()}>
{t("common.save")}
</button>
<button type="button" className="btn btn-ghost btn-sm" onClick={() => { setResetting(false); setPw(""); }}>✕</button>
</span>
)}
{canDelete && (
<button
type="button"
className="btn btn-danger btn-sm"
onClick={() => { if (confirm(t("users.confirmDelete", { name: u.username }))) delMut.mutate(); }}
>
{t("users.delete")}
</button>
)}
</div>
</td>
</tr>
);
}
/** Submitted form value. `password` is omitted entirely on edit (a blank field must
* not blank the password — that's the separate "reset password" flow). */
interface UserFormValue {
username: string;
password?: string;
roleId: string;
fullName: string;
phone: string;
email: string;
address: string;
}
function UserForm({
roles, editing, onCancel, onSubmit,
}: {
roles: ManagedRole[];
/** When set, the form edits this user (username/role/details; NOT the password). */
editing?: ManagedUser;
onCancel: () => void;
onSubmit: (v: UserFormValue) => void;
}) {
const { t } = useTranslation();
const isEdit = editing != null;
const [username, setUsername] = useState(editing?.username ?? "");
const [password, setPassword] = useState("");
const [roleId, setRoleId] = useState(editing?.roleId ?? roles[0]?.id ?? "");
const [fullName, setFullName] = useState(editing?.fullName ?? "");
const [phone, setPhone] = useState(editing?.phone ?? "");
const [email, setEmail] = useState(editing?.email ?? "");
const [address, setAddress] = useState(editing?.address ?? "");
// On create, a >=8 char password is required; on edit it's left untouched.
const valid = username.trim().length > 0 && roleId && (isEdit || password.length >= 8);
function submit() {
onSubmit({
username: username.trim(),
...(isEdit ? {} : { password }),
roleId,
fullName,
phone,
email,
address,
});
}
return (
<div>
<div className="grid grid-cols-3 gap-3">
<div className="field">
<span className="label">{t("users.username")}</span>
<input className="input" value={username} onChange={(e) => setUsername(e.target.value)} />
</div>
{!isEdit && (
<div className="field">
<span className="label">{t("users.password")}</span>
<input className="input" type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
</div>
)}
<div className="field">
<span className="label">{t("users.role")}</span>
<select className="select" value={roleId} onChange={(e) => setRoleId(e.target.value)}>
{roles.map((r) => <option key={r.id} value={r.id}>{r.name}</option>)}
</select>
</div>
</div>
{!isEdit && <div className="hint mt-1">{t("users.passwordHint")}</div>}
{/* Optional profile metadata. */}
<div className="mt-4 mb-2 text-[11px] uppercase tracking-wider text-term-muted">{t("users.detailsSection")}</div>
<div className="grid grid-cols-2 gap-3">
<div className="field">
<span className="label">{t("users.fullName")}</span>
<input className="input" value={fullName} onChange={(e) => setFullName(e.target.value)} />
</div>
<div className="field">
<span className="label">{t("users.phone")}</span>
<input className="input" value={phone} onChange={(e) => setPhone(e.target.value)} />
</div>
<div className="field">
<span className="label">{t("users.email")}</span>
<input className="input" type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
</div>
<div className="field">
<span className="label">{t("users.address")}</span>
<input className="input" value={address} onChange={(e) => setAddress(e.target.value)} />
</div>
</div>
<div className="mt-4 flex justify-end gap-2">
<button type="button" className="btn btn-sm" onClick={onCancel}>{t("common.cancel")}</button>
<button type="button" className="btn btn-primary btn-sm" disabled={!valid} onClick={submit}>{t("common.save")}</button>
</div>
</div>
);
}