Files
persionalBrand/apps/admin/src/main.tsx
T

327 lines
11 KiB
TypeScript

import React, { Suspense, useState } from "react";
import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { useQuery } from "@tanstack/react-query";
import {
App,
Button,
Card,
Form,
Input,
Layout,
Menu,
Select,
Space,
Tag,
Typography,
message,
} from "antd";
import { createApiClient } from "./lib/api.js";
const FeatureInquiriesPage = React.lazy(() =>
import("./features/inquiries/InquiriesPage.js").then((module) => ({
default: module.InquiriesPage,
})),
);
const FeatureTrustContentPage = React.lazy(() =>
import("./features/trust-content/TrustContentPage.js").then((module) => ({
default: module.TrustContentPage,
})),
);
const FeatureServicesPage = React.lazy(() =>
import("./features/services/ServicesPage.js").then((module) => ({
default: module.ServicesPage,
})),
);
const FeatureBrandPage = React.lazy(() =>
import("./features/brand/BrandPage.js").then((module) => ({ default: module.BrandPage })),
);
const FeatureWorkspacePage = React.lazy(() =>
import("./features/workspace/WorkspacePage.js").then((module) => ({
default: module.WorkspacePage,
})),
);
const FeatureOverviewPage = React.lazy(() =>
import("./features/overview/OverviewPage.js").then((module) => ({
default: module.OverviewPage,
})),
);
const FeatureCapabilitiesPage = React.lazy(() =>
import("./features/capabilities/CapabilitiesPage.js").then((module) => ({
default: module.CapabilitiesPage,
})),
);
const FeatureMembersPage = React.lazy(() =>
import("./features/team/MembersPage.js").then((module) => ({
default: module.MembersPage,
})),
);
const FeaturePublicationPage = React.lazy(() =>
import("./features/publication/PublicationPage.js").then((module) => ({
default: module.PublicationPage,
})),
);
import { BrowserRouter, Navigate, Route, Routes, useLocation, useNavigate } from "react-router-dom";
import "antd/dist/reset.css";
const queryClient = new QueryClient();
const api = createApiClient;
function Login({
onLogin,
}: {
onLogin: (session: { role: string; mustChangePassword: boolean }) => void;
}) {
const [form] = Form.useForm();
const [loading, setLoading] = useState(false);
async function submit(values: { username: string; password: string }) {
setLoading(true);
try {
const result = await api().loginAdmin(values.username, values.password);
localStorage.setItem("adminToken", result.token);
localStorage.setItem("adminRole", result.role);
localStorage.setItem("adminMustChangePassword", String(result.mustChangePassword));
onLogin(result);
} catch (error) {
message.error(error instanceof Error ? error.message : "登录失败");
} finally {
setLoading(false);
}
}
return (
<Card title="个人品牌后台" style={{ maxWidth: 420, margin: "120px auto" }}>
<Form form={form} layout="vertical" onFinish={submit}>
<Form.Item name="username" label="账号" initialValue="admin" rules={[{ required: true }]}>
<Input />
</Form.Item>
<Form.Item name="password" label="密码" rules={[{ required: true }]}>
<Input.Password />
</Form.Item>
<Button type="primary" htmlType="submit" loading={loading} block>
登录
</Button>
</Form>
</Card>
);
}
function ChangePassword({ onComplete }: { onComplete: () => void }) {
const [form] = Form.useForm<{
currentPassword: string;
newPassword: string;
confirmPassword: string;
}>();
const [loading, setLoading] = useState(false);
async function submit(values: {
currentPassword: string;
newPassword: string;
confirmPassword: string;
}) {
if (values.newPassword !== values.confirmPassword) {
message.error("两次输入的新密码不一致");
return;
}
setLoading(true);
try {
await api().changeAdminPassword(values.currentPassword, values.newPassword);
localStorage.setItem("adminMustChangePassword", "false");
message.success("密码已更新");
onComplete();
} catch (error) {
message.error(error instanceof Error ? error.message : "密码更新失败");
} finally {
setLoading(false);
}
}
return (
<Card title="首次登录需要修改密码" style={{ maxWidth: 420, margin: "120px auto" }}>
<Typography.Paragraph type="secondary">请先设置只有你本人知道的新密码。</Typography.Paragraph>
<Form form={form} layout="vertical" onFinish={submit}>
<Form.Item name="currentPassword" label="初始密码" rules={[{ required: true }]}>
<Input.Password />
</Form.Item>
<Form.Item
name="newPassword"
label="新密码"
rules={[{ required: true, min: 8, message: "请输入至少 8 位新密码" }]}
>
<Input.Password />
</Form.Item>
<Form.Item name="confirmPassword" label="确认新密码" rules={[{ required: true }]}>
<Input.Password />
</Form.Item>
<Button type="primary" htmlType="submit" loading={loading} block>
保存新密码
</Button>
</Form>
</Card>
);
}
function Dashboard({ onLogout, role }: { onLogout: () => void; role: string }) {
const navigate = useNavigate();
const location = useLocation();
const brand = useQuery({
queryKey: ["admin-shell-brand"],
queryFn: () => createApiClient().getAdminBrand(),
});
const memberships = useQuery({
queryKey: ["admin-brand-memberships"],
queryFn: () => createApiClient().listAdminBrands(),
});
const switchBrand = async (brandId: string) => {
try {
const result = await createApiClient().switchAdminBrand(brandId);
localStorage.setItem("adminToken", result.token);
window.location.reload();
} catch (error) {
message.error(error instanceof Error ? error.message : "品牌切换失败");
}
};
const page = location.pathname.split("/")[2] || "overview";
const items = [
{
type: "group" as const,
label: "日常经营",
children: [
{ key: "overview", label: "当前品牌概览" },
{ key: "publication", label: "配置与发布" },
{ key: "brand", label: "品牌表达" },
{ key: "trust", label: "信任内容" },
{ key: "services", label: "业务提供项" },
{ key: "inquiries", label: "咨询记录" },
],
},
...(role === "editor"
? []
: [
{
type: "group" as const,
label: "系统管理",
children: [
{ key: "workspace", label: "模板与表单设置" },
{ key: "capabilities", label: "能力插件" },
{ key: "members", label: "团队成员" },
],
},
]),
];
return (
<Layout style={{ minHeight: "100vh" }}>
<Layout.Sider breakpoint="lg" collapsedWidth={0}>
<Typography.Title level={4} style={{ color: "white", padding: 20 }}>
当前品牌工作区
</Typography.Title>
<Menu
theme="dark"
selectedKeys={[page]}
onClick={({ key }) => navigate(`/admin/${key}`)}
items={items}
/>
</Layout.Sider>
<Layout>
<Layout.Header
style={{
background: "white",
display: "flex",
justifyContent: "space-between",
alignItems: "center",
}}
>
<Space>
<Typography.Text strong>{brand.data?.name || "当前品牌"}</Typography.Text>
<Typography.Text type="secondary">品牌工作区</Typography.Text>
<Tag color={role === "owner" ? "blue" : "default"}>
{role === "owner" ? "负责人" : "内容编辑"}
</Tag>
<Select
size="small"
value={brand.data?.id}
loading={memberships.isLoading}
onChange={(value) => {
if (value) void switchBrand(value);
}}
options={(memberships.data ?? []).map((item) => ({
value: item.brand.id,
label: item.brand.name,
}))}
/>
</Space>
<Button type="text" onClick={onLogout}>
退出登录
</Button>
</Layout.Header>
<Layout.Content style={{ padding: 24 }}>
<Suspense fallback={<Card loading />}>
<Routes>
<Route path="/admin/overview" element={<FeatureOverviewPage />} />
<Route
path="/admin/publication"
element={<FeaturePublicationPage canManageTemplate={role !== "editor"} />}
/>
<Route path="/admin/brand" element={<FeatureBrandPage />} />
{role === "editor" ? null : (
<Route path="/admin/workspace" element={<FeatureWorkspacePage />} />
)}
{role === "editor" ? null : (
<Route path="/admin/capabilities" element={<FeatureCapabilitiesPage />} />
)}
{role === "editor" ? null : (
<Route path="/admin/members" element={<FeatureMembersPage />} />
)}
<Route path="/admin/trust" element={<FeatureTrustContentPage />} />
<Route path="/admin/services" element={<FeatureServicesPage />} />
<Route path="/admin/inquiries" element={<FeatureInquiriesPage />} />
<Route path="*" element={<Navigate to="/admin/overview" replace />} />
</Routes>
</Suspense>
</Layout.Content>
</Layout>
</Layout>
);
}
function Root() {
const [loggedIn, setLoggedIn] = useState(Boolean(localStorage.getItem("adminToken")));
const [role, setRole] = useState(localStorage.getItem("adminRole") || "owner");
const [mustChangePassword, setMustChangePassword] = useState(
localStorage.getItem("adminMustChangePassword") === "true",
);
React.useEffect(() => {
const expire = () => {
message.warning("登录状态已失效,请重新登录");
setLoggedIn(false);
};
window.addEventListener("admin-auth-expired", expire);
return () => window.removeEventListener("admin-auth-expired", expire);
}, []);
const logout = () => {
localStorage.removeItem("adminToken");
localStorage.removeItem("adminRole");
localStorage.removeItem("adminMustChangePassword");
setLoggedIn(false);
};
if (!loggedIn)
return (
<Login
onLogin={(session) => {
setRole(session.role);
setMustChangePassword(session.mustChangePassword);
setLoggedIn(true);
}}
/>
);
if (mustChangePassword) return <ChangePassword onComplete={() => setMustChangePassword(false)} />;
return <Dashboard onLogout={logout} role={role} />;
}
createRoot(document.getElementById("app")!).render(
<React.StrictMode>
<QueryClientProvider client={queryClient}>
<App>
<BrowserRouter>
<Root />
</BrowserRouter>
</App>
</QueryClientProvider>
</React.StrictMode>,
);