Compare commits
No commits in common. "4ad96f07be3e27e5ecf7362dcba4d20c42ba88c4" and "2f7e3bb86a5ff51f3d49c7cd9f765840c8b1ee9b" have entirely different histories.
4ad96f07be
...
2f7e3bb86a
12
AGENTS.md
12
AGENTS.md
@ -28,7 +28,7 @@
|
||||
- 应用壳:`src/app/App.jsx`、`src/app/layout/AdminLayout.jsx`、`src/app/router/routeConfig.ts`。
|
||||
- 页面加载占位:`src/shared/ui/PageSkeleton.jsx`。
|
||||
- 公共时间选择器:`src/shared/ui/TimeRangeFilter.jsx`,使用 `{ startMs, endMs }` 毫秒值作为输入输出。
|
||||
- 全局资源组选择抽屉:`src/shared/ui/ResourceGroupSelectDrawer.jsx`,业务表单资源组字段统一使用其导出的 `ResourceGroupSelectField`,不在业务页面里重复手写普通下拉或资源组 ID 输入框。
|
||||
- 全局资源组选择抽屉:`src/shared/ui/ResourceGroupSelectDrawer.jsx`,资源组字段优先使用该组件,不在业务页面里重复手写普通下拉。
|
||||
- 顶部搜索弹窗:`src/features/search/components/SearchDialog.jsx`。
|
||||
- MUI 主题:`src/theme.js`。
|
||||
- CSS token:`src/styles/tokens.css`。
|
||||
@ -77,10 +77,10 @@ import { Refresh } from "@mui/icons-material";
|
||||
## 样式规则
|
||||
|
||||
- 状态色不要随意改:
|
||||
- `--success`:运行中
|
||||
- `--warning`:警告
|
||||
- `--danger`:异常/危险操作
|
||||
- `--stopped`:已停止
|
||||
- `--success`:运行中
|
||||
- `--warning`:警告
|
||||
- `--danger`:异常/危险操作
|
||||
- `--stopped`:已停止
|
||||
- 新增颜色优先写入 token 或 theme,不要在多个组件里重复硬编码。
|
||||
- 基础组件的视觉兼容优先改封装组件,不要让页面直接依赖 MUI 细节。
|
||||
- 不添加卡片套卡片。
|
||||
@ -93,7 +93,7 @@ import { Refresh } from "@mui/icons-material";
|
||||
- 表格状态筛选使用 Select 下拉框,默认值为 `全部状态`,不使用状态 chip 组。
|
||||
- 后台列表页的时间区间筛选必须使用统一的单入口时间区间筛选框(`src/shared/ui/TimeRangeFilter.jsx`);不要在工具栏里并排放两个开始/结束时间输入框,也不要使用浏览器原生日期/时间输入样式。时间区间弹层内使用快捷项、日历和时分下拉点选,不使用手写时间文本框。
|
||||
- 后台表单里的生效时间、有效期、投放时间等时间区间必须使用统一公共时间选择器(`src/shared/ui/TimeRangeFilter.jsx`);不要并排放两个开始/结束时间输入框,也不要使用浏览器原生日期/时间输入样式。
|
||||
- 资源组选择必须优先使用统一的 `src/shared/ui/ResourceGroupSelectDrawer.jsx` / `ResourceGroupSelectField`,点击输入框打开右侧资源组图标抽屉,点击资源组后自动回填并关闭,不要在业务页面里重复实现资源组 Select 下拉,也不要用普通文本框填写资源组 ID。
|
||||
- 资源组选择必须优先使用统一的 `src/shared/ui/ResourceGroupSelectDrawer.jsx`,点击输入框打开右侧资源组图标抽屉,点击资源组后自动回填并关闭,不要在业务页面里重复实现资源组 Select 下拉。
|
||||
- 区域编辑弹窗必须同时包含区域基础字段和国家码字段;国家码使用可搜索多选下拉框,不再拆成独立“区域国家”弹窗。
|
||||
- 头像、图片、封面等图片资源字段必须使用 `src/shared/ui/UploadField.jsx` 上传表单组件,不使用普通文本输入框承载 URL。
|
||||
- 图片上传表单必须提供统一预览;`webp` 使用浏览器原生动效预览,`svga` 使用 SVGA 播放器预览,`pag` 使用 libpag + wasm 预览。
|
||||
|
||||
72
README.md
72
README.md
@ -54,40 +54,40 @@ pnpm build
|
||||
|
||||
- `src/App.jsx` 只负责应用状态、页面切换、抽屉挂载和数据分发。
|
||||
- 页面模块放在 `src/pages/`:
|
||||
- `OverviewPage.jsx`
|
||||
- `ServicesPage.jsx`
|
||||
- `UserManagementPage.jsx`
|
||||
- `OverviewPage.jsx`
|
||||
- `ServicesPage.jsx`
|
||||
- `UserManagementPage.jsx`
|
||||
- 基础组件放在 `src/components/base/`,对 MUI 做项目级封装:
|
||||
- `Button`
|
||||
- `IconButton`
|
||||
- `Card`
|
||||
- `SearchBox`
|
||||
- `FilterChip`
|
||||
- `KpiCard`
|
||||
- `SegmentControl`
|
||||
- 当前共享后台组件统一放在 `src/shared/ui/`;资源组字段统一使用 `ResourceGroupSelectDrawer.jsx` 导出的 `ResourceGroupSelectField`,点击输入框打开右侧资源组图标抽屉,选择后自动回填,不在业务页面里手写资源组下拉或资源组 ID 输入框。
|
||||
- `Button`
|
||||
- `IconButton`
|
||||
- `Card`
|
||||
- `SearchBox`
|
||||
- `FilterChip`
|
||||
- `KpiCard`
|
||||
- `SegmentControl`
|
||||
- 当前共享后台组件统一放在 `src/shared/ui/`;资源组字段使用 `ResourceGroupSelectDrawer.jsx`,点击输入框打开右侧资源组图标抽屉,选择后自动回填。
|
||||
- 布局组件放在 `src/components/layout/`:
|
||||
- `Header`
|
||||
- `Sidebar`
|
||||
- `PageHead`
|
||||
- `PageSkeleton`
|
||||
- `Header`
|
||||
- `Sidebar`
|
||||
- `PageHead`
|
||||
- `PageSkeleton`
|
||||
- 图表组件放在 `src/components/charts/`,统一封装 ECharts:
|
||||
- `EChart`
|
||||
- `LineChart`
|
||||
- `BarChart`
|
||||
- `StatusDonut`
|
||||
- `ChartCard`
|
||||
- `EChart`
|
||||
- `LineChart`
|
||||
- `BarChart`
|
||||
- `StatusDonut`
|
||||
- `ChartCard`
|
||||
- 服务业务组件放在 `src/components/service/`:
|
||||
- `ServiceTable`
|
||||
- `ServerRail`
|
||||
- `DetailPanel`
|
||||
- `RowActions`
|
||||
- `ResourceCell`
|
||||
- `StatusBadge`
|
||||
- `ServiceTable`
|
||||
- `ServerRail`
|
||||
- `DetailPanel`
|
||||
- `RowActions`
|
||||
- `ResourceCell`
|
||||
- `StatusBadge`
|
||||
- 常量、模拟数据和工具函数分别放在:
|
||||
- `src/constants/`
|
||||
- `src/data/`
|
||||
- `src/utils/`
|
||||
- `src/constants/`
|
||||
- `src/data/`
|
||||
- `src/utils/`
|
||||
|
||||
## 样式约定
|
||||
|
||||
@ -97,10 +97,10 @@ pnpm build
|
||||
- MUI 主题集中在 `src/theme.js`,优先在主题层统一颜色、圆角、hover、focus 和组件兼容样式。
|
||||
- 避免在页面里直接散落 MUI 组件样式;优先改项目封装组件。
|
||||
- 状态色必须保持语义一致:
|
||||
- 运行中:`--success`
|
||||
- 警告:`--warning`
|
||||
- 异常:`--danger`
|
||||
- 已停止:`--stopped`
|
||||
- 运行中:`--success`
|
||||
- 警告:`--warning`
|
||||
- 异常:`--danger`
|
||||
- 已停止:`--stopped`
|
||||
|
||||
## 按需导入约定
|
||||
|
||||
@ -109,9 +109,9 @@ pnpm build
|
||||
- 不使用 `@mui/material` 或 `@mui/icons-material` 总入口导入。
|
||||
- ECharts 通过封装组件按需加载所需图表和组件能力。
|
||||
- 页面使用 `React.lazy` 拆分:
|
||||
- `OverviewPage`
|
||||
- `ServicesPage`
|
||||
- `DetailDrawer`
|
||||
- `OverviewPage`
|
||||
- `ServicesPage`
|
||||
- `DetailDrawer`
|
||||
|
||||
## 动画与加载
|
||||
|
||||
|
||||
178
src/App.test.jsx
178
src/App.test.jsx
@ -7,127 +7,125 @@ import { adminRoutes } from "@/app/router/routeConfig";
|
||||
import { setAccessToken } from "@/shared/api/request";
|
||||
|
||||
beforeEach(() => {
|
||||
window.localStorage.clear();
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async () => new Response(JSON.stringify({ code: 401, message: "unauthorized" }), { status: 401 })),
|
||||
);
|
||||
window.localStorage.clear();
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async () => new Response(JSON.stringify({ code: 401, message: "unauthorized" }), { status: 401 }))
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
test("renders login route", async () => {
|
||||
renderWithRoute("/login");
|
||||
renderWithRoute("/login");
|
||||
|
||||
expect(await screen.findByText("HYApp 管理平台")).toBeInTheDocument();
|
||||
expect(await screen.findByText("HYApp 管理平台")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test("redirects protected route to login when unauthenticated", async () => {
|
||||
renderWithRoute("/system/users");
|
||||
renderWithRoute("/system/users");
|
||||
|
||||
expect(await screen.findByText("HYApp 管理平台")).toBeInTheDocument();
|
||||
expect(await screen.findByText("HYApp 管理平台")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test("renders resource list route with an authenticated session", async () => {
|
||||
setAccessToken("test-token");
|
||||
vi.mocked(fetch).mockImplementation(async (input) => {
|
||||
const url = String(input);
|
||||
if (url.includes("/v1/auth/refresh") || url.includes("/v1/auth/me")) {
|
||||
return jsonResponse({
|
||||
accessToken: "test-token",
|
||||
permissions: ["resource:view"],
|
||||
user: { userId: 1, username: "admin" },
|
||||
});
|
||||
}
|
||||
if (url.includes("/v1/admin/apps")) {
|
||||
return jsonResponse({ items: [{ appCode: "lalu", name: "Lalu" }], total: 1 });
|
||||
}
|
||||
if (url.includes("/v1/admin/navigation/menus")) {
|
||||
return jsonResponse([]);
|
||||
}
|
||||
if (url.includes("/v1/admin/resources")) {
|
||||
return jsonResponse({ items: [], page: 1, pageSize: 50, total: 0 });
|
||||
}
|
||||
return jsonResponse(null);
|
||||
});
|
||||
setAccessToken("test-token");
|
||||
vi.mocked(fetch).mockImplementation(async (input) => {
|
||||
const url = String(input);
|
||||
if (url.includes("/v1/auth/refresh") || url.includes("/v1/auth/me")) {
|
||||
return jsonResponse({
|
||||
accessToken: "test-token",
|
||||
permissions: ["resource:view"],
|
||||
user: { userId: 1, username: "admin" },
|
||||
});
|
||||
}
|
||||
if (url.includes("/v1/admin/apps")) {
|
||||
return jsonResponse({ items: [{ appCode: "lalu", name: "Lalu" }], total: 1 });
|
||||
}
|
||||
if (url.includes("/v1/admin/navigation/menus")) {
|
||||
return jsonResponse([]);
|
||||
}
|
||||
if (url.includes("/v1/admin/resources")) {
|
||||
return jsonResponse({ items: [], page: 1, pageSize: 50, total: 0 });
|
||||
}
|
||||
return jsonResponse(null);
|
||||
});
|
||||
|
||||
renderWithRoute("/resources");
|
||||
renderWithRoute("/resources");
|
||||
|
||||
expect((await screen.findAllByText("资源列表")).length).toBeGreaterThan(0);
|
||||
expect(await screen.findByText("资源")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test("renders cp config route with an authenticated session", async () => {
|
||||
setAccessToken("test-token");
|
||||
vi.mocked(fetch).mockImplementation(async (input) => {
|
||||
const url = String(input);
|
||||
if (url.includes("/v1/auth/refresh") || url.includes("/v1/auth/me")) {
|
||||
return jsonResponse({
|
||||
accessToken: "test-token",
|
||||
permissions: ["cp-config:view"],
|
||||
user: { userId: 1, username: "admin" },
|
||||
});
|
||||
}
|
||||
if (url.includes("/v1/admin/apps")) {
|
||||
return jsonResponse({ items: [{ appCode: "lalu", name: "Lalu" }], total: 1 });
|
||||
}
|
||||
if (url.includes("/v1/admin/navigation/menus")) {
|
||||
return jsonResponse([]);
|
||||
}
|
||||
if (url.includes("/v1/admin/resource-groups")) {
|
||||
return jsonResponse({ items: [], page: 1, pageSize: 50, total: 0 });
|
||||
}
|
||||
if (url.includes("/v1/admin/activity/cp/config")) {
|
||||
return jsonResponse({
|
||||
appCode: "lalu",
|
||||
relations: [
|
||||
cpRelationFixture("cp", "CP", 1),
|
||||
cpRelationFixture("brother", "兄弟", 5),
|
||||
cpRelationFixture("sister", "姐妹", 5),
|
||||
],
|
||||
});
|
||||
}
|
||||
return jsonResponse(null);
|
||||
});
|
||||
setAccessToken("test-token");
|
||||
vi.mocked(fetch).mockImplementation(async (input) => {
|
||||
const url = String(input);
|
||||
if (url.includes("/v1/auth/refresh") || url.includes("/v1/auth/me")) {
|
||||
return jsonResponse({
|
||||
accessToken: "test-token",
|
||||
permissions: ["cp-config:view"],
|
||||
user: { userId: 1, username: "admin" },
|
||||
});
|
||||
}
|
||||
if (url.includes("/v1/admin/apps")) {
|
||||
return jsonResponse({ items: [{ appCode: "lalu", name: "Lalu" }], total: 1 });
|
||||
}
|
||||
if (url.includes("/v1/admin/navigation/menus")) {
|
||||
return jsonResponse([]);
|
||||
}
|
||||
if (url.includes("/v1/admin/activity/cp/config")) {
|
||||
return jsonResponse({
|
||||
appCode: "lalu",
|
||||
relations: [
|
||||
cpRelationFixture("cp", "CP", 1),
|
||||
cpRelationFixture("brother", "兄弟", 5),
|
||||
cpRelationFixture("sister", "姐妹", 5),
|
||||
],
|
||||
});
|
||||
}
|
||||
return jsonResponse(null);
|
||||
});
|
||||
|
||||
renderWithRoute("/activities/cp-config");
|
||||
renderWithRoute("/activities/cp-config");
|
||||
|
||||
expect((await screen.findAllByText("CP配置")).length).toBeGreaterThan(0);
|
||||
expect((await screen.findAllByText("CP配置")).length).toBeGreaterThan(0);
|
||||
expect(await screen.findByText("兄弟上限")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test("admin routes declare menu code and permission", () => {
|
||||
expect(adminRoutes.length).toBeGreaterThan(0);
|
||||
expect(adminRoutes.every((route) => route.menuCode && route.permission)).toBe(true);
|
||||
expect(adminRoutes.length).toBeGreaterThan(0);
|
||||
expect(adminRoutes.every((route) => route.menuCode && route.permission)).toBe(true);
|
||||
});
|
||||
|
||||
function renderWithRoute(route) {
|
||||
return render(
|
||||
<AppProviders>
|
||||
<MemoryRouter initialEntries={[route]}>
|
||||
<App />
|
||||
</MemoryRouter>
|
||||
</AppProviders>,
|
||||
);
|
||||
return render(
|
||||
<AppProviders>
|
||||
<MemoryRouter initialEntries={[route]}>
|
||||
<App />
|
||||
</MemoryRouter>
|
||||
</AppProviders>
|
||||
);
|
||||
}
|
||||
|
||||
function jsonResponse(data) {
|
||||
return new Response(JSON.stringify({ code: 0, data }), { status: 200 });
|
||||
return new Response(JSON.stringify({ code: 0, data }), { status: 200 });
|
||||
}
|
||||
|
||||
function cpRelationFixture(relationType, displayName, maxCountPerUser) {
|
||||
return {
|
||||
relationType,
|
||||
displayName,
|
||||
maxCountPerUser,
|
||||
applicationExpireHours: 24,
|
||||
status: "active",
|
||||
levels: Array.from({ length: 5 }, (_, index) => ({
|
||||
level: index + 1,
|
||||
intimacyThreshold: index * 10000,
|
||||
rewardResourceGroupId: 0,
|
||||
levelIconUrl: "",
|
||||
status: "active",
|
||||
})),
|
||||
};
|
||||
return {
|
||||
relationType,
|
||||
displayName,
|
||||
maxCountPerUser,
|
||||
applicationExpireHours: 24,
|
||||
status: "active",
|
||||
levels: Array.from({ length: 5 }, (_, index) => ({
|
||||
level: index + 1,
|
||||
intimacyThreshold: index * 10000,
|
||||
rewardResourceGroupId: 0,
|
||||
levelIconUrl: "",
|
||||
status: "active",
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
@ -16,7 +16,6 @@ export interface CPRelationConfigDto {
|
||||
displayName: string;
|
||||
maxCountPerUser: number;
|
||||
applicationExpireHours: number;
|
||||
breakupCostCoins: number;
|
||||
status: string;
|
||||
levels: CPLevelDto[];
|
||||
updatedAtMs?: number;
|
||||
@ -33,7 +32,6 @@ export interface CPConfigPayload {
|
||||
relationType: CPRelationType;
|
||||
maxCountPerUser: number;
|
||||
applicationExpireHours: number;
|
||||
breakupCostCoins: number;
|
||||
status: string;
|
||||
levels: Array<{
|
||||
level: number;
|
||||
@ -76,7 +74,6 @@ function normalizeRelation(raw: unknown): CPRelationConfigDto {
|
||||
displayName: stringValue(item.displayName ?? item.display_name) || relationLabel(relationType),
|
||||
maxCountPerUser: numberValue(item.maxCountPerUser ?? item.max_count_per_user),
|
||||
applicationExpireHours: numberValue(item.applicationExpireHours ?? item.application_expire_hours),
|
||||
breakupCostCoins: numberValue(item.breakupCostCoins ?? item.breakup_cost_coins),
|
||||
status: stringValue(item.status) || "active",
|
||||
levels: arrayValue(item.levels).map(normalizeLevel),
|
||||
updatedAtMs: numberValue(item.updatedAtMs ?? item.updated_at_ms),
|
||||
|
||||
@ -92,84 +92,22 @@
|
||||
.relationEditorList,
|
||||
.levelEditorList {
|
||||
display: grid;
|
||||
gap: 16px;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.configDrawer {
|
||||
box-sizing: border-box;
|
||||
width: min(980px, calc(100vw - 48px));
|
||||
height: 100vh;
|
||||
max-height: 100vh;
|
||||
grid-template-rows: auto minmax(0, 1fr) auto;
|
||||
overflow: hidden;
|
||||
padding: var(--space-5);
|
||||
}
|
||||
|
||||
.configDrawerHeader {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-4);
|
||||
padding-bottom: var(--space-3);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.configDrawerHeader h2 {
|
||||
margin: 0;
|
||||
font-size: 20px;
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
.configDrawerStats {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-end;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.configDrawerStats span {
|
||||
display: inline-flex;
|
||||
height: var(--admin-tag-height);
|
||||
align-items: center;
|
||||
padding: 0 var(--space-3);
|
||||
border: 1px solid var(--admin-tag-border);
|
||||
border-radius: var(--admin-tag-radius);
|
||||
background: var(--admin-tag-bg);
|
||||
color: var(--admin-tag-color);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.configDrawerBody {
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
padding-right: 2px;
|
||||
}
|
||||
|
||||
.configDrawerActions {
|
||||
padding-top: var(--space-3);
|
||||
border-top: 1px solid var(--border);
|
||||
background: var(--bg-card);
|
||||
}
|
||||
|
||||
.relationEditor {
|
||||
.relationEditor,
|
||||
.levelEditor {
|
||||
border: 1px solid var(--color-border-subtle);
|
||||
border-radius: 8px;
|
||||
background: var(--bg-card);
|
||||
background: var(--color-surface-subtle);
|
||||
}
|
||||
|
||||
.relationEditor {
|
||||
padding: 18px;
|
||||
padding: 14px;
|
||||
}
|
||||
|
||||
.levelEditor {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
min-width: 0;
|
||||
padding: 16px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-control);
|
||||
background: var(--bg-card-strong);
|
||||
padding: 12px;
|
||||
}
|
||||
|
||||
.relationEditorHeader,
|
||||
@ -178,54 +116,12 @@
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
margin-bottom: 14px;
|
||||
margin-bottom: 12px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.levelEditorList {
|
||||
grid-template-columns: repeat(2, minmax(320px, 1fr));
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.relationTitleGroup,
|
||||
.levelTitleGroup {
|
||||
display: grid;
|
||||
min-width: 0;
|
||||
gap: 3px;
|
||||
}
|
||||
|
||||
.relationTitle,
|
||||
.levelTitle {
|
||||
color: var(--text-primary);
|
||||
font-size: 16px;
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
.relationSubtitle,
|
||||
.levelMeta {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
color: var(--text-tertiary);
|
||||
font-size: 12px;
|
||||
font-weight: 650;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.relationControls {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(180px, 1fr));
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
.levelFields {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(140px, 0.7fr) minmax(220px, 1fr);
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
.levelFields > :last-child {
|
||||
grid-column: 1 / -1;
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
@media (max-width: 760px) {
|
||||
@ -237,24 +133,4 @@
|
||||
.summaryActions {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.configDrawer {
|
||||
width: 100vw;
|
||||
padding: var(--space-4);
|
||||
}
|
||||
|
||||
.configDrawerHeader {
|
||||
align-items: flex-start;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.levelEditorList,
|
||||
.relationControls,
|
||||
.levelFields {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.levelFields > :last-child {
|
||||
grid-column: auto;
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,7 +1,6 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { getCPConfig, updateCPConfig } from "@/features/cp-config/api";
|
||||
import { useCPConfigAbilities } from "@/features/cp-config/permissions.js";
|
||||
import { listResourceGroups } from "@/features/resources/api";
|
||||
import { useToast } from "@/shared/ui/ToastProvider.jsx";
|
||||
|
||||
export const cpRelationTypes = ["cp", "brother", "sister"];
|
||||
@ -21,7 +20,6 @@ export function useCPConfigPage() {
|
||||
const [form, setForm] = useState({ relations: defaultRelations().map(relationToForm) });
|
||||
const [drawerOpen, setDrawerOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [resourceGroups, setResourceGroups] = useState([]);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
const activeRelationCount = useMemo(
|
||||
@ -32,23 +30,10 @@ export function useCPConfigPage() {
|
||||
const reload = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [configResult, groupResult] = await Promise.allSettled([
|
||||
getCPConfig(),
|
||||
listResourceGroups({ page: 1, page_size: 200, status: "active" }),
|
||||
]);
|
||||
if (configResult.status === "fulfilled") {
|
||||
const remoteConfig = configResult.value;
|
||||
const relations = completeRelations(remoteConfig.relations || []);
|
||||
setConfig({ ...remoteConfig, relations });
|
||||
setForm({ relations: relations.map(relationToForm) });
|
||||
} else {
|
||||
showToast(configResult.reason?.message || "加载 CP 配置失败", "error");
|
||||
}
|
||||
if (groupResult.status === "fulfilled") {
|
||||
setResourceGroups(groupResult.value?.items || []);
|
||||
} else {
|
||||
showToast(groupResult.reason?.message || "加载资源组失败", "error");
|
||||
}
|
||||
const remoteConfig = await getCPConfig();
|
||||
const relations = completeRelations(remoteConfig.relations || []);
|
||||
setConfig({ ...remoteConfig, relations });
|
||||
setForm({ relations: relations.map(relationToForm) });
|
||||
} catch (err) {
|
||||
showToast(err.message || "加载 CP 配置失败", "error");
|
||||
} finally {
|
||||
@ -135,7 +120,6 @@ export function useCPConfigPage() {
|
||||
loading,
|
||||
openDrawer,
|
||||
reload,
|
||||
resourceGroups,
|
||||
saving,
|
||||
submit,
|
||||
updateLevel,
|
||||
@ -149,7 +133,6 @@ export function defaultRelations() {
|
||||
displayName: cpRelationLabels[relationType],
|
||||
maxCountPerUser: relationType === "cp" ? 1 : 5,
|
||||
applicationExpireHours: defaultExpireHours,
|
||||
breakupCostCoins: 0,
|
||||
status: "active",
|
||||
levels: defaultLevels(),
|
||||
updatedAtMs: 0,
|
||||
@ -195,7 +178,6 @@ function relationToForm(relation) {
|
||||
displayName: relation.displayName || cpRelationLabels[relation.relationType],
|
||||
maxCountPerUser: relation.relationType === "cp" ? "1" : String(relation.maxCountPerUser || 5),
|
||||
applicationExpireHours: String(relation.applicationExpireHours || defaultExpireHours),
|
||||
breakupCostCoins: String(relation.breakupCostCoins || 0),
|
||||
status: relation.status || "active",
|
||||
levels: completeLevels(relation.levels || []).map(levelToForm),
|
||||
};
|
||||
@ -216,7 +198,6 @@ function payloadFromForm(form) {
|
||||
const relationType = relation.relationType;
|
||||
const maxCountPerUser = relationType === "cp" ? 1 : Number(relation.maxCountPerUser || 0);
|
||||
const applicationExpireHours = Number(relation.applicationExpireHours || 0);
|
||||
const breakupCostCoins = Number(relation.breakupCostCoins || 0);
|
||||
const status = relation.status === "disabled" ? "disabled" : "active";
|
||||
if (!Number.isInteger(maxCountPerUser) || maxCountPerUser <= 0) {
|
||||
throw new Error(`${cpRelationLabels[relationType]}数量必须大于 0`);
|
||||
@ -224,14 +205,10 @@ function payloadFromForm(form) {
|
||||
if (!Number.isInteger(applicationExpireHours) || applicationExpireHours <= 0) {
|
||||
throw new Error(`${cpRelationLabels[relationType]}申请过期小时必须大于 0`);
|
||||
}
|
||||
if (!Number.isInteger(breakupCostCoins) || breakupCostCoins < 0) {
|
||||
throw new Error(`${cpRelationLabels[relationType]}解除费用不能小于 0`);
|
||||
}
|
||||
return {
|
||||
relationType,
|
||||
maxCountPerUser,
|
||||
applicationExpireHours,
|
||||
breakupCostCoins,
|
||||
status,
|
||||
levels: completeFormLevels(relation.levels || [], relationType),
|
||||
};
|
||||
@ -241,10 +218,7 @@ function payloadFromForm(form) {
|
||||
|
||||
function completeFormRelations(relations) {
|
||||
const byType = new Map((relations || []).map((relation) => [relation.relationType, relation]));
|
||||
return defaultRelations().map((fallback) => ({
|
||||
...relationToForm(fallback),
|
||||
...(byType.get(fallback.relationType) || {}),
|
||||
}));
|
||||
return defaultRelations().map((fallback) => ({ ...relationToForm(fallback), ...(byType.get(fallback.relationType) || {}) }));
|
||||
}
|
||||
|
||||
function completeFormLevels(levels, relationType) {
|
||||
|
||||
@ -4,14 +4,16 @@ import SaveOutlined from "@mui/icons-material/SaveOutlined";
|
||||
import Drawer from "@mui/material/Drawer";
|
||||
import TextField from "@mui/material/TextField";
|
||||
import { useMemo } from "react";
|
||||
import { cpRelationLabels, useCPConfigPage } from "@/features/cp-config/hooks/useCPConfigPage.js";
|
||||
import {
|
||||
cpRelationLabels,
|
||||
useCPConfigPage,
|
||||
} from "@/features/cp-config/hooks/useCPConfigPage.js";
|
||||
import styles from "@/features/cp-config/cp-config.module.css";
|
||||
import { AdminListBody, AdminListPage } from "@/shared/ui/AdminListLayout.jsx";
|
||||
import { AdminSwitch } from "@/shared/ui/AdminSwitch.jsx";
|
||||
import { Button } from "@/shared/ui/Button.jsx";
|
||||
import { DataState } from "@/shared/ui/DataState.jsx";
|
||||
import { DataTable } from "@/shared/ui/DataTable.jsx";
|
||||
import { ResourceGroupSelectField } from "@/shared/ui/ResourceGroupSelectDrawer.jsx";
|
||||
import { formatMillis } from "@/shared/utils/time.js";
|
||||
|
||||
export function CPConfigPage() {
|
||||
@ -27,14 +29,9 @@ export function CPConfigPage() {
|
||||
<SummaryItem label="启用类型">{page.activeRelationCount}</SummaryItem>
|
||||
<SummaryItem label="兄弟上限">{relationMax(relations, "brother")}</SummaryItem>
|
||||
<SummaryItem label="姐妹上限">{relationMax(relations, "sister")}</SummaryItem>
|
||||
<SummaryItem label="CP解除费">{relationBreakupCost(relations, "cp")}</SummaryItem>
|
||||
</div>
|
||||
<div className={styles.summaryActions}>
|
||||
<Button
|
||||
disabled={page.loading}
|
||||
startIcon={<RefreshOutlined fontSize="small" />}
|
||||
onClick={page.reload}
|
||||
>
|
||||
<Button disabled={page.loading} startIcon={<RefreshOutlined fontSize="small" />} onClick={page.reload}>
|
||||
刷新
|
||||
</Button>
|
||||
{page.abilities.canUpdate ? (
|
||||
@ -51,12 +48,7 @@ export function CPConfigPage() {
|
||||
</div>
|
||||
<DataState loading={page.loading} onRetry={page.reload}>
|
||||
<AdminListBody>
|
||||
<DataTable
|
||||
columns={columns}
|
||||
items={relations}
|
||||
minWidth="1120px"
|
||||
rowKey={(item) => item.relationType}
|
||||
/>
|
||||
<DataTable columns={columns} items={relations} minWidth="1120px" rowKey={(item) => item.relationType} />
|
||||
</AdminListBody>
|
||||
</DataState>
|
||||
<CPConfigDrawer page={page} />
|
||||
@ -68,32 +60,23 @@ function CPConfigDrawer({ page }) {
|
||||
const disabled = !page.abilities.canUpdate || page.saving || page.loading;
|
||||
return (
|
||||
<Drawer anchor="right" open={page.drawerOpen} onClose={page.saving ? undefined : page.closeDrawer}>
|
||||
<form className={["form-drawer", styles.configDrawer].join(" ")} onSubmit={page.submit}>
|
||||
<div className={styles.configDrawerHeader}>
|
||||
<h2>CP配置</h2>
|
||||
<div className={styles.configDrawerStats}>
|
||||
<span>{(page.form.relations || []).length} 个关系</span>
|
||||
<span>{page.activeRelationCount} 个启用</span>
|
||||
<form className="form-drawer form-drawer--wide" onSubmit={page.submit}>
|
||||
<h2>CP配置</h2>
|
||||
<section className="form-drawer__section">
|
||||
<div className="form-drawer__section-title">关系与等级</div>
|
||||
<div className={styles.relationEditorList}>
|
||||
{(page.form.relations || []).map((relation) => (
|
||||
<RelationEditor
|
||||
disabled={disabled}
|
||||
key={relation.relationType}
|
||||
relation={relation}
|
||||
updateLevel={page.updateLevel}
|
||||
updateRelation={page.updateRelation}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className={styles.configDrawerBody}>
|
||||
<section className="form-drawer__section">
|
||||
<div className="form-drawer__section-title">关系与等级</div>
|
||||
<div className={styles.relationEditorList}>
|
||||
{(page.form.relations || []).map((relation) => (
|
||||
<RelationEditor
|
||||
disabled={disabled}
|
||||
key={relation.relationType}
|
||||
relation={relation}
|
||||
resourceGroups={page.resourceGroups}
|
||||
updateLevel={page.updateLevel}
|
||||
updateRelation={page.updateRelation}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
<div className={["form-drawer__actions", styles.configDrawerActions].join(" ")}>
|
||||
</section>
|
||||
<div className="form-drawer__actions">
|
||||
<Button disabled={page.saving} type="button" onClick={page.closeDrawer}>
|
||||
取消
|
||||
</Button>
|
||||
@ -111,22 +94,14 @@ function CPConfigDrawer({ page }) {
|
||||
);
|
||||
}
|
||||
|
||||
function RelationEditor({ disabled, relation, resourceGroups, updateLevel, updateRelation }) {
|
||||
function RelationEditor({ disabled, relation, updateLevel, updateRelation }) {
|
||||
const relationType = relation.relationType;
|
||||
const maxCountDisabled = disabled || relationType === "cp";
|
||||
const activeLevelCount = (relation.levels || []).filter((level) => level.status === "active").length;
|
||||
|
||||
return (
|
||||
<div className={styles.relationEditor}>
|
||||
<div className={styles.relationEditorHeader}>
|
||||
<div className={styles.relationTitleGroup}>
|
||||
<span className={styles.relationTitle}>
|
||||
{relation.displayName || cpRelationLabels[relationType]}
|
||||
</span>
|
||||
<span className={styles.relationSubtitle}>
|
||||
{relationType} / {activeLevelCount} 个等级启用
|
||||
</span>
|
||||
</div>
|
||||
<span>{relation.displayName || cpRelationLabels[relationType]}</span>
|
||||
<AdminSwitch
|
||||
checked={relation.status === "active"}
|
||||
checkedLabel="启用"
|
||||
@ -138,7 +113,7 @@ function RelationEditor({ disabled, relation, resourceGroups, updateLevel, updat
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.relationControls}>
|
||||
<div className="form-drawer__grid">
|
||||
<TextField
|
||||
disabled={maxCountDisabled}
|
||||
inputProps={{ min: 1, step: 1 }}
|
||||
@ -155,14 +130,6 @@ function RelationEditor({ disabled, relation, resourceGroups, updateLevel, updat
|
||||
value={relation.applicationExpireHours}
|
||||
onChange={(event) => updateRelation(relationType, { applicationExpireHours: event.target.value })}
|
||||
/>
|
||||
<TextField
|
||||
disabled={disabled}
|
||||
inputProps={{ min: 0, step: 1 }}
|
||||
label="解除费用金币"
|
||||
type="number"
|
||||
value={relation.breakupCostCoins}
|
||||
onChange={(event) => updateRelation(relationType, { breakupCostCoins: event.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.levelEditorList}>
|
||||
{(relation.levels || []).map((level) => (
|
||||
@ -171,7 +138,6 @@ function RelationEditor({ disabled, relation, resourceGroups, updateLevel, updat
|
||||
key={`${relationType}-${level.level}`}
|
||||
level={level}
|
||||
relationType={relationType}
|
||||
resourceGroups={resourceGroups}
|
||||
updateLevel={updateLevel}
|
||||
/>
|
||||
))}
|
||||
@ -180,18 +146,11 @@ function RelationEditor({ disabled, relation, resourceGroups, updateLevel, updat
|
||||
);
|
||||
}
|
||||
|
||||
function LevelEditor({ disabled, level, relationType, resourceGroups, updateLevel }) {
|
||||
const selectedGroup = resourceGroups.find((group) => String(group.groupId) === String(level.rewardResourceGroupId));
|
||||
|
||||
function LevelEditor({ disabled, level, relationType, updateLevel }) {
|
||||
return (
|
||||
<div className={styles.levelEditor}>
|
||||
<div className={styles.levelEditorHeader}>
|
||||
<div className={styles.levelTitleGroup}>
|
||||
<span className={styles.levelTitle}>{level.level}级</span>
|
||||
<span className={styles.levelMeta}>
|
||||
{resourceGroupLabel(selectedGroup, level.rewardResourceGroupId)}
|
||||
</span>
|
||||
</div>
|
||||
<span>{level.level}级</span>
|
||||
<AdminSwitch
|
||||
checked={level.status === "active"}
|
||||
checkedLabel="启用"
|
||||
@ -205,7 +164,7 @@ function LevelEditor({ disabled, level, relationType, resourceGroups, updateLeve
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.levelFields}>
|
||||
<div className="form-drawer__grid">
|
||||
<TextField
|
||||
disabled={disabled}
|
||||
inputProps={{ min: 0, step: 1 }}
|
||||
@ -216,16 +175,15 @@ function LevelEditor({ disabled, level, relationType, resourceGroups, updateLeve
|
||||
updateLevel(relationType, level.level, { intimacyThreshold: event.target.value })
|
||||
}
|
||||
/>
|
||||
<ResourceGroupSelectField
|
||||
allowEmpty
|
||||
<TextField
|
||||
disabled={disabled}
|
||||
drawerTitle={`${cpRelationLabels[relationType]} ${level.level}级奖励资源组`}
|
||||
emptyLabel="不配置奖励"
|
||||
groups={resourceGroups}
|
||||
label="奖励资源组"
|
||||
placeholder="点击选择奖励资源组"
|
||||
inputProps={{ min: 0, step: 1 }}
|
||||
label="奖励资源组ID"
|
||||
type="number"
|
||||
value={level.rewardResourceGroupId}
|
||||
onChange={(value) => updateLevel(relationType, level.level, { rewardResourceGroupId: value })}
|
||||
onChange={(event) =>
|
||||
updateLevel(relationType, level.level, { rewardResourceGroupId: event.target.value })
|
||||
}
|
||||
/>
|
||||
<TextField
|
||||
disabled={disabled}
|
||||
@ -263,16 +221,10 @@ function cpConfigColumns() {
|
||||
width: "minmax(130px, 0.45fr)",
|
||||
render: (item) => `${formatNumber(item.applicationExpireHours)} 小时`,
|
||||
},
|
||||
{
|
||||
key: "breakupCost",
|
||||
label: "解除费用",
|
||||
width: "minmax(130px, 0.45fr)",
|
||||
render: (item) => `${formatNumber(item.breakupCostCoins)} 金币`,
|
||||
},
|
||||
{
|
||||
key: "levels",
|
||||
label: "等级亲密值",
|
||||
width: "minmax(360px, 1.2fr)",
|
||||
width: "minmax(360px, 1.3fr)",
|
||||
render: (item) => <LevelPreview levels={item.levels || []} />,
|
||||
},
|
||||
{
|
||||
@ -325,18 +277,6 @@ function relationMax(relations, relationType) {
|
||||
return relation ? formatNumber(relation.maxCountPerUser) : "-";
|
||||
}
|
||||
|
||||
function relationBreakupCost(relations, relationType) {
|
||||
const relation = relations.find((item) => item.relationType === relationType);
|
||||
return relation ? `${formatNumber(relation.breakupCostCoins)} 金币` : "-";
|
||||
}
|
||||
|
||||
function resourceGroupLabel(group, value) {
|
||||
if (group) {
|
||||
return group.name || group.groupCode || `资源组 #${group.groupId}`;
|
||||
}
|
||||
return value ? `资源组 #${value}` : "未配置奖励";
|
||||
}
|
||||
|
||||
function formatNumber(value) {
|
||||
return Number(value || 0).toLocaleString("zh-CN");
|
||||
}
|
||||
|
||||
@ -48,17 +48,6 @@ const defaultPlatformForm = {
|
||||
sortOrder: 0,
|
||||
};
|
||||
|
||||
const defaultBridgeScriptForm = {
|
||||
bridgeScriptUrl: "",
|
||||
bridgeScriptVersion: "",
|
||||
bridgeScriptSha256: "",
|
||||
};
|
||||
|
||||
const defaultBridgeHashState = {
|
||||
loading: false,
|
||||
error: "",
|
||||
};
|
||||
|
||||
const emptyCatalog = { items: [], pageSize: 50 };
|
||||
const emptyPlatforms = { items: [] };
|
||||
const defaultPageSize = 50;
|
||||
@ -80,8 +69,6 @@ export function useGamesPage() {
|
||||
const [editingPlatformCode, setEditingPlatformCode] = useState("");
|
||||
const [gameForm, setGameForm] = useState(defaultGameForm);
|
||||
const [platformForm, setPlatformForm] = useState(defaultPlatformForm);
|
||||
const [bridgeScriptForm, setBridgeScriptForm] = useState(defaultBridgeScriptForm);
|
||||
const [bridgeHashState, setBridgeHashState] = useState(defaultBridgeHashState);
|
||||
const [loadingAction, setLoadingAction] = useState("");
|
||||
const [syncPlatform, setSyncPlatform] = useState(null);
|
||||
const [syncCandidates, setSyncCandidates] = useState([]);
|
||||
@ -117,9 +104,7 @@ export function useGamesPage() {
|
||||
return result;
|
||||
}
|
||||
setCatalogMeta(result);
|
||||
setCatalogItems((current) =>
|
||||
append ? mergeCatalogItems(current, result.items || []) : result.items || [],
|
||||
);
|
||||
setCatalogItems((current) => (append ? mergeCatalogItems(current, result.items || []) : result.items || []));
|
||||
return result;
|
||||
} catch (err) {
|
||||
if (catalogRequestRef.current === requestId) {
|
||||
@ -215,12 +200,6 @@ export function useGamesPage() {
|
||||
setActiveAction("manage-platforms");
|
||||
};
|
||||
|
||||
const openBridgeScript = () => {
|
||||
setBridgeScriptForm(bridgeScriptFormFromPlatforms(platformData.items || []));
|
||||
setBridgeHashState(defaultBridgeHashState);
|
||||
setActiveAction("bridge-script");
|
||||
};
|
||||
|
||||
const openEditPlatform = (platform) => {
|
||||
setEditingPlatformCode(platform.platformCode);
|
||||
setPlatformForm(platformToForm(platform));
|
||||
@ -233,80 +212,11 @@ export function useGamesPage() {
|
||||
setSyncCandidates([]);
|
||||
setSelectedSyncGameIds([]);
|
||||
}
|
||||
if (activeAction === "bridge-script") {
|
||||
setBridgeScriptForm(defaultBridgeScriptForm);
|
||||
setBridgeHashState(defaultBridgeHashState);
|
||||
}
|
||||
setActiveAction("");
|
||||
setEditingGameId("");
|
||||
setEditingPlatformCode("");
|
||||
};
|
||||
|
||||
const refreshBridgeScriptHash = useCallback(async () => {
|
||||
const url = bridgeScriptForm.bridgeScriptUrl.trim();
|
||||
if (activeAction !== "bridge-script" || url === "") {
|
||||
return "";
|
||||
}
|
||||
setBridgeHashState({ loading: true, error: "" });
|
||||
try {
|
||||
const hash = await calculateBridgeScriptSha256(url);
|
||||
setBridgeScriptForm((current) => {
|
||||
if (current.bridgeScriptUrl.trim() !== url) {
|
||||
return current;
|
||||
}
|
||||
return { ...current, bridgeScriptSha256: hash };
|
||||
});
|
||||
setBridgeHashState(defaultBridgeHashState);
|
||||
return hash;
|
||||
} catch (err) {
|
||||
const message = err.message || "生成 SHA256 失败";
|
||||
setBridgeHashState({ loading: false, error: message });
|
||||
showToast(message, "error");
|
||||
return "";
|
||||
}
|
||||
}, [activeAction, bridgeScriptForm.bridgeScriptUrl, showToast]);
|
||||
|
||||
useEffect(() => {
|
||||
if (activeAction !== "bridge-script") {
|
||||
return undefined;
|
||||
}
|
||||
const url = bridgeScriptForm.bridgeScriptUrl.trim();
|
||||
const version = bridgeScriptForm.bridgeScriptVersion.trim();
|
||||
if (!url || !version) {
|
||||
setBridgeScriptForm((current) =>
|
||||
current.bridgeScriptSha256 ? { ...current, bridgeScriptSha256: "" } : current,
|
||||
);
|
||||
setBridgeHashState(defaultBridgeHashState);
|
||||
return undefined;
|
||||
}
|
||||
let cancelled = false;
|
||||
const timer = window.setTimeout(async () => {
|
||||
setBridgeHashState({ loading: true, error: "" });
|
||||
try {
|
||||
const hash = await calculateBridgeScriptSha256(url);
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
setBridgeScriptForm((current) => {
|
||||
if (current.bridgeScriptUrl.trim() !== url || current.bridgeScriptVersion.trim() !== version) {
|
||||
return current;
|
||||
}
|
||||
return { ...current, bridgeScriptSha256: hash };
|
||||
});
|
||||
setBridgeHashState(defaultBridgeHashState);
|
||||
} catch (err) {
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
setBridgeHashState({ loading: false, error: err.message || "生成 SHA256 失败" });
|
||||
}
|
||||
}, 500);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
window.clearTimeout(timer);
|
||||
};
|
||||
}, [activeAction, bridgeScriptForm.bridgeScriptUrl, bridgeScriptForm.bridgeScriptVersion]);
|
||||
|
||||
const submitGame = async (event) => {
|
||||
event.preventDefault();
|
||||
const payload = gamePayload(gameForm);
|
||||
@ -348,54 +258,6 @@ export function useGamesPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const submitBridgeScript = async (event) => {
|
||||
event.preventDefault();
|
||||
const platforms = platformData.items || [];
|
||||
if (platforms.length === 0) {
|
||||
showToast("暂无游戏平台可写入", "error");
|
||||
return;
|
||||
}
|
||||
const bridgeScriptUrl = bridgeScriptForm.bridgeScriptUrl.trim();
|
||||
const bridgeScriptVersion = bridgeScriptForm.bridgeScriptVersion.trim();
|
||||
if (!bridgeScriptUrl || !bridgeScriptVersion) {
|
||||
showToast("请填写 bridge_script_url 和 bridge_script_version", "error");
|
||||
return;
|
||||
}
|
||||
let bridgeScriptSha256 = bridgeScriptForm.bridgeScriptSha256.trim();
|
||||
if (!bridgeScriptSha256) {
|
||||
bridgeScriptSha256 = await refreshBridgeScriptHash();
|
||||
}
|
||||
if (!bridgeScriptSha256) {
|
||||
return;
|
||||
}
|
||||
setLoadingAction("bridge-script");
|
||||
try {
|
||||
await Promise.all(
|
||||
platforms.map((platform) => {
|
||||
const config = parseJsonObject(platform.adapterConfigJson);
|
||||
config.bridge_script_url = bridgeScriptUrl;
|
||||
config.bridge_script_version = bridgeScriptVersion;
|
||||
config.bridge_script_sha256 = bridgeScriptSha256;
|
||||
delete config.bridgeScriptUrl;
|
||||
delete config.bridgeScriptVersion;
|
||||
delete config.bridgeScriptSha256;
|
||||
return upsertGamePlatform(
|
||||
platformUpsertPayload(platform, JSON.stringify(config, null, 2)),
|
||||
platform.platformCode,
|
||||
);
|
||||
}),
|
||||
);
|
||||
await reloadPlatforms();
|
||||
await reloadCatalog();
|
||||
showToast(`JS 桥接配置已同步 ${platforms.length} 个平台`, "success");
|
||||
closeAction();
|
||||
} catch (err) {
|
||||
showToast(err.message || "保存 JS 桥接配置失败", "error");
|
||||
} finally {
|
||||
setLoadingAction("");
|
||||
}
|
||||
};
|
||||
|
||||
const changeGameStatus = async (game, checked) => {
|
||||
const nextStatus = checked ? "active" : "maintenance";
|
||||
setLoadingAction(`status-${game.gameId}`);
|
||||
@ -518,8 +380,6 @@ export function useGamesPage() {
|
||||
abilities,
|
||||
activeAction,
|
||||
allSyncGamesSelected,
|
||||
bridgeHashState,
|
||||
bridgeScriptForm,
|
||||
changeGameStatus,
|
||||
deleteGame,
|
||||
closeAction,
|
||||
@ -540,7 +400,6 @@ export function useGamesPage() {
|
||||
importSingleSyncGame,
|
||||
openCreateGame,
|
||||
openCreatePlatform,
|
||||
openBridgeScript,
|
||||
openEditGame,
|
||||
openEditPlatform,
|
||||
openManagePlatforms,
|
||||
@ -550,18 +409,15 @@ export function useGamesPage() {
|
||||
platformForm,
|
||||
platformOptions,
|
||||
loadNextPage,
|
||||
refreshBridgeScriptHash,
|
||||
reload: reloadCatalog,
|
||||
resetFilters,
|
||||
resolveGameURL,
|
||||
changePageSize,
|
||||
setGameForm,
|
||||
setBridgeScriptForm,
|
||||
setPlatformCode: changePlatformCode,
|
||||
setPlatformForm,
|
||||
setStatus: changeStatus,
|
||||
status,
|
||||
submitBridgeScript,
|
||||
submitGame,
|
||||
submitPlatform,
|
||||
syncCandidates,
|
||||
@ -584,66 +440,6 @@ function mergeCatalogItems(current, nextItems) {
|
||||
});
|
||||
}
|
||||
|
||||
function bridgeScriptFormFromPlatform(platform) {
|
||||
if (!platform) {
|
||||
return defaultBridgeScriptForm;
|
||||
}
|
||||
const config = parseJsonObject(platform.adapterConfigJson);
|
||||
return {
|
||||
bridgeScriptUrl: readConfigString(config.bridge_script_url ?? config.bridgeScriptUrl),
|
||||
bridgeScriptVersion: readConfigString(config.bridge_script_version ?? config.bridgeScriptVersion),
|
||||
bridgeScriptSha256: readConfigString(
|
||||
config.bridge_script_sha256 ?? config.bridgeScriptSha256 ?? config.bridge_script_hash,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function bridgeScriptFormFromPlatforms(platforms) {
|
||||
for (const platform of platforms) {
|
||||
const form = bridgeScriptFormFromPlatform(platform);
|
||||
if (form.bridgeScriptUrl || form.bridgeScriptVersion || form.bridgeScriptSha256) {
|
||||
return form;
|
||||
}
|
||||
}
|
||||
return defaultBridgeScriptForm;
|
||||
}
|
||||
|
||||
function readConfigString(value) {
|
||||
if (value === null || value === undefined) {
|
||||
return "";
|
||||
}
|
||||
return String(value).trim();
|
||||
}
|
||||
|
||||
function platformUpsertPayload(platform, adapterConfigJson) {
|
||||
return {
|
||||
platformCode: platform.platformCode,
|
||||
platformName: platform.platformName,
|
||||
status: platform.status,
|
||||
apiBaseUrl: platform.apiBaseUrl,
|
||||
adapterType: platform.adapterType,
|
||||
callbackSecret: "",
|
||||
callbackIpWhitelist: platform.callbackIpWhitelist || [],
|
||||
adapterConfigJson,
|
||||
sortOrder: Number(platform.sortOrder || 0),
|
||||
};
|
||||
}
|
||||
|
||||
async function calculateBridgeScriptSha256(url) {
|
||||
if (!window.crypto?.subtle) {
|
||||
throw new Error("当前浏览器不支持 SHA256 计算");
|
||||
}
|
||||
const response = await fetch(url, { cache: "no-store" });
|
||||
if (!response.ok) {
|
||||
throw new Error(`拉取 JS 失败:HTTP ${response.status}`);
|
||||
}
|
||||
const buffer = await response.arrayBuffer();
|
||||
const digest = await window.crypto.subtle.digest("SHA-256", buffer);
|
||||
return Array.from(new Uint8Array(digest))
|
||||
.map((byte) => byte.toString(16).padStart(2, "0"))
|
||||
.join("");
|
||||
}
|
||||
|
||||
async function saveGameUrl(platforms, game, gameUrl) {
|
||||
const platform = platforms.find((item) => item.platformCode === game.platformCode);
|
||||
if (!platform) {
|
||||
@ -656,10 +452,9 @@ async function saveGameUrl(platforms, game, gameUrl) {
|
||||
}
|
||||
|
||||
const config = parseJsonObject(platform.adapterConfigJson);
|
||||
const gameURLs =
|
||||
config.game_urls && typeof config.game_urls === "object" && !Array.isArray(config.game_urls)
|
||||
? { ...config.game_urls }
|
||||
: {};
|
||||
const gameURLs = config.game_urls && typeof config.game_urls === "object" && !Array.isArray(config.game_urls)
|
||||
? { ...config.game_urls }
|
||||
: {};
|
||||
const keys = gameUrlKeys(game);
|
||||
for (const key of keys) {
|
||||
delete gameURLs[key];
|
||||
@ -673,7 +468,20 @@ async function saveGameUrl(platforms, game, gameUrl) {
|
||||
delete config.game_urls;
|
||||
}
|
||||
|
||||
await upsertGamePlatform(platformUpsertPayload(platform, JSON.stringify(config, null, 2)), platform.platformCode);
|
||||
await upsertGamePlatform(
|
||||
{
|
||||
platformCode: platform.platformCode,
|
||||
platformName: platform.platformName,
|
||||
status: platform.status,
|
||||
apiBaseUrl: platform.apiBaseUrl,
|
||||
adapterType: platform.adapterType,
|
||||
callbackSecret: "",
|
||||
callbackIpWhitelist: platform.callbackIpWhitelist || [],
|
||||
adapterConfigJson: JSON.stringify(config, null, 2),
|
||||
sortOrder: Number(platform.sortOrder || 0),
|
||||
},
|
||||
platform.platformCode,
|
||||
);
|
||||
}
|
||||
|
||||
function gameToForm(game, platforms = []) {
|
||||
|
||||
@ -1,5 +1,4 @@
|
||||
import Add from "@mui/icons-material/Add";
|
||||
import CodeOutlined from "@mui/icons-material/CodeOutlined";
|
||||
import DeleteOutlineOutlined from "@mui/icons-material/DeleteOutlineOutlined";
|
||||
import EditOutlined from "@mui/icons-material/EditOutlined";
|
||||
import SettingsOutlined from "@mui/icons-material/SettingsOutlined";
|
||||
@ -149,11 +148,6 @@ export function GameListPage() {
|
||||
<AdminListToolbar
|
||||
actions={
|
||||
<>
|
||||
{page.abilities.canUpdate ? (
|
||||
<AdminActionIconButton label="JS 桥接" onClick={page.openBridgeScript}>
|
||||
<CodeOutlined fontSize="small" />
|
||||
</AdminActionIconButton>
|
||||
) : null}
|
||||
{page.abilities.canUpdate ? (
|
||||
<AdminActionIconButton label="平台配置" onClick={page.openManagePlatforms}>
|
||||
<SettingsOutlined fontSize="small" />
|
||||
@ -215,14 +209,6 @@ export function GameListPage() {
|
||||
onClose={page.closeAction}
|
||||
onSubmit={page.submitPlatform}
|
||||
/>
|
||||
<BridgeScriptDialog
|
||||
form={page.bridgeScriptForm}
|
||||
loading={page.loadingAction === "bridge-script"}
|
||||
open={page.activeAction === "bridge-script"}
|
||||
page={page}
|
||||
onClose={page.closeAction}
|
||||
onSubmit={page.submitBridgeScript}
|
||||
/>
|
||||
<PlatformManageDialog
|
||||
open={page.activeAction === "manage-platforms"}
|
||||
page={page}
|
||||
@ -433,73 +419,6 @@ function GameFormDialog({ form, loading, mode, open, page, onClose, onSubmit })
|
||||
);
|
||||
}
|
||||
|
||||
function BridgeScriptDialog({ form, loading, open, page, onClose, onSubmit }) {
|
||||
const hashState = page.bridgeHashState || {};
|
||||
const disabled = !page.abilities.canUpdate;
|
||||
const submitDisabled =
|
||||
disabled ||
|
||||
loading ||
|
||||
hashState.loading ||
|
||||
!form.bridgeScriptUrl.trim() ||
|
||||
!form.bridgeScriptVersion.trim() ||
|
||||
!form.bridgeScriptSha256.trim();
|
||||
return (
|
||||
<AdminFormDialog
|
||||
disabled={disabled}
|
||||
loading={loading}
|
||||
open={open}
|
||||
submitDisabled={submitDisabled}
|
||||
submitLabel="保存桥接"
|
||||
title="JS 桥接配置"
|
||||
onClose={onClose}
|
||||
onSubmit={onSubmit}
|
||||
>
|
||||
<AdminFormSection
|
||||
title="通用桥接脚本"
|
||||
actions={
|
||||
<Button
|
||||
disabled={disabled || hashState.loading || !form.bridgeScriptUrl.trim()}
|
||||
onClick={page.refreshBridgeScriptHash}
|
||||
>
|
||||
{hashState.loading ? "生成中..." : "重新生成 SHA256"}
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<AdminFormFieldGrid columns="repeat(2, minmax(0, 1fr))">
|
||||
<TextField
|
||||
label="bridge_script_version"
|
||||
required
|
||||
value={form.bridgeScriptVersion}
|
||||
onChange={(event) =>
|
||||
page.setBridgeScriptForm({ ...form, bridgeScriptVersion: event.target.value })
|
||||
}
|
||||
/>
|
||||
<TextField
|
||||
className={styles.fullField}
|
||||
label="bridge_script_url"
|
||||
minRows={2}
|
||||
multiline
|
||||
required
|
||||
value={form.bridgeScriptUrl}
|
||||
onChange={(event) => page.setBridgeScriptForm({ ...form, bridgeScriptUrl: event.target.value })}
|
||||
/>
|
||||
<TextField
|
||||
className={styles.fullField}
|
||||
error={Boolean(hashState.error)}
|
||||
helperText={hashState.error || (hashState.loading ? "正在拉取 JS 并计算 SHA256" : "")}
|
||||
label="bridge_script_sha256"
|
||||
required
|
||||
value={form.bridgeScriptSha256}
|
||||
onChange={(event) =>
|
||||
page.setBridgeScriptForm({ ...form, bridgeScriptSha256: event.target.value })
|
||||
}
|
||||
/>
|
||||
</AdminFormFieldGrid>
|
||||
</AdminFormSection>
|
||||
</AdminFormDialog>
|
||||
);
|
||||
}
|
||||
|
||||
function PlatformFormDialog({ form, loading, mode, open, page, onClose, onSubmit }) {
|
||||
const isLeaderCC = form.adapterType === "leadercc_v1";
|
||||
return (
|
||||
|
||||
@ -51,7 +51,6 @@ test("resource APIs use generated admin paths", async () => {
|
||||
badgeKind: "level",
|
||||
coinPrice: 10,
|
||||
levelTrack: "wealth",
|
||||
managerGrantEnabled: true,
|
||||
metadataJson: '{"profile_card_layout":{"content_top":117,"content_height":1550}}',
|
||||
name: "VIP Badge",
|
||||
previewUrl: "https://media.haiyihy.com/resource/cover.png",
|
||||
@ -67,7 +66,6 @@ test("resource APIs use generated admin paths", async () => {
|
||||
badgeForm: "tile",
|
||||
badgeKind: "normal",
|
||||
coinPrice: 20,
|
||||
managerGrantEnabled: false,
|
||||
metadataJson: '{"profile_card_layout":{"content_top":120,"content_height":1500}}',
|
||||
name: "VIP Badge Updated",
|
||||
previewUrl: "https://media.haiyihy.com/resource/cover-updated.png",
|
||||
@ -81,7 +79,6 @@ test("resource APIs use generated admin paths", async () => {
|
||||
await createGift({
|
||||
chargeAssetType: "COIN",
|
||||
coinPrice: 10,
|
||||
cpRelationType: "",
|
||||
effectiveAtMs: 1777766400000,
|
||||
effectiveFromMs: 0,
|
||||
effectiveToMs: 0,
|
||||
@ -132,7 +129,6 @@ test("resource APIs use generated admin paths", async () => {
|
||||
await updateGift("rose", {
|
||||
chargeAssetType: "COIN",
|
||||
coinPrice: 10,
|
||||
cpRelationType: "",
|
||||
effectiveAtMs: 1777766400000,
|
||||
effectiveFromMs: 0,
|
||||
effectiveToMs: 0,
|
||||
|
||||
@ -10,7 +10,6 @@ export interface ResourceDto {
|
||||
name?: string;
|
||||
status?: string;
|
||||
grantable?: boolean;
|
||||
managerGrantEnabled?: boolean;
|
||||
grantStrategy?: string;
|
||||
walletAssetType?: string;
|
||||
walletAssetAmount?: number;
|
||||
@ -37,7 +36,6 @@ export interface ResourcePayload {
|
||||
badgeKind?: string;
|
||||
coinPrice: number;
|
||||
levelTrack?: string;
|
||||
managerGrantEnabled: boolean;
|
||||
metadataJson?: string;
|
||||
name: string;
|
||||
previewUrl: string;
|
||||
@ -126,7 +124,6 @@ export interface GiftDto {
|
||||
presentationJson?: string;
|
||||
priceVersion?: string;
|
||||
giftTypeCode?: string;
|
||||
cpRelationType?: string;
|
||||
chargeAssetType?: string;
|
||||
coinPrice?: number;
|
||||
effectiveFromMs?: number;
|
||||
@ -159,7 +156,6 @@ export interface GiftPayload {
|
||||
presentationJson: string;
|
||||
priceVersion: string;
|
||||
giftTypeCode: string;
|
||||
cpRelationType: string;
|
||||
chargeAssetType: string;
|
||||
coinPrice: number;
|
||||
effectiveAtMs: number;
|
||||
|
||||
@ -108,7 +108,6 @@ export function resourcePlanToPayload(item) {
|
||||
badgeForm: item.resourceType === "badge" ? item.badgeForm || "tile" : undefined,
|
||||
badgeKind: item.resourceType === "badge" ? "normal" : undefined,
|
||||
coinPrice,
|
||||
managerGrantEnabled: true,
|
||||
metadataJson: item.resourceType === "profile_card" ? profileCardMetadataJSON(item.metadataJson) : undefined,
|
||||
name: item.name,
|
||||
previewUrl: item.coverUrl,
|
||||
|
||||
@ -74,10 +74,6 @@ const emptyResourceForm = (resource = {}) => ({
|
||||
coinPrice: resource.coinPrice === 0 || resource.coinPrice ? String(resource.coinPrice) : "",
|
||||
enabled: resource.status ? resource.status === "active" : true,
|
||||
levelTrack: resource.resourceType === "badge" ? resource.levelTrack || levelTrackFromMetadata(resource.metadataJson) || "" : "",
|
||||
managerGrantEnabled:
|
||||
resource.managerGrantEnabled === undefined || resource.managerGrantEnabled === null
|
||||
? true
|
||||
: Boolean(resource.managerGrantEnabled),
|
||||
metadataJson: resource.metadataJson || "",
|
||||
name: resource.name || "",
|
||||
previewUrl: resource.previewUrl || "",
|
||||
@ -122,11 +118,14 @@ const emptyGroupWalletAssetItem = (walletAssetType) => ({
|
||||
const emptyGiftForm = (gift = {}) => {
|
||||
const giftTypeCode = gift.giftTypeCode || "normal";
|
||||
const presentationJson = gift.presentationJson || "{}";
|
||||
const cpRelationType = cpRelationTypeFromGift({ ...gift, giftTypeCode, presentationJson }) || defaultCPRelationType;
|
||||
const cpRelationType =
|
||||
giftTypeCode === cpGiftTypeCode
|
||||
? cpRelationTypeFromPresentationJson(presentationJson) || defaultCPRelationType
|
||||
: "";
|
||||
return {
|
||||
chargeAssetType: gift.chargeAssetType || "COIN",
|
||||
coinPrice: gift.coinPrice === 0 || gift.coinPrice ? String(gift.coinPrice) : "",
|
||||
cpRelationType: giftTypeCode === cpGiftTypeCode ? cpRelationType : "",
|
||||
cpRelationType,
|
||||
effectTypes: gift.effectTypes || [],
|
||||
effectiveFrom: msToDatetimeLocal(gift.effectiveFromMs),
|
||||
effectiveTo: msToDatetimeLocal(gift.effectiveToMs),
|
||||
@ -171,18 +170,6 @@ export function cpRelationTypeFromPresentationJson(presentationJson) {
|
||||
return relationType || "";
|
||||
}
|
||||
|
||||
export function cpRelationTypeFromGift(gift = {}) {
|
||||
if (gift?.giftTypeCode !== cpGiftTypeCode) {
|
||||
return "";
|
||||
}
|
||||
return validCPRelationType(gift.cpRelationType) || cpRelationTypeFromPresentationJson(gift.presentationJson);
|
||||
}
|
||||
|
||||
export function cpRelationTypeShortLabel(value) {
|
||||
const label = cpRelationTypeLabels[validCPRelationType(value)] || String(value || "").trim();
|
||||
return label.endsWith("礼物") ? label.slice(0, -2) : label;
|
||||
}
|
||||
|
||||
export function normalizeGiftPresentationJson(presentationJson, giftTypeCode, cpRelationType) {
|
||||
const rawValue = String(presentationJson || "").trim();
|
||||
const isCPGift = giftTypeCode === cpGiftTypeCode;
|
||||
@ -248,12 +235,8 @@ function parseGiftPresentationObject(presentationJson) {
|
||||
}
|
||||
|
||||
function normalizedCPRelationType(value) {
|
||||
return validCPRelationType(value) || defaultCPRelationType;
|
||||
}
|
||||
|
||||
function validCPRelationType(value) {
|
||||
const relationType = String(value || "").trim().toLowerCase();
|
||||
return cpRelationTypeValues.has(relationType) ? relationType : "";
|
||||
return cpRelationTypeValues.has(relationType) ? relationType : defaultCPRelationType;
|
||||
}
|
||||
|
||||
function cpPresentationJson(basePresentation, cpRelationType) {
|
||||
@ -401,27 +384,6 @@ export function useResourceListPage() {
|
||||
);
|
||||
};
|
||||
|
||||
const toggleManagerGrant = async (resource, nextEnabled = !resource.managerGrantEnabled) => {
|
||||
if (!abilities.canUpdate || !resource?.resourceId) {
|
||||
return;
|
||||
}
|
||||
if (Boolean(resource.managerGrantEnabled) === nextEnabled) {
|
||||
return;
|
||||
}
|
||||
await runAction(
|
||||
`resource-manager-grant-${resource.resourceId}`,
|
||||
nextEnabled ? "经理赠送已开启" : "经理赠送已关闭",
|
||||
async () => {
|
||||
const formValue = parseForm(resourceFormSchema, {
|
||||
...emptyResourceForm(resource),
|
||||
managerGrantEnabled: nextEnabled,
|
||||
});
|
||||
await updateResource(resource.resourceId, buildResourcePayload(formValue));
|
||||
await result.reload();
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const runAction = async (action, successMessage, submitter) => {
|
||||
setLoadingAction(action);
|
||||
try {
|
||||
@ -458,7 +420,6 @@ export function useResourceListPage() {
|
||||
setForm,
|
||||
status,
|
||||
submitResource,
|
||||
toggleManagerGrant,
|
||||
toggleResource,
|
||||
};
|
||||
}
|
||||
@ -1518,7 +1479,6 @@ function buildResourcePayload(form) {
|
||||
badgeKind: resourceType === "badge" ? form.badgeKind || "normal" : undefined,
|
||||
coinPrice: form.priceType === "coin" ? Number(form.coinPrice) : 0,
|
||||
levelTrack: resourceType === "badge" && form.badgeKind === "level" ? form.levelTrack : undefined,
|
||||
managerGrantEnabled: Boolean(form.managerGrantEnabled),
|
||||
metadataJson: resourceType === "profile_card" ? profileCardMetadataJSON(form.metadataJson) : undefined,
|
||||
name: form.name.trim(),
|
||||
previewUrl: form.previewUrl.trim(),
|
||||
@ -1642,11 +1602,9 @@ function buildResourceGroupPayload(form) {
|
||||
}
|
||||
|
||||
function buildGiftPayload(form) {
|
||||
const cpRelationType = form.giftTypeCode === cpGiftTypeCode ? normalizedCPRelationType(form.cpRelationType) : "";
|
||||
return {
|
||||
chargeAssetType: form.chargeAssetType,
|
||||
coinPrice: Number(form.coinPrice),
|
||||
cpRelationType,
|
||||
effectiveAtMs: Date.now(),
|
||||
effectiveFromMs: datetimeLocalToMs(form.effectiveFrom),
|
||||
effectiveToMs: datetimeLocalToMs(form.effectiveTo),
|
||||
@ -1664,11 +1622,9 @@ function buildGiftPayload(form) {
|
||||
}
|
||||
|
||||
function buildGiftInlineSortPayload(gift, sortOrder) {
|
||||
const cpRelationType = cpRelationTypeFromGift(gift);
|
||||
return {
|
||||
chargeAssetType: gift.chargeAssetType || "COIN",
|
||||
coinPrice: Number(gift.coinPrice || 0),
|
||||
cpRelationType: gift.giftTypeCode === cpGiftTypeCode ? cpRelationType || defaultCPRelationType : "",
|
||||
effectiveAtMs: Date.now(),
|
||||
effectiveFromMs: Number(gift.effectiveFromMs || 0),
|
||||
effectiveToMs: Number(gift.effectiveToMs || 0),
|
||||
|
||||
@ -2,9 +2,7 @@ import { expect, test, vi } from "vitest";
|
||||
import {
|
||||
applyGiftPriceDefaults,
|
||||
applyGiftResourceSelection,
|
||||
cpRelationTypeFromGift,
|
||||
cpRelationTypeFromPresentationJson,
|
||||
cpRelationTypeShortLabel,
|
||||
fetchAllOptionPages,
|
||||
normalizeGiftPresentationJson,
|
||||
} from "./useResourcePages.js";
|
||||
@ -69,24 +67,6 @@ test("reads CP relation type from gift presentation json", () => {
|
||||
expect(cpRelationTypeFromPresentationJson('{"cp_relation_type":"unknown"}')).toBe("");
|
||||
});
|
||||
|
||||
test("prefers explicit CP relation type and formats compact list label", () => {
|
||||
expect(
|
||||
cpRelationTypeFromGift({
|
||||
cpRelationType: "brother",
|
||||
giftTypeCode: "cp",
|
||||
presentationJson: '{"cp_relation_type":"sister"}',
|
||||
}),
|
||||
).toBe("brother");
|
||||
expect(
|
||||
cpRelationTypeFromGift({
|
||||
giftTypeCode: "cp",
|
||||
presentationJson: '{"cp_relation_type":"sister"}',
|
||||
}),
|
||||
).toBe("sister");
|
||||
expect(cpRelationTypeShortLabel("brother")).toBe("兄弟");
|
||||
expect(cpRelationTypeShortLabel("cp")).toBe("CP");
|
||||
});
|
||||
|
||||
test("normalizes CP gift presentation json for submit", () => {
|
||||
const nextJson = normalizeGiftPresentationJson(
|
||||
'{"other":1,"cp_relation_type":"brother","cpRelationLabel":"old"}',
|
||||
|
||||
@ -34,17 +34,14 @@ import { createRegionColumnFilter } from "@/shared/ui/RegionFilterControl.jsx";
|
||||
import { createOptionsColumnFilter, createTextColumnFilter } from "@/shared/ui/tableFilters.js";
|
||||
import { formatMillis } from "@/shared/utils/time.js";
|
||||
import {
|
||||
cpRelationTypeLabels,
|
||||
cpRelationTypeOptions,
|
||||
defaultGiftTypeOptions,
|
||||
resourceStatusFilters,
|
||||
} from "@/features/resources/constants.js";
|
||||
import { GiftTypeConfigDialog } from "@/features/resources/components/GiftTypeConfigDialog.jsx";
|
||||
import { ResourceSelectField } from "@/features/resources/components/ResourceSelectDrawer.jsx";
|
||||
import {
|
||||
cpRelationTypeFromGift,
|
||||
cpRelationTypeShortLabel,
|
||||
useGiftListPage,
|
||||
} from "@/features/resources/hooks/useResourcePages.js";
|
||||
import { cpRelationTypeFromPresentationJson, useGiftListPage } from "@/features/resources/hooks/useResourcePages.js";
|
||||
import styles from "@/features/resources/resources.module.css";
|
||||
|
||||
const effectOptions = [
|
||||
@ -670,10 +667,13 @@ function giftTypeLabel(value, options = defaultGiftTypeOptions) {
|
||||
}
|
||||
|
||||
function GiftTypeIdentity({ gift, giftTypeOptions }) {
|
||||
const typeLabel = giftTypeLabel(gift.giftTypeCode, giftTypeOptions);
|
||||
const relationType = gift.giftTypeCode === "cp" ? cpRelationTypeFromGift(gift) || "cp" : "";
|
||||
const relationLabel = relationType ? cpRelationTypeShortLabel(relationType) : "";
|
||||
return <span>{relationLabel ? `${typeLabel}(${relationLabel})` : typeLabel}</span>;
|
||||
const relationType = gift.giftTypeCode === "cp" ? cpRelationTypeFromPresentationJson(gift.presentationJson) : "";
|
||||
return (
|
||||
<div className={styles.stack}>
|
||||
<span>{giftTypeLabel(gift.giftTypeCode, giftTypeOptions)}</span>
|
||||
{relationType ? <span className="admin-tag">{cpRelationTypeLabels[relationType] || relationType}</span> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function giftPriceLabel(gift) {
|
||||
|
||||
@ -92,11 +92,6 @@ const baseColumns = [
|
||||
label: "状态",
|
||||
width: "minmax(92px, 0.55fr)",
|
||||
},
|
||||
{
|
||||
key: "managerGrant",
|
||||
label: "经理赠送",
|
||||
width: "minmax(112px, 0.6fr)",
|
||||
},
|
||||
{
|
||||
key: "time",
|
||||
label: "更新时间",
|
||||
@ -151,11 +146,6 @@ export function ResourceListPage() {
|
||||
}),
|
||||
render: (resource) => <ResourceStatusSwitch page={page} resource={resource} />,
|
||||
}
|
||||
: column.key === "managerGrant"
|
||||
? {
|
||||
...column,
|
||||
render: (resource) => <ManagerGrantSwitch page={page} resource={resource} />,
|
||||
}
|
||||
: column.key === "actions"
|
||||
? {
|
||||
...column,
|
||||
@ -291,7 +281,7 @@ export function ResourceListPage() {
|
||||
<DataTable
|
||||
columns={columns}
|
||||
items={items}
|
||||
minWidth="1060px"
|
||||
minWidth="940px"
|
||||
pagination={
|
||||
total > 0
|
||||
? {
|
||||
@ -666,14 +656,6 @@ function ResourceFormDialog({ disabled, form, loading, mode, onClose, onSubmit,
|
||||
uncheckedLabel="禁用"
|
||||
onChange={(checked) => setForm({ ...form, enabled: checked })}
|
||||
/>
|
||||
<AdminFormSwitchField
|
||||
checked={Boolean(form.managerGrantEnabled)}
|
||||
checkedLabel="开启"
|
||||
disabled={disabled}
|
||||
label="经理赠送"
|
||||
uncheckedLabel="关闭"
|
||||
onChange={(checked) => setForm({ ...form, managerGrantEnabled: checked })}
|
||||
/>
|
||||
</AdminFormSection>
|
||||
</AdminFormDialog>
|
||||
);
|
||||
@ -706,20 +688,6 @@ function ResourceStatusSwitch({ page, resource }) {
|
||||
);
|
||||
}
|
||||
|
||||
function ManagerGrantSwitch({ page, resource }) {
|
||||
const checked = Boolean(resource.managerGrantEnabled);
|
||||
return (
|
||||
<AdminSwitch
|
||||
checked={checked}
|
||||
checkedLabel="开启"
|
||||
disabled={!page.abilities.canUpdate || page.loadingAction === `resource-manager-grant-${resource.resourceId}`}
|
||||
inputProps={{ "aria-label": checked ? "关闭经理赠送" : "开启经理赠送" }}
|
||||
uncheckedLabel="关闭"
|
||||
onChange={(event) => page.toggleManagerGrant(resource, event.target.checked)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function resourcePriceLabel(resource) {
|
||||
if (resource.priceType === "free") {
|
||||
return resourcePriceTypeLabels.free;
|
||||
|
||||
@ -38,7 +38,6 @@ export const resourceCreateFormSchema = z
|
||||
badgeKind: z.enum(badgeKinds).optional(),
|
||||
enabled: z.boolean(),
|
||||
levelTrack: z.enum(badgeLevelTracks).optional().or(z.literal("")),
|
||||
managerGrantEnabled: z.boolean(),
|
||||
metadataJson: z.string().trim().max(4096, "资源元数据不能超过 4096 个字符").optional(),
|
||||
name: z.string().trim().min(1, "请输入资源名称").max(128, "资源名称不能超过 128 个字符"),
|
||||
coinPrice: z.union([z.string(), z.number()]).optional(),
|
||||
|
||||
@ -15,7 +15,6 @@ describe("resource form schema", () => {
|
||||
animationUrl: "https://media.haiyihy.com/resource/profile-card.pag",
|
||||
badgeForm: "tile",
|
||||
enabled: true,
|
||||
managerGrantEnabled: true,
|
||||
metadataJson:
|
||||
'{"profile_card_layout":{"source_width":1136,"source_height":1680,"color_content_width":750,"content_top":117,"content_bottom":1666,"content_height":1550,"content_top_ratio":0.069643,"content_height_ratio":0.922619,"detect_version":1}}',
|
||||
name: "Profile Card",
|
||||
@ -37,7 +36,6 @@ describe("resource form schema", () => {
|
||||
badgeKind: "level",
|
||||
enabled: true,
|
||||
levelTrack: "wealth",
|
||||
managerGrantEnabled: true,
|
||||
name: "VIP Badge",
|
||||
previewUrl: "https://media.haiyihy.com/resource/badge.png",
|
||||
priceType: "free",
|
||||
@ -53,7 +51,6 @@ describe("resource form schema", () => {
|
||||
parseForm(resourceFormSchema, {
|
||||
animationUrl: "https://media.haiyihy.com/resource/badge.pag",
|
||||
enabled: true,
|
||||
managerGrantEnabled: true,
|
||||
name: "VIP Badge",
|
||||
previewUrl: "https://media.haiyihy.com/resource/badge.png",
|
||||
priceType: "free",
|
||||
@ -68,7 +65,6 @@ describe("resource form schema", () => {
|
||||
badgeForm: "strip",
|
||||
badgeKind: "level",
|
||||
enabled: true,
|
||||
managerGrantEnabled: true,
|
||||
name: "VIP Badge",
|
||||
previewUrl: "https://media.haiyihy.com/resource/badge.png",
|
||||
priceType: "free",
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user