feat: split settings management pages
This commit is contained in:
7
app/(app)/app/loading.tsx
Normal file
7
app/(app)/app/loading.tsx
Normal file
@@ -0,0 +1,7 @@
|
||||
export default function AppLoading(): React.ReactElement {
|
||||
return (
|
||||
<div className="fixed inset-x-0 top-0 z-50 h-1 overflow-hidden bg-secondary">
|
||||
<div className="loading-progress h-full bg-primary" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
100
app/(app)/app/settings/audit/page.tsx
Normal file
100
app/(app)/app/settings/audit/page.tsx
Normal file
@@ -0,0 +1,100 @@
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { getCurrentAuthContext } from "@/modules/core/server/auth";
|
||||
import { hasPermission } from "@/modules/core/server/permissions";
|
||||
import { readData } from "@/modules/core/server/store";
|
||||
import { TableToolbar } from "@/modules/settings/components/TableToolbar";
|
||||
import { getPage, getPageCount, getSearchParam, paginate, type SearchParams } from "@/modules/settings/lib/pagination";
|
||||
|
||||
type AuditPageProps = {
|
||||
searchParams?: Promise<SearchParams>;
|
||||
};
|
||||
|
||||
export default async function AuditPage({ searchParams }: AuditPageProps): Promise<React.ReactElement> {
|
||||
const context = await getCurrentAuthContext();
|
||||
if (!context) {
|
||||
redirect("/login");
|
||||
}
|
||||
|
||||
if (!hasPermission(context.permissions, "audit:read")) {
|
||||
redirect("/app/dashboard");
|
||||
}
|
||||
|
||||
const params = (await searchParams) ?? {};
|
||||
const query = getSearchParam(params, "q");
|
||||
const page = getPage(params);
|
||||
const data = await readData();
|
||||
const normalizedQuery = query.trim().toLowerCase();
|
||||
const filteredLogs = data.auditLogs.filter((log) =>
|
||||
[log.actorEmail ?? "系统", log.action, log.targetType, log.targetId ?? "", log.result, log.reason]
|
||||
.join(" ")
|
||||
.toLowerCase()
|
||||
.includes(normalizedQuery),
|
||||
);
|
||||
const pageCount = getPageCount(filteredLogs.length);
|
||||
const visibleLogs = paginate(filteredLogs, page);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<section>
|
||||
<Badge variant="success">Audit</Badge>
|
||||
<h2 className="mt-3 text-xl font-semibold">审计日志</h2>
|
||||
<p className="mt-1 text-sm text-muted-foreground">关键操作、拒绝访问和故障处理留痕。</p>
|
||||
</section>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>审计列表</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="p-0">
|
||||
<TableToolbar
|
||||
page={Math.min(page, pageCount)}
|
||||
pageCount={pageCount}
|
||||
pathname="/app/settings/audit"
|
||||
query={query}
|
||||
searchPlaceholder="搜索操作者、动作、对象、结果"
|
||||
total={filteredLogs.length}
|
||||
/>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full min-w-[900px] text-sm">
|
||||
<thead className="bg-secondary text-left text-xs text-muted-foreground">
|
||||
<tr>
|
||||
<th className="px-4 py-3 font-medium">时间</th>
|
||||
<th className="px-4 py-3 font-medium">操作者</th>
|
||||
<th className="px-4 py-3 font-medium">动作</th>
|
||||
<th className="px-4 py-3 font-medium">对象</th>
|
||||
<th className="px-4 py-3 font-medium">结果</th>
|
||||
<th className="px-4 py-3 font-medium">原因</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y bg-card">
|
||||
{visibleLogs.map((log) => (
|
||||
<tr className="table-row-enter hover:bg-secondary/45" key={log.id}>
|
||||
<td className="px-4 py-3 text-muted-foreground">{new Date(log.timestamp).toLocaleString("zh-CN")}</td>
|
||||
<td className="px-4 py-3">{log.actorEmail ?? "系统"}</td>
|
||||
<td className="px-4 py-3">{log.action}</td>
|
||||
<td className="px-4 py-3 text-muted-foreground">
|
||||
{log.targetType}
|
||||
{log.targetId ? ` / ${log.targetId.slice(0, 8)}` : ""}
|
||||
</td>
|
||||
<td className="px-4 py-3">{log.result}</td>
|
||||
<td className="px-4 py-3 text-muted-foreground">{log.reason}</td>
|
||||
</tr>
|
||||
))}
|
||||
{visibleLogs.length === 0 ? (
|
||||
<tr>
|
||||
<td className="px-4 py-8 text-center text-muted-foreground" colSpan={6}>
|
||||
暂无匹配审计
|
||||
</td>
|
||||
</tr>
|
||||
) : null}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
37
app/(app)/app/settings/layout.tsx
Normal file
37
app/(app)/app/settings/layout.tsx
Normal file
@@ -0,0 +1,37 @@
|
||||
import Link from "next/link";
|
||||
import { Activity, Building2, ListChecks, Settings, Users } from "lucide-react";
|
||||
|
||||
const settingsNavItems = [
|
||||
{ href: "/app/settings/users", label: "用户管理", icon: Users },
|
||||
{ href: "/app/settings/organizations", label: "机构管理", icon: Building2 },
|
||||
{ href: "/app/settings/roles", label: "角色权限", icon: Settings },
|
||||
{ href: "/app/settings/audit", label: "审计日志", icon: ListChecks },
|
||||
{ href: "/app/settings/status", label: "运行状态", icon: Activity },
|
||||
];
|
||||
|
||||
type SettingsLayoutProps = {
|
||||
children: React.ReactNode;
|
||||
};
|
||||
|
||||
export default function SettingsLayout({ children }: SettingsLayoutProps): React.ReactElement {
|
||||
return (
|
||||
<div className="mx-auto flex w-full max-w-7xl flex-col gap-5">
|
||||
<section className="border-b pb-4">
|
||||
<h1 className="text-2xl font-semibold tracking-normal">系统设置</h1>
|
||||
<nav className="mt-4 flex gap-2 overflow-x-auto" aria-label="系统设置导航">
|
||||
{settingsNavItems.map((item) => (
|
||||
<Link
|
||||
className="inline-flex min-h-10 shrink-0 items-center gap-2 rounded-md border bg-card px-3 text-sm font-medium transition-colors hover:bg-secondary"
|
||||
href={item.href}
|
||||
key={item.href}
|
||||
>
|
||||
<item.icon className="size-4 text-muted-foreground" aria-hidden="true" />
|
||||
{item.label}
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
</section>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
102
app/(app)/app/settings/organizations/page.tsx
Normal file
102
app/(app)/app/settings/organizations/page.tsx
Normal file
@@ -0,0 +1,102 @@
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { getCurrentAuthContext } from "@/modules/core/server/auth";
|
||||
import { hasPermission } from "@/modules/core/server/permissions";
|
||||
import { readData } from "@/modules/core/server/store";
|
||||
import {
|
||||
OrganizationManagementClient,
|
||||
OrganizationRowActions,
|
||||
} from "@/modules/settings/components/OrganizationManagementClient";
|
||||
import { TableToolbar } from "@/modules/settings/components/TableToolbar";
|
||||
import { getPage, getPageCount, getSearchParam, paginate, type SearchParams } from "@/modules/settings/lib/pagination";
|
||||
|
||||
type OrganizationsPageProps = {
|
||||
searchParams?: Promise<SearchParams>;
|
||||
};
|
||||
|
||||
export default async function OrganizationsPage({ searchParams }: OrganizationsPageProps): Promise<React.ReactElement> {
|
||||
const context = await getCurrentAuthContext();
|
||||
if (!context) {
|
||||
redirect("/login");
|
||||
}
|
||||
|
||||
if (!hasPermission(context.permissions, "organization:read")) {
|
||||
redirect("/app/dashboard");
|
||||
}
|
||||
|
||||
const params = (await searchParams) ?? {};
|
||||
const query = getSearchParam(params, "q");
|
||||
const page = getPage(params);
|
||||
const data = await readData();
|
||||
const normalizedQuery = query.trim().toLowerCase();
|
||||
const filteredOrganizations = data.organizations.filter((organization) =>
|
||||
[organization.name, organization.slug, organization.status].join(" ").toLowerCase().includes(normalizedQuery),
|
||||
);
|
||||
const pageCount = getPageCount(filteredOrganizations.length);
|
||||
const visibleOrganizations = paginate(filteredOrganizations, page);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<section>
|
||||
<Badge variant="success">Organizations</Badge>
|
||||
<h2 className="mt-3 text-xl font-semibold">机构管理</h2>
|
||||
<p className="mt-1 text-sm text-muted-foreground">多机构租户、启停状态和机构角色初始化。</p>
|
||||
</section>
|
||||
|
||||
{hasPermission(context.permissions, "organization:manage") ? <OrganizationManagementClient /> : null}
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>机构列表</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="p-0">
|
||||
<TableToolbar
|
||||
page={Math.min(page, pageCount)}
|
||||
pageCount={pageCount}
|
||||
pathname="/app/settings/organizations"
|
||||
query={query}
|
||||
searchPlaceholder="搜索机构名称、标识、状态"
|
||||
total={filteredOrganizations.length}
|
||||
/>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full min-w-[820px] text-sm">
|
||||
<thead className="bg-secondary text-left text-xs text-muted-foreground">
|
||||
<tr>
|
||||
<th className="px-4 py-3 font-medium">机构</th>
|
||||
<th className="px-4 py-3 font-medium">Slug</th>
|
||||
<th className="px-4 py-3 font-medium">状态</th>
|
||||
<th className="px-4 py-3 text-right font-medium">创建时间</th>
|
||||
<th className="px-4 py-3 text-right font-medium">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y bg-card">
|
||||
{visibleOrganizations.map((organization) => (
|
||||
<tr className="table-row-enter hover:bg-secondary/45" key={organization.id}>
|
||||
<td className="px-4 py-3 font-medium">{organization.name}</td>
|
||||
<td className="px-4 py-3 text-muted-foreground">{organization.slug}</td>
|
||||
<td className="px-4 py-3">{organization.status === "active" ? "启用" : "停用"}</td>
|
||||
<td className="px-4 py-3 text-right text-muted-foreground">
|
||||
{new Date(organization.createdAt).toLocaleString("zh-CN")}
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<OrganizationRowActions organization={organization} />
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{visibleOrganizations.length === 0 ? (
|
||||
<tr>
|
||||
<td className="px-4 py-8 text-center text-muted-foreground" colSpan={5}>
|
||||
暂无匹配机构
|
||||
</td>
|
||||
</tr>
|
||||
) : null}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,31 +1,5 @@
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
import { getCurrentAuthContext, toPublicAccount } from "@/modules/core/server/auth";
|
||||
import { getRoleDefinitions, hasPermission } from "@/modules/core/server/permissions";
|
||||
import { readData } from "@/modules/core/server/store";
|
||||
import { SettingsOverview } from "@/modules/settings/components/SettingsOverview";
|
||||
|
||||
export default async function SettingsPage(): Promise<React.ReactElement> {
|
||||
const context = await getCurrentAuthContext();
|
||||
if (!context) {
|
||||
redirect("/login");
|
||||
}
|
||||
|
||||
if (!hasPermission(context.permissions, "account:read")) {
|
||||
redirect("/app/dashboard");
|
||||
}
|
||||
|
||||
const data = await readData();
|
||||
const roles = await getRoleDefinitions(context.organization?.id);
|
||||
return (
|
||||
<SettingsOverview
|
||||
accounts={data.accounts.map((account) => toPublicAccount(account))}
|
||||
roles={roles}
|
||||
auditLogs={data.auditLogs.slice(0, 100)}
|
||||
organizations={data.organizations}
|
||||
memberships={data.memberships}
|
||||
joinRequests={data.joinRequests}
|
||||
incidents={data.incidents}
|
||||
/>
|
||||
);
|
||||
redirect("/app/settings/users");
|
||||
}
|
||||
|
||||
101
app/(app)/app/settings/roles/page.tsx
Normal file
101
app/(app)/app/settings/roles/page.tsx
Normal file
@@ -0,0 +1,101 @@
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { getCurrentAuthContext } from "@/modules/core/server/auth";
|
||||
import { getRoleDefinitions, hasPermission, PERMISSION_DEFINITIONS } from "@/modules/core/server/permissions";
|
||||
import { RoleManagementClient, RoleRowActions } from "@/modules/settings/components/RoleManagementClient";
|
||||
import { TableToolbar } from "@/modules/settings/components/TableToolbar";
|
||||
import { getPage, getPageCount, getSearchParam, paginate, type SearchParams } from "@/modules/settings/lib/pagination";
|
||||
|
||||
type RolesPageProps = {
|
||||
searchParams?: Promise<SearchParams>;
|
||||
};
|
||||
|
||||
export default async function RolesPage({ searchParams }: RolesPageProps): Promise<React.ReactElement> {
|
||||
const context = await getCurrentAuthContext();
|
||||
if (!context) {
|
||||
redirect("/login");
|
||||
}
|
||||
|
||||
if (!hasPermission(context.permissions, "role:read")) {
|
||||
redirect("/app/dashboard");
|
||||
}
|
||||
|
||||
const params = (await searchParams) ?? {};
|
||||
const query = getSearchParam(params, "q");
|
||||
const page = getPage(params);
|
||||
const roles = await getRoleDefinitions(context.organization?.id);
|
||||
const normalizedQuery = query.trim().toLowerCase();
|
||||
const filteredRoles = roles.filter((role) =>
|
||||
[role.label, role.key, role.description, role.scope, ...role.permissions].join(" ").toLowerCase().includes(normalizedQuery),
|
||||
);
|
||||
const pageCount = getPageCount(filteredRoles.length);
|
||||
const visibleRoles = paginate(filteredRoles, page);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<section>
|
||||
<Badge variant="success">RBAC</Badge>
|
||||
<h2 className="mt-3 text-xl font-semibold">角色权限</h2>
|
||||
<p className="mt-1 text-sm text-muted-foreground">系统权限点、内置角色和机构自定义角色。</p>
|
||||
</section>
|
||||
|
||||
{hasPermission(context.permissions, "role:manage") ? <RoleManagementClient permissions={PERMISSION_DEFINITIONS} /> : null}
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>角色列表</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="p-0">
|
||||
<TableToolbar
|
||||
page={Math.min(page, pageCount)}
|
||||
pageCount={pageCount}
|
||||
pathname="/app/settings/roles"
|
||||
query={query}
|
||||
searchPlaceholder="搜索角色、权限、说明"
|
||||
total={filteredRoles.length}
|
||||
/>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full min-w-[980px] text-sm">
|
||||
<thead className="bg-secondary text-left text-xs text-muted-foreground">
|
||||
<tr>
|
||||
<th className="px-4 py-3 font-medium">角色</th>
|
||||
<th className="px-4 py-3 font-medium">范围</th>
|
||||
<th className="px-4 py-3 font-medium">类型</th>
|
||||
<th className="px-4 py-3 font-medium">状态</th>
|
||||
<th className="px-4 py-3 font-medium">权限</th>
|
||||
<th className="px-4 py-3 text-right font-medium">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y bg-card">
|
||||
{visibleRoles.map((role) => (
|
||||
<tr className="table-row-enter align-top hover:bg-secondary/45" key={role.id}>
|
||||
<td className="px-4 py-3">
|
||||
<p className="font-medium">{role.label}</p>
|
||||
<p className="text-xs text-muted-foreground">{role.description}</p>
|
||||
</td>
|
||||
<td className="px-4 py-3">{role.scope === "platform" ? "平台" : "机构"}</td>
|
||||
<td className="px-4 py-3">{role.isSystem ? "内置" : "自定义"}</td>
|
||||
<td className="px-4 py-3">{role.isEnabled ? "启用" : "停用"}</td>
|
||||
<td className="px-4 py-3 text-muted-foreground">{role.permissions.join(", ") || "-"}</td>
|
||||
<td className="px-4 py-3">
|
||||
<RoleRowActions permissions={PERMISSION_DEFINITIONS} role={role} />
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{visibleRoles.length === 0 ? (
|
||||
<tr>
|
||||
<td className="px-4 py-8 text-center text-muted-foreground" colSpan={6}>
|
||||
暂无匹配角色
|
||||
</td>
|
||||
</tr>
|
||||
) : null}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
138
app/(app)/app/settings/status/page.tsx
Normal file
138
app/(app)/app/settings/status/page.tsx
Normal file
@@ -0,0 +1,138 @@
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { checkDatabaseConnection } from "@/modules/core/server/db";
|
||||
import { getCurrentAuthContext } from "@/modules/core/server/auth";
|
||||
import { hasPermission } from "@/modules/core/server/permissions";
|
||||
import { readData } from "@/modules/core/server/store";
|
||||
import { IncidentStatusActions } from "@/modules/settings/components/IncidentStatusActions";
|
||||
import { TableToolbar } from "@/modules/settings/components/TableToolbar";
|
||||
import { getPage, getPageCount, getSearchParam, paginate, type SearchParams } from "@/modules/settings/lib/pagination";
|
||||
|
||||
type StatusPageProps = {
|
||||
searchParams?: Promise<SearchParams>;
|
||||
};
|
||||
|
||||
export default async function StatusPage({ searchParams }: StatusPageProps): Promise<React.ReactElement> {
|
||||
const context = await getCurrentAuthContext();
|
||||
if (!context) {
|
||||
redirect("/login");
|
||||
}
|
||||
|
||||
if (!hasPermission(context.permissions, "incident:read")) {
|
||||
redirect("/app/dashboard");
|
||||
}
|
||||
|
||||
const params = (await searchParams) ?? {};
|
||||
const query = getSearchParam(params, "q");
|
||||
const page = getPage(params);
|
||||
const [data, databaseHealth] = await Promise.all([readData(), checkDatabaseConnection()]);
|
||||
const canManageIncidents = hasPermission(context.permissions, "incident:manage");
|
||||
const normalizedQuery = query.trim().toLowerCase();
|
||||
const filteredIncidents = data.incidents.filter((incident) =>
|
||||
[incident.title, incident.description, incident.source, incident.severity, incident.status]
|
||||
.join(" ")
|
||||
.toLowerCase()
|
||||
.includes(normalizedQuery),
|
||||
);
|
||||
const pageCount = getPageCount(filteredIncidents.length);
|
||||
const visibleIncidents = paginate(filteredIncidents, page);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<section>
|
||||
<Badge variant={databaseHealth.ok ? "success" : "danger"}>{databaseHealth.ok ? "Healthy" : "Degraded"}</Badge>
|
||||
<h2 className="mt-3 text-xl font-semibold">运行状态</h2>
|
||||
<p className="mt-1 text-sm text-muted-foreground">{databaseHealth.reason}</p>
|
||||
</section>
|
||||
|
||||
<section className="grid gap-4 md:grid-cols-4">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-3xl">{data.organizations.length}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-0 text-sm text-muted-foreground">机构</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-3xl">{data.accounts.length}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-0 text-sm text-muted-foreground">账号</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-3xl">{data.beds.length}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-0 text-sm text-muted-foreground">床位</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-3xl">{data.incidents.length}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-0 text-sm text-muted-foreground">故障事件</CardContent>
|
||||
</Card>
|
||||
</section>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>故障中心</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="p-0">
|
||||
<TableToolbar
|
||||
page={Math.min(page, pageCount)}
|
||||
pageCount={pageCount}
|
||||
pathname="/app/settings/status"
|
||||
query={query}
|
||||
searchPlaceholder="搜索故障标题、来源、状态"
|
||||
total={filteredIncidents.length}
|
||||
/>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full min-w-[960px] text-sm">
|
||||
<thead className="bg-secondary text-left text-xs text-muted-foreground">
|
||||
<tr>
|
||||
<th className="px-4 py-3 font-medium">标题</th>
|
||||
<th className="px-4 py-3 font-medium">严重级别</th>
|
||||
<th className="px-4 py-3 font-medium">状态</th>
|
||||
<th className="px-4 py-3 font-medium">来源</th>
|
||||
<th className="px-4 py-3 text-right font-medium">创建时间</th>
|
||||
<th className="px-4 py-3 text-right font-medium">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y bg-card">
|
||||
{visibleIncidents.map((incident) => (
|
||||
<tr className="table-row-enter align-top hover:bg-secondary/45" key={incident.id}>
|
||||
<td className="px-4 py-3">
|
||||
<p className="font-medium">{incident.title}</p>
|
||||
<p className="text-xs text-muted-foreground">{incident.description}</p>
|
||||
</td>
|
||||
<td className="px-4 py-3">{incident.severity}</td>
|
||||
<td className="px-4 py-3">{incident.status}</td>
|
||||
<td className="px-4 py-3 text-muted-foreground">{incident.source}</td>
|
||||
<td className="px-4 py-3 text-right text-muted-foreground">
|
||||
{new Date(incident.createdAt).toLocaleString("zh-CN")}
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
{canManageIncidents ? (
|
||||
<IncidentStatusActions incident={incident} />
|
||||
) : (
|
||||
<span className="block text-right text-xs text-muted-foreground">只读</span>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{visibleIncidents.length === 0 ? (
|
||||
<tr>
|
||||
<td className="px-4 py-8 text-center text-muted-foreground" colSpan={6}>
|
||||
暂无匹配故障
|
||||
</td>
|
||||
</tr>
|
||||
) : null}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
140
app/(app)/app/settings/users/page.tsx
Normal file
140
app/(app)/app/settings/users/page.tsx
Normal file
@@ -0,0 +1,140 @@
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { getCurrentAuthContext, toPublicAccount } from "@/modules/core/server/auth";
|
||||
import { getRoleDefinitions, hasPermission } from "@/modules/core/server/permissions";
|
||||
import { readData } from "@/modules/core/server/store";
|
||||
import { ROLE_LABELS } from "@/modules/core/types";
|
||||
import type { RoleId } from "@/modules/core/types";
|
||||
import { TableToolbar } from "@/modules/settings/components/TableToolbar";
|
||||
import { UserAccountActions, UserManagementClient } from "@/modules/settings/components/UserManagementClient";
|
||||
import { getPage, getPageCount, getSearchParam, paginate, type SearchParams } from "@/modules/settings/lib/pagination";
|
||||
|
||||
type UsersPageProps = {
|
||||
searchParams?: Promise<SearchParams>;
|
||||
};
|
||||
|
||||
function formatRoleLabel(role: string): string {
|
||||
if (role in ROLE_LABELS) {
|
||||
return ROLE_LABELS[role as RoleId];
|
||||
}
|
||||
|
||||
return role;
|
||||
}
|
||||
|
||||
export default async function UsersPage({ searchParams }: UsersPageProps): Promise<React.ReactElement> {
|
||||
const context = await getCurrentAuthContext();
|
||||
if (!context) {
|
||||
redirect("/login");
|
||||
}
|
||||
|
||||
if (!hasPermission(context.permissions, "account:read")) {
|
||||
redirect("/app/dashboard");
|
||||
}
|
||||
|
||||
const params = (await searchParams) ?? {};
|
||||
const query = getSearchParam(params, "q");
|
||||
const page = getPage(params);
|
||||
const data = await readData();
|
||||
const roles = await getRoleDefinitions(context.organization?.id);
|
||||
const roleById = new Map(roles.map((role) => [role.id, role]));
|
||||
const organizationById = new Map(data.organizations.map((organization) => [organization.id, organization]));
|
||||
const accounts = data.accounts.map((account) => {
|
||||
const membership = context.organization?.id
|
||||
? data.memberships.find(
|
||||
(item) => item.accountId === account.id && item.organizationId === context.organization?.id && item.status === "active",
|
||||
)
|
||||
: data.memberships.find((item) => item.accountId === account.id && item.status === "active");
|
||||
const organization = membership ? organizationById.get(membership.organizationId) : undefined;
|
||||
const platformRole = account.platformRoleId ? roleById.get(account.platformRoleId) : undefined;
|
||||
|
||||
return toPublicAccount(account, platformRole?.key ?? membership?.roleKey, organization);
|
||||
});
|
||||
const normalizedQuery = query.trim().toLowerCase();
|
||||
const filteredAccounts = accounts.filter((account) =>
|
||||
[account.name, account.email, account.status, String(account.role), account.organization ?? ""]
|
||||
.join(" ")
|
||||
.toLowerCase()
|
||||
.includes(normalizedQuery),
|
||||
);
|
||||
const pageCount = getPageCount(filteredAccounts.length);
|
||||
const visibleAccounts = paginate(filteredAccounts, page);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<section>
|
||||
<Badge variant="success">Accounts</Badge>
|
||||
<h2 className="mt-3 text-xl font-semibold">用户管理</h2>
|
||||
<p className="mt-1 text-sm text-muted-foreground">账号创建、机构加入审批、角色分配和账号列表。</p>
|
||||
</section>
|
||||
|
||||
<UserManagementClient organizations={data.organizations} roles={roles} joinRequests={data.joinRequests} />
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>账号列表</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="p-0">
|
||||
<TableToolbar
|
||||
page={Math.min(page, pageCount)}
|
||||
pageCount={pageCount}
|
||||
pathname="/app/settings/users"
|
||||
query={query}
|
||||
searchPlaceholder="搜索姓名、邮箱、角色、状态"
|
||||
total={filteredAccounts.length}
|
||||
/>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full min-w-[920px] text-sm">
|
||||
<thead className="bg-secondary text-left text-xs text-muted-foreground">
|
||||
<tr>
|
||||
<th className="px-4 py-3 font-medium">账号</th>
|
||||
<th className="px-4 py-3 font-medium">角色</th>
|
||||
<th className="px-4 py-3 font-medium">机构</th>
|
||||
<th className="px-4 py-3 font-medium">状态</th>
|
||||
<th className="px-4 py-3 text-right font-medium">创建时间</th>
|
||||
<th className="px-4 py-3 text-right font-medium">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y bg-card">
|
||||
{visibleAccounts.map((account) => (
|
||||
<tr className="table-row-enter hover:bg-secondary/45" key={account.id}>
|
||||
<td className="px-4 py-3">
|
||||
<p className="font-medium">{account.name}</p>
|
||||
<p className="text-xs text-muted-foreground">{account.email}</p>
|
||||
</td>
|
||||
<td className="px-4 py-3">{formatRoleLabel(account.role)}</td>
|
||||
<td className="px-4 py-3 text-muted-foreground">{account.organization ?? "-"}</td>
|
||||
<td className="px-4 py-3">
|
||||
<Badge variant={account.status === "active" ? "success" : account.status === "pending" ? "warning" : "danger"}>
|
||||
{account.status === "active" ? "启用" : account.status === "pending" ? "待审批" : "停用"}
|
||||
</Badge>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-right text-muted-foreground">
|
||||
{new Date(account.createdAt).toLocaleString("zh-CN")}
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<UserAccountActions
|
||||
account={account}
|
||||
currentAccountId={context.account.id}
|
||||
organizations={data.organizations}
|
||||
roles={roles}
|
||||
/>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{visibleAccounts.length === 0 ? (
|
||||
<tr>
|
||||
<td className="px-4 py-8 text-center text-muted-foreground" colSpan={6}>
|
||||
暂无匹配账号
|
||||
</td>
|
||||
</tr>
|
||||
) : null}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
145
app/api/organizations/[id]/route.ts
Normal file
145
app/api/organizations/[id]/route.ts
Normal file
@@ -0,0 +1,145 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
|
||||
import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
|
||||
import { recordAuditLog } from "@/modules/core/server/audit";
|
||||
import { requirePermission } from "@/modules/core/server/auth";
|
||||
import { getDatabase } from "@/modules/core/server/db";
|
||||
import { organizations } from "@/modules/core/server/schema";
|
||||
import type { OrganizationStatus } from "@/modules/core/types";
|
||||
|
||||
type RouteContext = {
|
||||
params: Promise<{
|
||||
id: string;
|
||||
}>;
|
||||
};
|
||||
|
||||
const ORGANIZATION_STATUSES: OrganizationStatus[] = ["active", "disabled"];
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function readString(source: Record<string, unknown>, key: string): string {
|
||||
const value = source[key];
|
||||
return typeof value === "string" ? value.trim() : "";
|
||||
}
|
||||
|
||||
function readStatus(value: unknown): OrganizationStatus | null {
|
||||
if (typeof value !== "string") {
|
||||
return null;
|
||||
}
|
||||
|
||||
return ORGANIZATION_STATUSES.find((status) => status === value) ?? null;
|
||||
}
|
||||
|
||||
export async function PATCH(request: Request, context: RouteContext): Promise<Response> {
|
||||
const { id } = await context.params;
|
||||
const auth = await requirePermission("organization:manage", {
|
||||
action: "organization.update",
|
||||
targetType: "organization",
|
||||
targetId: id,
|
||||
});
|
||||
|
||||
if (!auth.success) {
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
const body = await readJsonBody(request);
|
||||
if (!isRecord(body)) {
|
||||
return jsonFailure("请求数据格式无效");
|
||||
}
|
||||
|
||||
const name = readString(body, "name");
|
||||
const slug = readString(body, "slug");
|
||||
const status = "status" in body ? readStatus(body.status) : null;
|
||||
if ("status" in body && !status) {
|
||||
return jsonFailure("机构状态无效");
|
||||
}
|
||||
|
||||
if (!name && !slug && !status) {
|
||||
return jsonFailure("请至少填写一个要更新的字段");
|
||||
}
|
||||
|
||||
const updateValues: {
|
||||
name?: string;
|
||||
slug?: string;
|
||||
status?: OrganizationStatus;
|
||||
updatedAt: Date;
|
||||
} = {
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
|
||||
if (name) {
|
||||
updateValues.name = name;
|
||||
}
|
||||
if (slug) {
|
||||
updateValues.slug = slug;
|
||||
}
|
||||
if (status) {
|
||||
updateValues.status = status;
|
||||
}
|
||||
|
||||
const database = getDatabase();
|
||||
try {
|
||||
const rows = await database.update(organizations).set(updateValues).where(eq(organizations.id, id)).returning();
|
||||
const organization = rows[0];
|
||||
if (!organization) {
|
||||
return jsonFailure("机构不存在", 404);
|
||||
}
|
||||
|
||||
await recordAuditLog({
|
||||
actor: auth.context.account,
|
||||
organizationId: organization.id,
|
||||
action: "organization.update",
|
||||
targetType: "organization",
|
||||
targetId: organization.id,
|
||||
result: "success",
|
||||
reason: `更新机构:${organization.name}`,
|
||||
});
|
||||
|
||||
return jsonSuccess("机构已更新", { organization });
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "";
|
||||
if (message.includes("organizations_slug_unique")) {
|
||||
return jsonFailure("机构标识已存在", 409);
|
||||
}
|
||||
|
||||
return jsonFailure("机构更新失败", 500);
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(_request: Request, context: RouteContext): Promise<Response> {
|
||||
const { id } = await context.params;
|
||||
const auth = await requirePermission("organization:manage", {
|
||||
action: "organization.disable",
|
||||
targetType: "organization",
|
||||
targetId: id,
|
||||
});
|
||||
|
||||
if (!auth.success) {
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
const database = getDatabase();
|
||||
const rows = await database
|
||||
.update(organizations)
|
||||
.set({ status: "disabled", updatedAt: new Date() })
|
||||
.where(eq(organizations.id, id))
|
||||
.returning();
|
||||
const organization = rows[0];
|
||||
if (!organization) {
|
||||
return jsonFailure("机构不存在", 404);
|
||||
}
|
||||
|
||||
await recordAuditLog({
|
||||
actor: auth.context.account,
|
||||
organizationId: organization.id,
|
||||
action: "organization.disable",
|
||||
targetType: "organization",
|
||||
targetId: organization.id,
|
||||
result: "success",
|
||||
reason: `停用机构:${organization.name}`,
|
||||
});
|
||||
|
||||
return jsonSuccess("机构已停用", { organization });
|
||||
}
|
||||
240
app/api/settings/accounts/[id]/route.ts
Normal file
240
app/api/settings/accounts/[id]/route.ts
Normal file
@@ -0,0 +1,240 @@
|
||||
import { and, eq } from "drizzle-orm";
|
||||
|
||||
import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
|
||||
import { recordAuditLog } from "@/modules/core/server/audit";
|
||||
import { requirePermission, toPublicAccount } from "@/modules/core/server/auth";
|
||||
import { getDatabase } from "@/modules/core/server/db";
|
||||
import { hasPermission } from "@/modules/core/server/permissions";
|
||||
import { accounts, memberships, organizations, roles, sessions } from "@/modules/core/server/schema";
|
||||
import type { AccountStatus, Organization } from "@/modules/core/types";
|
||||
|
||||
type RouteContext = {
|
||||
params: Promise<{
|
||||
id: string;
|
||||
}>;
|
||||
};
|
||||
|
||||
const ACCOUNT_STATUSES: AccountStatus[] = ["active", "disabled", "pending"];
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function readString(source: Record<string, unknown>, key: string): string {
|
||||
const value = source[key];
|
||||
return typeof value === "string" ? value.trim() : "";
|
||||
}
|
||||
|
||||
function readStatus(value: unknown): AccountStatus | null {
|
||||
if (typeof value !== "string") {
|
||||
return null;
|
||||
}
|
||||
|
||||
return ACCOUNT_STATUSES.find((status) => status === value) ?? null;
|
||||
}
|
||||
|
||||
function toOrganization(row: typeof organizations.$inferSelect): Organization {
|
||||
return {
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
slug: row.slug,
|
||||
status: row.status,
|
||||
createdAt: row.createdAt.toISOString(),
|
||||
updatedAt: row.updatedAt.toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
export async function PATCH(request: Request, context: RouteContext): Promise<Response> {
|
||||
const { id } = await context.params;
|
||||
const auth = await requirePermission("account:manage", {
|
||||
action: "account.update",
|
||||
targetType: "account",
|
||||
targetId: id,
|
||||
});
|
||||
|
||||
if (!auth.success) {
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
const body = await readJsonBody(request);
|
||||
if (!isRecord(body)) {
|
||||
return jsonFailure("请求数据格式无效");
|
||||
}
|
||||
|
||||
const name = readString(body, "name");
|
||||
const status = "status" in body ? readStatus(body.status) : null;
|
||||
const roleId = readString(body, "roleId");
|
||||
const requestedOrganizationId = readString(body, "organizationId");
|
||||
const organizationId = requestedOrganizationId || auth.context.organization?.id;
|
||||
|
||||
if ("status" in body && !status) {
|
||||
return jsonFailure("账号状态无效");
|
||||
}
|
||||
|
||||
if (!name && !status && !roleId) {
|
||||
return jsonFailure("请至少填写一个要更新的字段");
|
||||
}
|
||||
|
||||
if (id === auth.context.account.id && status === "disabled") {
|
||||
return jsonFailure("不能停用当前登录账号", 400);
|
||||
}
|
||||
|
||||
const canManagePlatform = hasPermission(auth.context.permissions, "platform:manage");
|
||||
if (!canManagePlatform && requestedOrganizationId && requestedOrganizationId !== auth.context.organization?.id) {
|
||||
return jsonFailure("权限不足", 403);
|
||||
}
|
||||
|
||||
const database = getDatabase();
|
||||
const targetAccountRows = await database.select().from(accounts).where(eq(accounts.id, id)).limit(1);
|
||||
const targetAccount = targetAccountRows[0];
|
||||
if (!targetAccount) {
|
||||
return jsonFailure("账号不存在", 404);
|
||||
}
|
||||
|
||||
if (roleId && !organizationId) {
|
||||
return jsonFailure("请选择机构后分配角色", 400);
|
||||
}
|
||||
|
||||
const organizationRows = organizationId
|
||||
? await database.select().from(organizations).where(eq(organizations.id, organizationId)).limit(1)
|
||||
: [];
|
||||
const organization = organizationRows[0];
|
||||
if (roleId && !organization) {
|
||||
return jsonFailure("机构不存在", 404);
|
||||
}
|
||||
|
||||
try {
|
||||
await database.transaction(async (transaction) => {
|
||||
if (name || status) {
|
||||
const updateValues: {
|
||||
name?: string;
|
||||
status?: AccountStatus;
|
||||
updatedAt: Date;
|
||||
} = {
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
if (name) {
|
||||
updateValues.name = name;
|
||||
}
|
||||
if (status) {
|
||||
updateValues.status = status;
|
||||
}
|
||||
|
||||
await transaction.update(accounts).set(updateValues).where(eq(accounts.id, id));
|
||||
if (status === "disabled") {
|
||||
await transaction.delete(sessions).where(eq(sessions.accountId, id));
|
||||
}
|
||||
}
|
||||
|
||||
if (roleId && organizationId) {
|
||||
const roleRows = await transaction
|
||||
.select()
|
||||
.from(roles)
|
||||
.where(and(eq(roles.id, roleId), eq(roles.organizationId, organizationId), eq(roles.isEnabled, true)))
|
||||
.limit(1);
|
||||
const role = roleRows[0];
|
||||
if (!role) {
|
||||
throw new Error("角色不存在");
|
||||
}
|
||||
|
||||
const membershipRows = await transaction
|
||||
.select()
|
||||
.from(memberships)
|
||||
.where(and(eq(memberships.accountId, id), eq(memberships.organizationId, organizationId)))
|
||||
.limit(1);
|
||||
const membership = membershipRows[0];
|
||||
|
||||
if (membership) {
|
||||
await transaction
|
||||
.update(memberships)
|
||||
.set({ roleId, status: "active", updatedAt: new Date() })
|
||||
.where(eq(memberships.id, membership.id));
|
||||
} else {
|
||||
await transaction.insert(memberships).values({
|
||||
accountId: id,
|
||||
organizationId,
|
||||
roleId,
|
||||
status: "active",
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.message : "账号更新失败";
|
||||
return jsonFailure(reason, reason === "角色不存在" ? 404 : 400);
|
||||
}
|
||||
|
||||
const updatedAccountRows = await database.select().from(accounts).where(eq(accounts.id, id)).limit(1);
|
||||
const updatedAccount = updatedAccountRows[0];
|
||||
if (!updatedAccount) {
|
||||
return jsonFailure("账号不存在", 404);
|
||||
}
|
||||
|
||||
const membershipRows = organizationId
|
||||
? await database
|
||||
.select({ membership: memberships, role: roles })
|
||||
.from(memberships)
|
||||
.innerJoin(roles, eq(roles.id, memberships.roleId))
|
||||
.where(and(eq(memberships.accountId, id), eq(memberships.organizationId, organizationId)))
|
||||
.limit(1)
|
||||
: [];
|
||||
const membership = membershipRows[0];
|
||||
const publicAccount = toPublicAccount(
|
||||
updatedAccount,
|
||||
membership?.role.key,
|
||||
organization ? toOrganization(organization) : undefined,
|
||||
);
|
||||
|
||||
await recordAuditLog({
|
||||
actor: auth.context.account,
|
||||
organizationId,
|
||||
action: "account.update",
|
||||
targetType: "account",
|
||||
targetId: updatedAccount.id,
|
||||
result: "success",
|
||||
reason: `更新账号:${updatedAccount.email}`,
|
||||
});
|
||||
|
||||
return jsonSuccess("账号已更新", { account: publicAccount });
|
||||
}
|
||||
|
||||
export async function DELETE(_request: Request, context: RouteContext): Promise<Response> {
|
||||
const { id } = await context.params;
|
||||
const auth = await requirePermission("account:manage", {
|
||||
action: "account.disable",
|
||||
targetType: "account",
|
||||
targetId: id,
|
||||
});
|
||||
|
||||
if (!auth.success) {
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
if (id === auth.context.account.id) {
|
||||
return jsonFailure("不能停用当前登录账号", 400);
|
||||
}
|
||||
|
||||
const database = getDatabase();
|
||||
const rows = await database
|
||||
.update(accounts)
|
||||
.set({ status: "disabled", updatedAt: new Date() })
|
||||
.where(eq(accounts.id, id))
|
||||
.returning();
|
||||
const account = rows[0];
|
||||
if (!account) {
|
||||
return jsonFailure("账号不存在", 404);
|
||||
}
|
||||
await database.delete(sessions).where(eq(sessions.accountId, id));
|
||||
|
||||
await recordAuditLog({
|
||||
actor: auth.context.account,
|
||||
organizationId: auth.context.organization?.id,
|
||||
action: "account.disable",
|
||||
targetType: "account",
|
||||
targetId: account.id,
|
||||
result: "success",
|
||||
reason: `停用账号:${account.email}`,
|
||||
});
|
||||
|
||||
return jsonSuccess("账号已停用", { account: toPublicAccount(account) });
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/ap
|
||||
import { hashPassword, normalizeEmail, requirePermission, toPublicAccount } from "@/modules/core/server/auth";
|
||||
import { recordAuditLog } from "@/modules/core/server/audit";
|
||||
import { getDatabase } from "@/modules/core/server/db";
|
||||
import { hasPermission } from "@/modules/core/server/permissions";
|
||||
import { getRoleDefinitions, hasPermission } from "@/modules/core/server/permissions";
|
||||
import { accounts, memberships, organizations, roles } from "@/modules/core/server/schema";
|
||||
import { readData } from "@/modules/core/server/store";
|
||||
|
||||
@@ -30,6 +30,9 @@ export async function GET(): Promise<Response> {
|
||||
const data = await readData();
|
||||
const canReadAllAccounts = hasPermission(auth.context.permissions, "platform:manage");
|
||||
const organizationId = auth.context.organization?.id;
|
||||
const roleDefinitions = await getRoleDefinitions(organizationId);
|
||||
const roleById = new Map(roleDefinitions.map((role) => [role.id, role]));
|
||||
const organizationById = new Map(data.organizations.map((organization) => [organization.id, organization]));
|
||||
const scopedAccountIds =
|
||||
organizationId && !canReadAllAccounts
|
||||
? new Set(
|
||||
@@ -42,7 +45,17 @@ export async function GET(): Promise<Response> {
|
||||
return jsonSuccess("账号列表已加载", {
|
||||
accounts: data.accounts
|
||||
.filter((account) => !scopedAccountIds || scopedAccountIds.has(account.id))
|
||||
.map((account) => toPublicAccount(account)),
|
||||
.map((account) => {
|
||||
const membership = organizationId
|
||||
? data.memberships.find(
|
||||
(item) => item.accountId === account.id && item.organizationId === organizationId && item.status === "active",
|
||||
)
|
||||
: data.memberships.find((item) => item.accountId === account.id && item.status === "active");
|
||||
const organization = membership ? organizationById.get(membership.organizationId) : undefined;
|
||||
const platformRole = account.platformRoleId ? roleById.get(account.platformRoleId) : undefined;
|
||||
|
||||
return toPublicAccount(account, platformRole?.key ?? membership?.roleKey, organization);
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
218
app/api/settings/roles/[id]/route.ts
Normal file
218
app/api/settings/roles/[id]/route.ts
Normal file
@@ -0,0 +1,218 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
|
||||
import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
|
||||
import { recordAuditLog } from "@/modules/core/server/audit";
|
||||
import { requirePermission } from "@/modules/core/server/auth";
|
||||
import { getDatabase } from "@/modules/core/server/db";
|
||||
import { getRoleDefinitions, hasPermission } from "@/modules/core/server/permissions";
|
||||
import { rolePermissions, roles } from "@/modules/core/server/schema";
|
||||
import { PERMISSIONS } from "@/modules/core/types";
|
||||
import type { Permission } from "@/modules/core/types";
|
||||
|
||||
type RouteContext = {
|
||||
params: Promise<{
|
||||
id: string;
|
||||
}>;
|
||||
};
|
||||
|
||||
const PERMISSION_SET = new Set<string>(PERMISSIONS);
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function readString(source: Record<string, unknown>, key: string): string {
|
||||
const value = source[key];
|
||||
return typeof value === "string" ? value.trim() : "";
|
||||
}
|
||||
|
||||
function readBoolean(source: Record<string, unknown>, key: string): boolean | null {
|
||||
const value = source[key];
|
||||
return typeof value === "boolean" ? value : null;
|
||||
}
|
||||
|
||||
function readPermissionArray(source: Record<string, unknown>): Permission[] | null {
|
||||
const value = source.permissions;
|
||||
if (!Array.isArray(value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const permissions = value.filter((item): item is string => typeof item === "string");
|
||||
if (permissions.length !== value.length || permissions.some((permission) => !PERMISSION_SET.has(permission))) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return permissions as Permission[];
|
||||
}
|
||||
|
||||
function createRoleKey(label: string): string {
|
||||
return label.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_|_$/g, "");
|
||||
}
|
||||
|
||||
async function getEditableRole(id: string, organizationId: string | undefined, canManagePlatform: boolean) {
|
||||
const database = getDatabase();
|
||||
const rows = await database.select().from(roles).where(eq(roles.id, id)).limit(1);
|
||||
const role = rows[0];
|
||||
if (!role) {
|
||||
return { success: false as const, response: jsonFailure("角色不存在", 404) };
|
||||
}
|
||||
|
||||
if (role.isSystem) {
|
||||
return { success: false as const, response: jsonFailure("内置角色不可编辑", 400) };
|
||||
}
|
||||
|
||||
if (!canManagePlatform && role.organizationId !== organizationId) {
|
||||
return { success: false as const, response: jsonFailure("角色不存在", 404) };
|
||||
}
|
||||
|
||||
return { success: true as const, role };
|
||||
}
|
||||
|
||||
export async function PATCH(request: Request, context: RouteContext): Promise<Response> {
|
||||
const { id } = await context.params;
|
||||
const auth = await requirePermission("role:manage", {
|
||||
action: "role.update",
|
||||
targetType: "role",
|
||||
targetId: id,
|
||||
});
|
||||
|
||||
if (!auth.success) {
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
const body = await readJsonBody(request);
|
||||
if (!isRecord(body)) {
|
||||
return jsonFailure("请求数据格式无效");
|
||||
}
|
||||
|
||||
const organizationId = auth.context.organization?.id;
|
||||
const editable = await getEditableRole(id, organizationId, hasPermission(auth.context.permissions, "platform:manage"));
|
||||
if (!editable.success) {
|
||||
return editable.response;
|
||||
}
|
||||
|
||||
const label = readString(body, "label");
|
||||
const key = readString(body, "key") || (label ? createRoleKey(label) : "");
|
||||
const description = readString(body, "description");
|
||||
const isEnabled = "isEnabled" in body ? readBoolean(body, "isEnabled") : null;
|
||||
if ("isEnabled" in body && isEnabled === null) {
|
||||
return jsonFailure("角色状态无效");
|
||||
}
|
||||
|
||||
const permissions = "permissions" in body ? readPermissionArray(body) : null;
|
||||
if ("permissions" in body && permissions === null) {
|
||||
return jsonFailure("权限列表无效");
|
||||
}
|
||||
|
||||
if (!label && !key && !description && isEnabled === null && permissions === null) {
|
||||
return jsonFailure("请至少填写一个要更新的字段");
|
||||
}
|
||||
|
||||
const updateValues: {
|
||||
label?: string;
|
||||
key?: string;
|
||||
description?: string;
|
||||
isEnabled?: boolean;
|
||||
updatedAt: Date;
|
||||
} = {
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
|
||||
if (label) {
|
||||
updateValues.label = label;
|
||||
}
|
||||
if (key) {
|
||||
updateValues.key = key;
|
||||
}
|
||||
if (description) {
|
||||
updateValues.description = description;
|
||||
}
|
||||
if (isEnabled !== null) {
|
||||
updateValues.isEnabled = isEnabled;
|
||||
}
|
||||
|
||||
const database = getDatabase();
|
||||
try {
|
||||
await database.transaction(async (transaction) => {
|
||||
await transaction.update(roles).set(updateValues).where(eq(roles.id, id));
|
||||
if (permissions) {
|
||||
await transaction.delete(rolePermissions).where(eq(rolePermissions.roleId, id));
|
||||
if (permissions.length > 0) {
|
||||
await transaction.insert(rolePermissions).values(
|
||||
permissions.map((permissionId) => ({
|
||||
roleId: id,
|
||||
permissionId,
|
||||
})),
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "";
|
||||
if (message.includes("roles_key_organization_unique")) {
|
||||
return jsonFailure("角色标识已存在", 409);
|
||||
}
|
||||
|
||||
return jsonFailure("角色更新失败", 500);
|
||||
}
|
||||
|
||||
await recordAuditLog({
|
||||
actor: auth.context.account,
|
||||
organizationId: editable.role.organizationId ?? organizationId,
|
||||
action: "role.update",
|
||||
targetType: "role",
|
||||
targetId: id,
|
||||
result: "success",
|
||||
reason: `更新角色:${label || editable.role.label}`,
|
||||
});
|
||||
|
||||
const roleRows = await getRoleDefinitions(editable.role.organizationId ?? organizationId);
|
||||
const role = roleRows.find((item) => item.id === id);
|
||||
if (!role) {
|
||||
return jsonFailure("角色更新后读取失败", 500);
|
||||
}
|
||||
|
||||
return jsonSuccess("角色已更新", { role });
|
||||
}
|
||||
|
||||
export async function DELETE(_request: Request, context: RouteContext): Promise<Response> {
|
||||
const { id } = await context.params;
|
||||
const auth = await requirePermission("role:manage", {
|
||||
action: "role.disable",
|
||||
targetType: "role",
|
||||
targetId: id,
|
||||
});
|
||||
|
||||
if (!auth.success) {
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
const organizationId = auth.context.organization?.id;
|
||||
const editable = await getEditableRole(id, organizationId, hasPermission(auth.context.permissions, "platform:manage"));
|
||||
if (!editable.success) {
|
||||
return editable.response;
|
||||
}
|
||||
|
||||
const database = getDatabase();
|
||||
const rows = await database
|
||||
.update(roles)
|
||||
.set({ isEnabled: false, updatedAt: new Date() })
|
||||
.where(eq(roles.id, id))
|
||||
.returning();
|
||||
const role = rows[0];
|
||||
if (!role) {
|
||||
return jsonFailure("角色不存在", 404);
|
||||
}
|
||||
|
||||
await recordAuditLog({
|
||||
actor: auth.context.account,
|
||||
organizationId: role.organizationId ?? organizationId,
|
||||
action: "role.disable",
|
||||
targetType: "role",
|
||||
targetId: role.id,
|
||||
result: "success",
|
||||
reason: `停用角色:${role.label}`,
|
||||
});
|
||||
|
||||
return jsonSuccess("角色已停用", { role });
|
||||
}
|
||||
@@ -79,3 +79,47 @@ a,
|
||||
::selection {
|
||||
background: color-mix(in oklch, var(--primary) 22%, transparent);
|
||||
}
|
||||
|
||||
@keyframes page-enter {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(6px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes loading-progress {
|
||||
0% {
|
||||
transform: translateX(-100%);
|
||||
}
|
||||
55% {
|
||||
transform: translateX(-18%);
|
||||
}
|
||||
100% {
|
||||
transform: translateX(100%);
|
||||
}
|
||||
}
|
||||
|
||||
.page-enter {
|
||||
animation: page-enter 180ms ease-out both;
|
||||
}
|
||||
|
||||
.table-row-enter {
|
||||
animation: page-enter 160ms ease-out both;
|
||||
}
|
||||
|
||||
.loading-progress {
|
||||
width: 55%;
|
||||
animation: loading-progress 900ms ease-in-out infinite;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.page-enter,
|
||||
.table-row-enter,
|
||||
.loading-progress {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -341,7 +341,7 @@ export async function loginWithPassword(input: {
|
||||
.from(memberships)
|
||||
.innerJoin(organizations, eq(organizations.id, memberships.organizationId))
|
||||
.innerJoin(roles, eq(roles.id, memberships.roleId))
|
||||
.where(and(eq(memberships.accountId, account.id), eq(memberships.status, "active")))
|
||||
.where(and(eq(memberships.accountId, account.id), eq(memberships.status, "active"), eq(roles.isEnabled, true)))
|
||||
.limit(1);
|
||||
const membership = membershipRows[0];
|
||||
const expiresAt = new Date(Date.now() + SESSION_MAX_AGE_SECONDS * 1000);
|
||||
@@ -401,7 +401,7 @@ export async function getCurrentAuthContext(): Promise<AuthContext | null> {
|
||||
|
||||
const session = toSession(row.session);
|
||||
const platformRoleRows = row.account.platformRoleId
|
||||
? await database.select().from(roles).where(eq(roles.id, row.account.platformRoleId)).limit(1)
|
||||
? await database.select().from(roles).where(and(eq(roles.id, row.account.platformRoleId), eq(roles.isEnabled, true))).limit(1)
|
||||
: [];
|
||||
const platformRole = platformRoleRows[0];
|
||||
const organizationRows = row.session.activeOrganizationId
|
||||
@@ -418,6 +418,7 @@ export async function getCurrentAuthContext(): Promise<AuthContext | null> {
|
||||
eq(memberships.accountId, row.account.id),
|
||||
eq(memberships.organizationId, organizationRow.id),
|
||||
eq(memberships.status, "active"),
|
||||
eq(roles.isEnabled, true),
|
||||
),
|
||||
)
|
||||
.limit(1)
|
||||
|
||||
@@ -249,7 +249,11 @@ export async function getRoleDefinitions(organizationId?: string): Promise<RoleD
|
||||
|
||||
export async function getPermissionsForRole(roleId: string): Promise<Permission[]> {
|
||||
const database = getDatabase();
|
||||
const rows = await database.select().from(rolePermissions).where(eq(rolePermissions.roleId, roleId));
|
||||
const rows = await database
|
||||
.select({ permissionId: rolePermissions.permissionId })
|
||||
.from(rolePermissions)
|
||||
.innerJoin(roles, eq(roles.id, rolePermissions.roleId))
|
||||
.where(and(eq(rolePermissions.roleId, roleId), eq(roles.isEnabled, true)));
|
||||
return rows.map((row) => row.permissionId as Permission);
|
||||
}
|
||||
|
||||
|
||||
84
modules/settings/components/IncidentStatusActions.tsx
Normal file
84
modules/settings/components/IncidentStatusActions.tsx
Normal file
@@ -0,0 +1,84 @@
|
||||
"use client";
|
||||
|
||||
import { CheckCheck, CircleCheck, CircleDot } from "lucide-react";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import type { ApiResult } from "@/modules/core/server/api";
|
||||
import type { IncidentStatus, SystemIncident } from "@/modules/core/types";
|
||||
|
||||
type IncidentStatusActionsProps = {
|
||||
incident: SystemIncident;
|
||||
};
|
||||
|
||||
type StatusAction = {
|
||||
label: string;
|
||||
status: IncidentStatus;
|
||||
icon: LucideIcon;
|
||||
};
|
||||
|
||||
const STATUS_ACTIONS: Record<IncidentStatus, StatusAction[]> = {
|
||||
open: [
|
||||
{ label: "确认", status: "acknowledged", icon: CircleDot },
|
||||
{ label: "解决", status: "resolved", icon: CircleCheck },
|
||||
],
|
||||
acknowledged: [
|
||||
{ label: "解决", status: "resolved", icon: CircleCheck },
|
||||
{ label: "关闭", status: "closed", icon: CheckCheck },
|
||||
],
|
||||
resolved: [{ label: "关闭", status: "closed", icon: CheckCheck }],
|
||||
closed: [],
|
||||
};
|
||||
|
||||
export function IncidentStatusActions({ incident }: IncidentStatusActionsProps): React.ReactElement {
|
||||
const router = useRouter();
|
||||
const [message, setMessage] = useState("");
|
||||
const [isPending, setIsPending] = useState(false);
|
||||
const actions = STATUS_ACTIONS[incident.status];
|
||||
|
||||
async function updateStatus(status: IncidentStatus): Promise<void> {
|
||||
setMessage("");
|
||||
setIsPending(true);
|
||||
const response = await fetch(`/api/system/incidents/${incident.id}`, {
|
||||
method: "PATCH",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ status }),
|
||||
});
|
||||
const result = (await response.json()) as ApiResult<{ incident: SystemIncident }>;
|
||||
setIsPending(false);
|
||||
|
||||
if (!result.success) {
|
||||
setMessage(result.reason);
|
||||
return;
|
||||
}
|
||||
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
if (actions.length === 0) {
|
||||
return <span className="block text-right text-xs text-muted-foreground">已关闭</span>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="grid justify-end gap-2">
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
{actions.map((action) => (
|
||||
<Button
|
||||
disabled={isPending}
|
||||
key={action.status}
|
||||
onClick={() => void updateStatus(action.status)}
|
||||
size="sm"
|
||||
type="button"
|
||||
variant="outline"
|
||||
>
|
||||
<action.icon className="size-4" aria-hidden="true" />
|
||||
{action.label}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
{message ? <p className="text-right text-xs text-destructive">{message}</p> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
194
modules/settings/components/OrganizationManagementClient.tsx
Normal file
194
modules/settings/components/OrganizationManagementClient.tsx
Normal file
@@ -0,0 +1,194 @@
|
||||
"use client";
|
||||
|
||||
import { FormEvent, useState } from "react";
|
||||
import { Pencil, Plus, Power } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Dialog } from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import type { ApiResult } from "@/modules/core/server/api";
|
||||
import type { Organization } from "@/modules/core/types";
|
||||
|
||||
export function OrganizationManagementClient(): React.ReactElement {
|
||||
const router = useRouter();
|
||||
const [message, setMessage] = useState("");
|
||||
const [isPending, setIsPending] = useState(false);
|
||||
|
||||
async function handleSubmit(event: FormEvent<HTMLFormElement>): Promise<void> {
|
||||
event.preventDefault();
|
||||
setMessage("");
|
||||
setIsPending(true);
|
||||
const formData = new FormData(event.currentTarget);
|
||||
const response = await fetch("/api/organizations", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
name: String(formData.get("name") ?? ""),
|
||||
slug: String(formData.get("slug") ?? ""),
|
||||
}),
|
||||
});
|
||||
const result = (await response.json()) as ApiResult<{ organization: Organization }>;
|
||||
setIsPending(false);
|
||||
|
||||
if (!result.success) {
|
||||
setMessage(result.reason);
|
||||
return;
|
||||
}
|
||||
|
||||
setMessage(result.reason);
|
||||
event.currentTarget.reset();
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>新增机构</CardTitle>
|
||||
<CardDescription>创建后会自动初始化机构内置角色。</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form className="grid gap-3 md:grid-cols-[1fr_1fr_auto]" onSubmit={handleSubmit}>
|
||||
<Input name="name" placeholder="机构名称" required />
|
||||
<Input name="slug" placeholder="机构标识,可留空" />
|
||||
<Button disabled={isPending} type="submit">
|
||||
<Plus className="size-4" aria-hidden="true" />
|
||||
新增机构
|
||||
</Button>
|
||||
</form>
|
||||
{message ? (
|
||||
<p className="mt-3 rounded-md bg-secondary px-3 py-2 text-sm text-secondary-foreground" role="status">
|
||||
{message}
|
||||
</p>
|
||||
) : null}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
type OrganizationRowActionsProps = {
|
||||
organization: Organization;
|
||||
};
|
||||
|
||||
export function OrganizationRowActions({ organization }: OrganizationRowActionsProps): React.ReactElement {
|
||||
const router = useRouter();
|
||||
const [isEditOpen, setIsEditOpen] = useState(false);
|
||||
const [message, setMessage] = useState("");
|
||||
const [isPending, setIsPending] = useState(false);
|
||||
|
||||
async function updateOrganization(payload: Record<string, string>): Promise<void> {
|
||||
setMessage("");
|
||||
setIsPending(true);
|
||||
const response = await fetch(`/api/organizations/${organization.id}`, {
|
||||
method: "PATCH",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
const result = (await response.json()) as ApiResult<{ organization: Organization }>;
|
||||
setIsPending(false);
|
||||
|
||||
if (!result.success) {
|
||||
setMessage(result.reason);
|
||||
return;
|
||||
}
|
||||
|
||||
setMessage(result.reason);
|
||||
setIsEditOpen(false);
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
async function disableOrganization(): Promise<void> {
|
||||
setMessage("");
|
||||
setIsPending(true);
|
||||
const response = await fetch(`/api/organizations/${organization.id}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
const result = (await response.json()) as ApiResult<{ organization: Organization }>;
|
||||
setIsPending(false);
|
||||
|
||||
if (!result.success) {
|
||||
setMessage(result.reason);
|
||||
return;
|
||||
}
|
||||
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
async function handleSubmit(event: FormEvent<HTMLFormElement>): Promise<void> {
|
||||
event.preventDefault();
|
||||
const formData = new FormData(event.currentTarget);
|
||||
await updateOrganization({
|
||||
name: String(formData.get("name") ?? ""),
|
||||
slug: String(formData.get("slug") ?? ""),
|
||||
status: String(formData.get("status") ?? ""),
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
<Button onClick={() => setIsEditOpen(true)} size="sm" type="button" variant="outline">
|
||||
<Pencil className="size-4" aria-hidden="true" />
|
||||
编辑
|
||||
</Button>
|
||||
{organization.status === "disabled" ? (
|
||||
<Button
|
||||
disabled={isPending}
|
||||
onClick={() => void updateOrganization({ status: "active" })}
|
||||
size="sm"
|
||||
type="button"
|
||||
variant="outline"
|
||||
>
|
||||
<Power className="size-4" aria-hidden="true" />
|
||||
启用
|
||||
</Button>
|
||||
) : (
|
||||
<Button disabled={isPending} onClick={() => void disableOrganization()} size="sm" type="button" variant="destructive">
|
||||
<Power className="size-4" aria-hidden="true" />
|
||||
停用
|
||||
</Button>
|
||||
)}
|
||||
<Dialog
|
||||
description="编辑机构名称、唯一标识和启停状态。"
|
||||
onClose={() => setIsEditOpen(false)}
|
||||
open={isEditOpen}
|
||||
title="编辑机构"
|
||||
>
|
||||
<form className="grid gap-4" onSubmit={handleSubmit}>
|
||||
<label className="grid gap-2 text-sm">
|
||||
<span className="font-medium">机构名称</span>
|
||||
<Input defaultValue={organization.name} name="name" required />
|
||||
</label>
|
||||
<label className="grid gap-2 text-sm">
|
||||
<span className="font-medium">机构标识</span>
|
||||
<Input defaultValue={organization.slug} name="slug" required />
|
||||
</label>
|
||||
<label className="grid gap-2 text-sm">
|
||||
<span className="font-medium">状态</span>
|
||||
<select
|
||||
className="h-11 w-full rounded-md border bg-background px-3 text-sm outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring"
|
||||
defaultValue={organization.status}
|
||||
name="status"
|
||||
>
|
||||
<option value="active">启用</option>
|
||||
<option value="disabled">停用</option>
|
||||
</select>
|
||||
</label>
|
||||
{message ? (
|
||||
<p className="rounded-md bg-secondary px-3 py-2 text-sm text-secondary-foreground" role="status">
|
||||
{message}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button onClick={() => setIsEditOpen(false)} type="button" variant="outline">
|
||||
取消
|
||||
</Button>
|
||||
<Button disabled={isPending} type="submit">
|
||||
保存
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
251
modules/settings/components/RoleManagementClient.tsx
Normal file
251
modules/settings/components/RoleManagementClient.tsx
Normal file
@@ -0,0 +1,251 @@
|
||||
"use client";
|
||||
|
||||
import { FormEvent, useState } from "react";
|
||||
import { Pencil, Plus, Power } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Dialog } from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import type { ApiResult } from "@/modules/core/server/api";
|
||||
import type { Permission, RoleDefinition } from "@/modules/core/types";
|
||||
|
||||
type PermissionDefinition = {
|
||||
id: Permission;
|
||||
label: string;
|
||||
category: string;
|
||||
description: string;
|
||||
};
|
||||
|
||||
type RoleManagementClientProps = {
|
||||
permissions: PermissionDefinition[];
|
||||
};
|
||||
|
||||
export function RoleManagementClient({ permissions }: RoleManagementClientProps): React.ReactElement {
|
||||
const router = useRouter();
|
||||
const [message, setMessage] = useState("");
|
||||
const [isPending, setIsPending] = useState(false);
|
||||
|
||||
async function handleSubmit(event: FormEvent<HTMLFormElement>): Promise<void> {
|
||||
event.preventDefault();
|
||||
setMessage("");
|
||||
setIsPending(true);
|
||||
const formData = new FormData(event.currentTarget);
|
||||
const response = await fetch("/api/settings/roles", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
label: String(formData.get("label") ?? ""),
|
||||
key: String(formData.get("key") ?? ""),
|
||||
description: String(formData.get("description") ?? ""),
|
||||
permissions: formData.getAll("permissions").map(String),
|
||||
}),
|
||||
});
|
||||
const result = (await response.json()) as ApiResult<{ role: RoleDefinition }>;
|
||||
setIsPending(false);
|
||||
|
||||
if (!result.success) {
|
||||
setMessage(result.reason);
|
||||
return;
|
||||
}
|
||||
|
||||
setMessage(result.reason);
|
||||
event.currentTarget.reset();
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>新增角色</CardTitle>
|
||||
<CardDescription>角色由系统注册权限点组合而成。</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form className="grid gap-4" onSubmit={handleSubmit}>
|
||||
<div className="grid gap-3 md:grid-cols-3">
|
||||
<Input name="label" placeholder="角色名称" required />
|
||||
<Input name="key" placeholder="角色标识,可留空" />
|
||||
<Input name="description" placeholder="角色说明" />
|
||||
</div>
|
||||
<div className="grid gap-2 sm:grid-cols-2 xl:grid-cols-3">
|
||||
{permissions.map((permission) => (
|
||||
<label className="flex items-start gap-2 rounded-md border p-3 text-sm" key={permission.id}>
|
||||
<input className="mt-1" name="permissions" type="checkbox" value={permission.id} />
|
||||
<span>
|
||||
<span className="block font-medium">{permission.label}</span>
|
||||
<span className="block text-xs text-muted-foreground">{permission.id}</span>
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<Button className="w-fit" disabled={isPending} type="submit">
|
||||
<Plus className="size-4" aria-hidden="true" />
|
||||
新增角色
|
||||
</Button>
|
||||
</form>
|
||||
{message ? (
|
||||
<p className="mt-3 rounded-md bg-secondary px-3 py-2 text-sm text-secondary-foreground" role="status">
|
||||
{message}
|
||||
</p>
|
||||
) : null}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
type RoleRowActionsProps = {
|
||||
permissions: PermissionDefinition[];
|
||||
role: RoleDefinition;
|
||||
};
|
||||
|
||||
export function RoleRowActions({ permissions, role }: RoleRowActionsProps): React.ReactElement {
|
||||
const router = useRouter();
|
||||
const [isEditOpen, setIsEditOpen] = useState(false);
|
||||
const [message, setMessage] = useState("");
|
||||
const [isPending, setIsPending] = useState(false);
|
||||
|
||||
async function updateRole(payload: Record<string, string | boolean | string[]>): Promise<void> {
|
||||
setMessage("");
|
||||
setIsPending(true);
|
||||
const response = await fetch(`/api/settings/roles/${role.id}`, {
|
||||
method: "PATCH",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
const result = (await response.json()) as ApiResult<{ role: RoleDefinition }>;
|
||||
setIsPending(false);
|
||||
|
||||
if (!result.success) {
|
||||
setMessage(result.reason);
|
||||
return;
|
||||
}
|
||||
|
||||
setMessage(result.reason);
|
||||
setIsEditOpen(false);
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
async function disableRole(): Promise<void> {
|
||||
setMessage("");
|
||||
setIsPending(true);
|
||||
const response = await fetch(`/api/settings/roles/${role.id}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
const result = (await response.json()) as ApiResult<{ role: RoleDefinition }>;
|
||||
setIsPending(false);
|
||||
|
||||
if (!result.success) {
|
||||
setMessage(result.reason);
|
||||
return;
|
||||
}
|
||||
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
async function handleSubmit(event: FormEvent<HTMLFormElement>): Promise<void> {
|
||||
event.preventDefault();
|
||||
const formData = new FormData(event.currentTarget);
|
||||
await updateRole({
|
||||
label: String(formData.get("label") ?? ""),
|
||||
key: String(formData.get("key") ?? ""),
|
||||
description: String(formData.get("description") ?? ""),
|
||||
isEnabled: String(formData.get("isEnabled") ?? "") === "true",
|
||||
permissions: formData.getAll("permissions").map(String),
|
||||
});
|
||||
}
|
||||
|
||||
if (role.isSystem) {
|
||||
return <span className="block text-right text-xs text-muted-foreground">内置只读</span>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
<Button onClick={() => setIsEditOpen(true)} size="sm" type="button" variant="outline">
|
||||
<Pencil className="size-4" aria-hidden="true" />
|
||||
编辑
|
||||
</Button>
|
||||
{role.isEnabled ? (
|
||||
<Button disabled={isPending} onClick={() => void disableRole()} size="sm" type="button" variant="destructive">
|
||||
<Power className="size-4" aria-hidden="true" />
|
||||
停用
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
disabled={isPending}
|
||||
onClick={() => void updateRole({ isEnabled: true })}
|
||||
size="sm"
|
||||
type="button"
|
||||
variant="outline"
|
||||
>
|
||||
<Power className="size-4" aria-hidden="true" />
|
||||
启用
|
||||
</Button>
|
||||
)}
|
||||
<Dialog
|
||||
description="编辑自定义角色的名称、说明、状态和权限点。"
|
||||
onClose={() => setIsEditOpen(false)}
|
||||
open={isEditOpen}
|
||||
title="编辑角色"
|
||||
>
|
||||
<form className="grid gap-4" onSubmit={handleSubmit}>
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
<label className="grid gap-2 text-sm">
|
||||
<span className="font-medium">角色名称</span>
|
||||
<Input defaultValue={role.label} name="label" required />
|
||||
</label>
|
||||
<label className="grid gap-2 text-sm">
|
||||
<span className="font-medium">角色标识</span>
|
||||
<Input defaultValue={role.key} name="key" required />
|
||||
</label>
|
||||
</div>
|
||||
<label className="grid gap-2 text-sm">
|
||||
<span className="font-medium">角色说明</span>
|
||||
<Input defaultValue={role.description} name="description" />
|
||||
</label>
|
||||
<label className="grid gap-2 text-sm">
|
||||
<span className="font-medium">状态</span>
|
||||
<select
|
||||
className="h-11 w-full rounded-md border bg-background px-3 text-sm outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring"
|
||||
defaultValue={String(role.isEnabled)}
|
||||
name="isEnabled"
|
||||
>
|
||||
<option value="true">启用</option>
|
||||
<option value="false">停用</option>
|
||||
</select>
|
||||
</label>
|
||||
<div className="grid gap-2 sm:grid-cols-2 xl:grid-cols-3">
|
||||
{permissions.map((permission) => (
|
||||
<label className="flex items-start gap-2 rounded-md border p-3 text-sm" key={permission.id}>
|
||||
<input
|
||||
className="mt-1"
|
||||
defaultChecked={role.permissions.includes(permission.id)}
|
||||
name="permissions"
|
||||
type="checkbox"
|
||||
value={permission.id}
|
||||
/>
|
||||
<span>
|
||||
<span className="block font-medium">{permission.label}</span>
|
||||
<span className="block text-xs text-muted-foreground">{permission.id}</span>
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
{message ? (
|
||||
<p className="rounded-md bg-secondary px-3 py-2 text-sm text-secondary-foreground" role="status">
|
||||
{message}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button onClick={() => setIsEditOpen(false)} type="button" variant="outline">
|
||||
取消
|
||||
</Button>
|
||||
<Button disabled={isPending} type="submit">
|
||||
保存
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
62
modules/settings/components/TableToolbar.tsx
Normal file
62
modules/settings/components/TableToolbar.tsx
Normal file
@@ -0,0 +1,62 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { buildPageHref } from "@/modules/settings/lib/pagination";
|
||||
|
||||
type TableToolbarProps = {
|
||||
actionLabel?: string;
|
||||
page: number;
|
||||
pageCount: number;
|
||||
pathname: string;
|
||||
query: string;
|
||||
searchPlaceholder: string;
|
||||
total: number;
|
||||
};
|
||||
|
||||
export function TableToolbar({
|
||||
actionLabel,
|
||||
page,
|
||||
pageCount,
|
||||
pathname,
|
||||
query,
|
||||
searchPlaceholder,
|
||||
total,
|
||||
}: TableToolbarProps): React.ReactElement {
|
||||
return (
|
||||
<div className="flex flex-col gap-3 border-b p-4 lg:flex-row lg:items-center lg:justify-between">
|
||||
<form className="flex w-full max-w-xl gap-2" action={pathname}>
|
||||
<Input name="q" placeholder={searchPlaceholder} defaultValue={query} />
|
||||
<Button type="submit" variant="outline">
|
||||
搜索
|
||||
</Button>
|
||||
</form>
|
||||
<div className="flex items-center justify-between gap-3 text-sm text-muted-foreground">
|
||||
<span>{actionLabel ?? `共 ${total} 条`}</span>
|
||||
<div className="flex items-center gap-2">
|
||||
{page <= 1 ? (
|
||||
<Button disabled size="sm" variant="outline">
|
||||
上一页
|
||||
</Button>
|
||||
) : (
|
||||
<Button asChild size="sm" variant="outline">
|
||||
<Link href={buildPageHref(pathname, query, page - 1)}>上一页</Link>
|
||||
</Button>
|
||||
)}
|
||||
<span className="min-w-16 text-center">
|
||||
{page}/{pageCount}
|
||||
</span>
|
||||
{page >= pageCount ? (
|
||||
<Button disabled size="sm" variant="outline">
|
||||
下一页
|
||||
</Button>
|
||||
) : (
|
||||
<Button asChild size="sm" variant="outline">
|
||||
<Link href={buildPageHref(pathname, query, page + 1)}>下一页</Link>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,15 +1,16 @@
|
||||
"use client";
|
||||
|
||||
import { FormEvent, useMemo, useState } from "react";
|
||||
import { Check, Plus, X } from "lucide-react";
|
||||
import { Check, Pencil, Plus, Power, X } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Dialog } from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import type { ApiResult } from "@/modules/core/server/api";
|
||||
import type { JoinRequest, Organization, RoleDefinition } from "@/modules/core/types";
|
||||
import type { JoinRequest, Organization, PublicAccount, RoleDefinition } from "@/modules/core/types";
|
||||
|
||||
type UserManagementClientProps = {
|
||||
organizations: Organization[];
|
||||
@@ -222,3 +223,184 @@ export function UserManagementClient({
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
type UserAccountActionsProps = {
|
||||
account: PublicAccount;
|
||||
currentAccountId: string;
|
||||
organizations: Organization[];
|
||||
roles: RoleDefinition[];
|
||||
};
|
||||
|
||||
export function UserAccountActions({
|
||||
account,
|
||||
currentAccountId,
|
||||
organizations,
|
||||
roles,
|
||||
}: UserAccountActionsProps): React.ReactElement {
|
||||
const router = useRouter();
|
||||
const [isEditOpen, setIsEditOpen] = useState(false);
|
||||
const [selectedOrganizationId, setSelectedOrganizationId] = useState(
|
||||
() => account.organizationId ?? getDefaultOrganizationId(organizations),
|
||||
);
|
||||
const [message, setMessage] = useState("");
|
||||
const [isPending, setIsPending] = useState(false);
|
||||
const organizationRoles = useMemo(
|
||||
() => getOrganizationRoles(roles, selectedOrganizationId),
|
||||
[roles, selectedOrganizationId],
|
||||
);
|
||||
const defaultRoleId =
|
||||
organizationRoles.find((role) => role.key === account.role || role.id === account.role)?.id ?? organizationRoles[0]?.id ?? "";
|
||||
const isCurrentAccount = account.id === currentAccountId;
|
||||
|
||||
async function updateAccount(payload: Record<string, string>): Promise<void> {
|
||||
setMessage("");
|
||||
setIsPending(true);
|
||||
const response = await fetch(`/api/settings/accounts/${account.id}`, {
|
||||
method: "PATCH",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
const result = (await response.json()) as ApiResult<{ account: PublicAccount }>;
|
||||
setIsPending(false);
|
||||
|
||||
if (!result.success) {
|
||||
setMessage(result.reason);
|
||||
return;
|
||||
}
|
||||
|
||||
setMessage(result.reason);
|
||||
setIsEditOpen(false);
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
async function disableAccount(): Promise<void> {
|
||||
setMessage("");
|
||||
setIsPending(true);
|
||||
const response = await fetch(`/api/settings/accounts/${account.id}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
const result = (await response.json()) as ApiResult<{ account: PublicAccount }>;
|
||||
setIsPending(false);
|
||||
|
||||
if (!result.success) {
|
||||
setMessage(result.reason);
|
||||
return;
|
||||
}
|
||||
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
async function handleSubmit(event: FormEvent<HTMLFormElement>): Promise<void> {
|
||||
event.preventDefault();
|
||||
const formData = new FormData(event.currentTarget);
|
||||
await updateAccount({
|
||||
name: String(formData.get("name") ?? ""),
|
||||
status: String(formData.get("status") ?? ""),
|
||||
organizationId: String(formData.get("organizationId") ?? ""),
|
||||
roleId: String(formData.get("roleId") ?? ""),
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
<Button onClick={() => setIsEditOpen(true)} size="sm" type="button" variant="outline">
|
||||
<Pencil className="size-4" aria-hidden="true" />
|
||||
编辑
|
||||
</Button>
|
||||
{account.status === "disabled" ? (
|
||||
<Button
|
||||
disabled={isPending}
|
||||
onClick={() => void updateAccount({ status: "active" })}
|
||||
size="sm"
|
||||
type="button"
|
||||
variant="outline"
|
||||
>
|
||||
<Power className="size-4" aria-hidden="true" />
|
||||
启用
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
disabled={isPending || isCurrentAccount}
|
||||
onClick={() => void disableAccount()}
|
||||
size="sm"
|
||||
type="button"
|
||||
variant="destructive"
|
||||
>
|
||||
<Power className="size-4" aria-hidden="true" />
|
||||
停用
|
||||
</Button>
|
||||
)}
|
||||
<Dialog
|
||||
description="调整账号基础信息、状态和机构角色。"
|
||||
onClose={() => setIsEditOpen(false)}
|
||||
open={isEditOpen}
|
||||
title="编辑用户"
|
||||
>
|
||||
<form className="grid gap-4" onSubmit={handleSubmit}>
|
||||
<label className="grid gap-2 text-sm">
|
||||
<span className="font-medium">姓名</span>
|
||||
<Input defaultValue={account.name} name="name" required />
|
||||
</label>
|
||||
<label className="grid gap-2 text-sm">
|
||||
<span className="font-medium">状态</span>
|
||||
<select
|
||||
className="h-11 w-full rounded-md border bg-background px-3 text-sm outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring"
|
||||
defaultValue={account.status}
|
||||
disabled={isCurrentAccount}
|
||||
name="status"
|
||||
>
|
||||
<option value="active">启用</option>
|
||||
<option value="disabled">停用</option>
|
||||
</select>
|
||||
</label>
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
<label className="grid gap-2 text-sm">
|
||||
<span className="font-medium">机构</span>
|
||||
<select
|
||||
className="h-11 w-full rounded-md border bg-background px-3 text-sm outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring"
|
||||
name="organizationId"
|
||||
onChange={(event) => setSelectedOrganizationId(event.target.value)}
|
||||
value={selectedOrganizationId}
|
||||
>
|
||||
{organizations.map((organization) => (
|
||||
<option key={organization.id} value={organization.id}>
|
||||
{organization.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="grid gap-2 text-sm">
|
||||
<span className="font-medium">角色</span>
|
||||
<select
|
||||
className="h-11 w-full rounded-md border bg-background px-3 text-sm outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring"
|
||||
defaultValue={defaultRoleId}
|
||||
disabled={organizationRoles.length === 0}
|
||||
key={selectedOrganizationId}
|
||||
name="roleId"
|
||||
>
|
||||
{organizationRoles.map((role) => (
|
||||
<option key={role.id} value={role.id}>
|
||||
{role.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
{message ? (
|
||||
<p className="rounded-md bg-secondary px-3 py-2 text-sm text-secondary-foreground" role="status">
|
||||
{message}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button onClick={() => setIsEditOpen(false)} type="button" variant="outline">
|
||||
取消
|
||||
</Button>
|
||||
<Button disabled={isPending} type="submit">
|
||||
保存
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
35
modules/settings/lib/pagination.ts
Normal file
35
modules/settings/lib/pagination.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
export const SETTINGS_PAGE_SIZE = 8;
|
||||
|
||||
export type SearchParams = Record<string, string | string[] | undefined>;
|
||||
|
||||
export function getSearchParam(params: SearchParams, key: string): string {
|
||||
const value = params[key];
|
||||
if (Array.isArray(value)) {
|
||||
return value[0] ?? "";
|
||||
}
|
||||
|
||||
return value ?? "";
|
||||
}
|
||||
|
||||
export function getPage(params: SearchParams): number {
|
||||
const page = Number(getSearchParam(params, "page"));
|
||||
return Number.isInteger(page) && page > 0 ? page : 1;
|
||||
}
|
||||
|
||||
export function getPageCount(total: number, pageSize = SETTINGS_PAGE_SIZE): number {
|
||||
return Math.max(1, Math.ceil(total / pageSize));
|
||||
}
|
||||
|
||||
export function paginate<T>(items: T[], page: number, pageSize = SETTINGS_PAGE_SIZE): T[] {
|
||||
const safePage = Math.min(page, getPageCount(items.length, pageSize));
|
||||
return items.slice((safePage - 1) * pageSize, safePage * pageSize);
|
||||
}
|
||||
|
||||
export function buildPageHref(pathname: string, query: string, page: number): string {
|
||||
const params = new URLSearchParams();
|
||||
if (query.trim()) {
|
||||
params.set("q", query.trim());
|
||||
}
|
||||
params.set("page", String(page));
|
||||
return `${pathname}?${params.toString()}`;
|
||||
}
|
||||
@@ -2,10 +2,12 @@ import Link from "next/link";
|
||||
import {
|
||||
Bell,
|
||||
BedDouble,
|
||||
Building2,
|
||||
ClipboardCheck,
|
||||
HeartPulse,
|
||||
Home,
|
||||
LayoutDashboard,
|
||||
ListChecks,
|
||||
Radio,
|
||||
Settings,
|
||||
ShieldAlert,
|
||||
@@ -78,10 +80,30 @@ const navItems: NavItem[] = [
|
||||
icon: TabletSmartphone,
|
||||
},
|
||||
{
|
||||
href: "/app/settings",
|
||||
label: "权限设置",
|
||||
href: "/app/settings/organizations",
|
||||
label: "机构管理",
|
||||
icon: Building2,
|
||||
},
|
||||
{
|
||||
href: "/app/settings/users",
|
||||
label: "用户管理",
|
||||
icon: Users,
|
||||
},
|
||||
{
|
||||
href: "/app/settings/roles",
|
||||
label: "角色权限",
|
||||
icon: Settings,
|
||||
},
|
||||
{
|
||||
href: "/app/settings/audit",
|
||||
label: "审计日志",
|
||||
icon: ListChecks,
|
||||
},
|
||||
{
|
||||
href: "/app/settings/status",
|
||||
label: "运行状态",
|
||||
icon: Wrench,
|
||||
},
|
||||
];
|
||||
|
||||
type AppShellProps = {
|
||||
@@ -150,7 +172,7 @@ export function AppShell({ children, account, permissions }: AppShellProps): Rea
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main className="min-h-0 flex-1 overflow-y-auto px-4 py-5 md:px-8">{children}</main>
|
||||
<main className="page-enter min-h-0 flex-1 overflow-y-auto px-4 py-5 md:px-8">{children}</main>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user