fix(table): 统一筛选交互并补齐移动视口覆盖

This commit is contained in:
zhanjunhao
2026-11-24 20:14:10 +08:00
parent 437a0345e8
commit dd4da99f1d
83 changed files with 2094 additions and 1355 deletions
+1 -1
View File
@@ -172,7 +172,7 @@ node --env-file=.env.playwright.local e2e/auth-login/run.mjs
测试先通过项目目录、启动日志与监听进程查找并验证已有开发服务;历史日志中的失效地址不能作为新启服务的依据。仅确认本项目服务不存在时才启动,结束时只清理本次启动的进程。项目 Playwright 配置和专项验收通过 `scripts/dev-service.mjs` 自动发现并复用服务(验证 Vite 源码映射属于当前项目,兼容 UTF-8 / UTF-16LE 日志);显式目标仍按调用方配置执行。本地登录脚本同样先发现已有服务,使用本机 Chrome 离屏串行执行企业 A/B 状态判定、真实 UI 登录、后台主体断言、个人端全新 Context 登录和 UI 退出。企业 A 路径先填写企业名称并点击“下一步”,B 路径直接填写登录名和密码;不可覆盖的路径单独记录。后续搜索按钮验收拦截非 GET 写请求;截图、脱敏失败记录与供后续用例复用的 storageState 保存在 `report/auth-login-<时间>/`,均为本地忽略产物。storageState 含会话凭据,不上传、不提交;登录规则见 `docs/ui/GLOBAL_UI_BASELINE.md` 第 6 节。 测试先通过项目目录、启动日志与监听进程查找并验证已有开发服务;历史日志中的失效地址不能作为新启服务的依据。仅确认本项目服务不存在时才启动,结束时只清理本次启动的进程。项目 Playwright 配置和专项验收通过 `scripts/dev-service.mjs` 自动发现并复用服务(验证 Vite 源码映射属于当前项目,兼容 UTF-8 / UTF-16LE 日志);显式目标仍按调用方配置执行。本地登录脚本同样先发现已有服务,使用本机 Chrome 离屏串行执行企业 A/B 状态判定、真实 UI 登录、后台主体断言、个人端全新 Context 登录和 UI 退出。企业 A 路径先填写企业名称并点击“下一步”,B 路径直接填写登录名和密码;不可覆盖的路径单独记录。后续搜索按钮验收拦截非 GET 写请求;截图、脱敏失败记录与供后续用例复用的 storageState 保存在 `report/auth-login-<时间>/`,均为本地忽略产物。storageState 含会话凭据,不上传、不提交;登录规则见 `docs/ui/GLOBAL_UI_BASELINE.md` 第 6 节。
Playwright 与 weelink 共用设备环境约定,依赖精确锁定 1.64.1;本项目 runner 优先复用已核验的现有开发服务,仅确认不存在时才使用 4176,避免与 weelink 的 4175 冲突。配置读取 `scripts/ui-review/config.json`,用例通过 `scripts/playwright-test.mjs` 的公共 fixture 后台建页并守护焦点。独立脚本使用 `scripts/playwright-focus-guard.mjs` 的 `launchFocusSafe()`,两类流程保留各自执行策略。前台激活或探测失败会记录并停止,离屏不保证绝无瞬时激活。环境变量和截图口径见 [全局基线第 7.1 节](docs/ui/GLOBAL_UI_BASELINE.md#71-工具)。 Playwright 默认运行桌面及两个移动项目:`chrome-mobile`(最小视口 360×800)与 `chrome-mobile-393`(393×851)。通用用例继承项目视口,专项用例可覆盖视口测试指定场景。Playwright 与 weelink 共用设备环境约定,依赖精确锁定 1.64.1;本项目 runner 优先复用已核验的现有开发服务,仅确认不存在时才使用 4176,避免与 weelink 的 4175 冲突。配置读取 `scripts/ui-review/config.json`,用例通过 `scripts/playwright-test.mjs` 的公共 fixture 后台建页并守护焦点。独立脚本使用 `scripts/playwright-focus-guard.mjs` 的 `launchFocusSafe()`,两类流程保留各自执行策略。前台激活或探测失败会记录并停止,离屏不保证绝无瞬时激活。环境变量和截图口径见 [全局基线第 7.1 节](docs/ui/GLOBAL_UI_BASELINE.md#71-工具)。
| 命令 / 参数 | 用途与默认值 | | 命令 / 参数 | 用途与默认值 |
| --- | --- | | --- | --- |
+16
View File
@@ -10,6 +10,22 @@
## 2026-11-24 ## 2026-11-24
### 调整 · Playwright 默认覆盖两档移动视口
- **范围**:项目 Playwright 配置与设备环境校验。
- **变更**:显式保留 `chrome-mobile` 的 360×800,新增默认项目 `chrome-mobile-393` 覆盖 393×851。
- **影响**:继承项目视口的用例默认在两档手机尺寸运行,设备环境检查校验实际尺寸、触摸和截图。
- **回滚**:从默认项目与设备配置移除 393×851 项目,并恢复对应断言。
- **关联**:`playwright.config.js`、`scripts/browser-environment.mjs`、`scripts/ui-review/config.json`。
### 调整 · 表格日期范围与自动搜索
- **范围**:控制台、企业中心、用户中心的表格筛选区。
- **变更**:日期范围共用快捷周期、格式和确认交互。接入公共 300ms 搜索调度,可取消过期查询。个人密钥的本地过滤按批处理。
- **影响**:搜索保留当前页与表格操作状态,重置恢复各页面默认条件及初始页。
- **回滚**:按受影响页面恢复筛选事件和列表请求,并还原表格日期和搜索公共入口。
- **关联**:`docs/standards/UI_COMPONENT_STANDARDS.md` 第 4、6 节,`src/hooks/common/useFilterSearch.js`。
### 调整 · 企业技能中心布局 ### 调整 · 企业技能中心布局
- **范围**:企业中心技能库与自研 Skill。 - **范围**:企业中心技能库与自研 Skill。
+12 -3
View File
@@ -130,13 +130,21 @@ html.dark .km-page {
- 字段竖排:标签在上(13px,次文字色,下距 8px),控件在下且宽度占满单元格。 - 字段竖排:标签在上(13px,次文字色,下距 8px),控件在下且宽度占满单元格。
- 栅格:列间距与行间距 16px;按页面宽度取 3–5 列(企业中心 3 列、控制台 4 列、用户中心 5 列,时间范围可跨 2 列);≤ 768px 单列。 - 栅格:列间距与行间距 16px;按页面宽度取 3–5 列(企业中心 3 列、控制台 4 列、用户中心 5 列,时间范围可跨 2 列);≤ 768px 单列。
- 操作:“重置”“搜索”位于右下,间距 8px;“搜索”为 primary 且 `htmlType='submit'`,回车提交。 - 操作:“重置”“搜索”位于右下,间距 8px;“搜索”为 primary 且 `htmlType='submit'`,回车提交。
- 行为:搜索与重置都回到第 1 页;重置 = 清空表单 + 以默认条件重新查询;只切换筛选的页签放在筛选卡上方。 - 搜索保留当前页码、每页条数、排序、勾选和展开等表格操作状态。点击“重置”时取消待执行搜索及在途筛选请求,恢复本页的默认筛选条件,回到第 1 页并初始化本页的表格操作状态。只切换筛选的页签放在筛选卡上方。
- 移动端:用户中心与控制台默认收起,通过“显示 / 隐藏操作项”或“筛选”按钮展开;列设置入口不随筛选收起。 - 移动端:用户中心与控制台默认收起,通过“显示 / 隐藏操作项”或“筛选”按钮展开;列设置入口不随筛选收起。
- 控制台使用 `ConsoleSearchBar` + `ConsoleSearchActions`,企业中心常规筛选使用 `OrgFilterCard`。消耗明细及提示词记录复用个人消费记录的筛选布局和移动端折叠。 - 控制台使用 `ConsoleSearchBar` + `ConsoleSearchActions`,企业中心常规筛选使用 `OrgFilterCard`。消耗明细及提示词记录复用个人消费记录的筛选布局和移动端折叠。
- 标准列表以 `/console/token` 为参考,覆盖控制台分佣、兑换码、会员卡和发票,企业及个人分佣,以及用户中心密钥管理(含各自子页、页签和详情列表)。使用 `ConsoleCollection`(或通过 `CardPro` 接入);独立列表可用 `ConsoleCollectionSearch` + `ConsoleFilterGrid`。筛选栅格为三列、≤ 1100px 两列、≤ 768px 单列。 - 标准列表以 `/console/token` 为参考,覆盖控制台分佣、兑换码、会员卡和发票,企业及个人分佣,以及用户中心密钥管理(含各自子页、页签和详情列表)。使用 `ConsoleCollection`(或通过 `CardPro` 接入);独立列表可用 `ConsoleCollectionSearch` + `ConsoleFilterGrid`。筛选栅格为三列、≤ 1100px 两列、≤ 768px 单列。
- 搜索操作在筛选卡右下,先默认样式“重置”(无图标),再带放大镜的主按钮“搜索”;点击和回车共用同一个提交入口。保留原有即时筛选及请求方式,移动端统一通过“显示/隐藏操作项”切换。 - 搜索操作在筛选卡右下,先默认样式“重置”(无图标),再带放大镜的主按钮“搜索”;点击和回车共用同一个提交入口。移动端统一通过“显示/隐藏操作项”切换。
- 工具栏在列表卡内、表格上方:列表标题、计数或快捷筛选在左;已有的批量、导出、刷新、列设置、新建等动作在右,主操作尽量靠右,使用公共操作图标和清晰文案。窗口变窄时自然换行。只读明细若没有筛选或业务动作,不新增占位按钮。 - 工具栏在列表卡内、表格上方:列表标题、计数或快捷筛选在左;已有的批量、导出、刷新、列设置、新建等动作在右,主操作尽量靠右,使用公共操作图标和清晰文案。窗口变窄时自然换行。只读明细若没有筛选或业务动作,不新增占位按钮。
### 4.1 时间范围及自动搜索
- 表格筛选的范围控件使用 `DatePicker` 或 `Form.DatePicker` 的 `tableFilter`,开始和结束输入框共用一个控件,支持清除。仅日期使用 `YYYY-MM-DD`,含时间使用 `YYYY-MM-DD HH:mm:ss`。日期弹层使用当前主题;桌面快捷周期位于日历左侧,窄屏可换行。
- 快捷周期依次为今天、近 7 天、本周、近 30 天、本月,复用 `DATE_RANGE_PRESETS`。相对周期按选择时的本地日期计算,匹配已提交范围时显示选中态。页面沿用自身初始日期或空值。选择完整范围、确认时间、选择快捷周期或清除后,通过同一个值变更入口提交;临时选择、悬浮预览和下拉搜索词不触发列表查询。
- `useFilterSearch` 将字段变更合并为一次 300ms 防抖查询。兼容表单用 `onValueChange={scheduleSearch}`,原生 Ant Design Form 用 `onValuesChange` 传最终值;独立受控字段可用 `changeFilter(setValue)`。输入框、数字组件、选择器、开关、复选和异步选择组件均在实际筛选值变化时接入。搜索按钮和回车共用 `submitSearch`,立即执行待查询条件。
- 后端分页沿用现有查询接口,传当前页及条件,同时将 `AbortSignal` 传到 `API`。字段变化、重置和卸载取消在途查询,忽略过期响应。以页码或已应用条件驱动请求的页面可用 `useTableFilterQuery` 将取消操作传给 `useFilterSearch`。
- 本地分页先按条件处理完整数据集再切页。独立控件可用 `useLocalTableFilters` 分开显示值与已应用值,再用 `useFilteredTableRows` 计算结果。大数组过滤复用 `filterTableRows`,超出 500 行时分片让出主线程,并在每批检查取消状态。
## 5. 表格 ## 5. 表格
### 5.1 表头与行 ### 5.1 表头与行
@@ -174,8 +182,9 @@ html.dark .km-page {
- 位置:列表卡底部右对齐,上距 16px;移动端换行显示并提供快速跳页。 - 位置:列表卡底部右对齐,上距 16px;移动端换行显示并提供快速跳页。
- 外观:小尺寸,可切换每页条数 `[10, 20, 50, 100]`,总数文案 `t('共 {{total}} 条', { total })`。 - 外观:小尺寸,可切换每页条数 `[10, 20, 50, 100]`,总数文案 `t('共 {{total}} 条', { total })`。
- 用法:分页列表使用 `@/components/ui` 的 `Table` / `Pagination`。第 4 节的标准列表及其明细分页均沿用密钥管理:表格底部右对齐、小尺寸,依次显示“共 N 条”、上一页/页码/下一页、每页条数(10、20、50、100),移动端保留跳页。已加载的明细可本地分页;服务端分页传 `currentPage`、`pageSize`、`total` 以及分页回调,切换每页条数回到第 1 页,只发一次请求。导出仍作用于原有结果范围,不受当前页条数影响。 - 用法:分页列表使用 `@/components/ui` 的 `Table` / `Pagination`。第 4 节的标准列表及其明细分页均沿用密钥管理:表格底部右对齐、小尺寸,依次显示“共 N 条”、上一页/页码/下一页、每页条数(10、20、50、100),移动端保留跳页。已加载的明细可本地分页;服务端分页传 `currentPage`、`pageSize`、`total` 以及分页回调,切换每页条数回到第 1 页,只发一次请求。导出仍作用于原有结果范围,不受当前页条数影响。
- 删除当前页最后一条后回到上一页;前端分页的列表在筛选或数据变化时回到第 1 页。`/org/*` 的独立表格、页签和下钻明细均用此分页规则;已加载的树形表格按根节点分页,子节点不拆散;接口已分页时沿用原查询与总数。 - 删除当前页最后一条后回到上一页;筛选和搜索沿用当前页,重置回到第 1 页。`/org/*` 的独立表格、页签和下钻明细均用此分页规则;已加载的树形表格按根节点分页,子节点不拆散;接口已分页时沿用原查询与总数。
- 受控分页须实现条数回调(或兼容的统一变更回调)才显示条数选择,不用客户端切片模拟固定条数的服务端接口;分页启用且有结果时单页也显示分页栏。 - 受控分页须实现条数回调(或兼容的统一变更回调)才显示条数选择,不用客户端切片模拟固定条数的服务端接口;分页启用且有结果时单页也显示分页栏。
- 接入自动搜索的表格使用 `preservePage`。筛选后当前页没有结果时仍保留页码,分页栏显示实际结果总数并允许手动返回。删除后的页码调整由对应删除流程处理。
## 7. 表单项 ## 7. 表单项
+2 -2
View File
@@ -151,8 +151,8 @@
| 配置 | 约定 | | 配置 | 约定 |
| --- | --- | | --- | --- |
| 设备源 | `scripts/ui-review/config.json` → `scripts/browser-environment.mjs`;与 weelink 的设备结构和 Playwright 1.64.1 保持一致,各项目独立保存 | | 设备源 | `scripts/ui-review/config.json` → `scripts/browser-environment.mjs`;与 weelink 的设备结构和 Playwright 1.64.1 保持一致,各项目独立保存 |
| 视口 | 默认 1920×1080、360×800;扩展增加 768×1024、1024×768、1366×768、1440×900、2560×1440、3840×2160 | | 视口 | 默认 1920×1080、360×800、393×851;扩展增加 768×1024、1024×768、1366×768、1440×900、2560×1440、3840×2160 |
| 手机 | Pixel 5 UA、触摸、移动模式和 DPR 2.75;viewport 覆盖为 360×800,screen 沿用模板;平板仅为桌面设备的平板尺寸 | | 手机 | Pixel 5 UA、触摸、移动模式和 DPR 2.75;默认项目覆盖 360×800(`chrome-mobile`)和 393×851(`chrome-mobile-393`),screen 沿用模板;平板仅为桌面设备的平板尺寸 |
| 本地目标 | 未指定目标时自动发现并复用已有开发服务,确认不存在后才启动 `http://127.0.0.1:4176/`;开发和预览均严格占用指定端口,禁止静默回退 | | 本地目标 | 未指定目标时自动发现并复用已有开发服务,确认不存在后才启动 `http://127.0.0.1:4176/`;开发和预览均严格占用指定端口,禁止静默回退 |
| 目标切换 | `local-dist` 先校验静态入口与引用资源,再启动 Vite preview;`remote` 必须提供 `PW_BASE_URL`,不启动服务 | | 目标切换 | `local-dist` 先校验静态入口与引用资源,再启动 Vite preview;`remote` 必须提供 `PW_BASE_URL`,不启动服务 |
| 窗口 | 本地默认有头离屏;`PW_HEADLESS=1` 无头,CI 强制无头;隐藏滚动条并禁用后台降频 | | 窗口 | 本地默认有头离屏;`PW_HEADLESS=1` 无头,CI 强制无头;隐藏滚动条并禁用后台降频 |
+2 -3
View File
@@ -2,6 +2,7 @@ import { defineConfig } from '@playwright/test';
import { import {
browserChannel, browserChannel,
contextOptions, contextOptions,
defaultProjectViewports,
projectViewports, projectViewports,
} from './scripts/browser-environment.mjs'; } from './scripts/browser-environment.mjs';
import { runtimeOptions } from './scripts/playwright-runtime.mjs'; import { runtimeOptions } from './scripts/playwright-runtime.mjs';
@@ -29,9 +30,7 @@ if (
) )
) )
throw new Error('CI requires headless non-interactive tests'); throw new Error('CI requires headless non-interactive tests');
const viewports = runtime.extended const viewports = runtime.extended ? projectViewports : defaultProjectViewports;
? projectViewports
: projectViewports.slice(0, 2);
// UI_VISUAL_OFFSCREEN=0 仅限人工本地可视化调试时临时使用。 // UI_VISUAL_OFFSCREEN=0 仅限人工本地可视化调试时临时使用。
// Agent、CI、无头/自动化环境禁止设置该值,必须保持默认离屏模式 // Agent、CI、无头/自动化环境禁止设置该值,必须保持默认离屏模式
+5 -3
View File
@@ -13,9 +13,9 @@ const aliases = {
'laptop-wxga': 'wxga', 'laptop-wxga': 'wxga',
}; };
export const browserChannel = config.browser.channel; export const browserChannel = config.browser.channel;
export const defaultProjectViewports = ['desktop', 'mobile', 'mobile-393'];
export const projectViewports = [ export const projectViewports = [
'desktop', ...defaultProjectViewports,
'mobile',
'tablet', 'tablet',
'desktop-boundary', 'desktop-boundary',
'laptop-hd', 'laptop-hd',
@@ -30,7 +30,9 @@ export function deviceOptions(name) {
if (!size) throw new Error(`Unknown viewport: ${name}`); if (!size) throw new Error(`Unknown viewport: ${name}`);
const descriptor = const descriptor =
devices[ devices[
config.browser[key === 'mobile' ? 'mobileDevice' : 'desktopDevice'] config.browser[
key.startsWith('mobile') ? 'mobileDevice' : 'desktopDevice'
]
]; ];
if (!descriptor) throw new Error(`Unknown device profile for ${name}`); if (!descriptor) throw new Error(`Unknown device profile for ${name}`);
const { defaultBrowserType, ...context } = descriptor; const { defaultBrowserType, ...context } = descriptor;
+1
View File
@@ -9,6 +9,7 @@
"viewports": { "viewports": {
"desktop": [1920, 1080], "desktop": [1920, 1080],
"mobile": [360, 800], "mobile": [360, 800],
"mobile-393": [393, 851],
"tablet": [768, 1024], "tablet": [768, 1024],
"laptop": [1024, 768], "laptop": [1024, 768],
"hd": [1366, 768], "hd": [1366, 768],
@@ -180,6 +180,7 @@ const DailyStatsTable = ({ data, title, icon, t, embedded = false }) => {
columns={columns} columns={columns}
dataSource={data || []} dataSource={data || []}
pagination={{ pagination={{
preservePage: true,
pageSize: 10, pageSize: 10,
showSizeChanger: true, showSizeChanger: true,
showTotal: (total) => t('共 {{total}} 条', { total, count: total }), showTotal: (total) => t('共 {{total}} 条', { total, count: total }),
@@ -0,0 +1,15 @@
const CHUNK_SIZE = 500;
export async function filterTableRows(items, matches, signal) {
const result = [];
for (let start = 0; start < items.length; start += CHUNK_SIZE) {
if (start > 0) await new Promise((resolve) => setTimeout(resolve, 0));
signal?.throwIfAborted();
const end = Math.min(items.length, start + CHUNK_SIZE);
for (let index = start; index < end; index++) {
if (matches(items[index])) result.push(items[index]);
}
}
signal?.throwIfAborted();
return result;
}
@@ -0,0 +1,79 @@
.table-filter-range {
min-width: 0;
}
.table-filter-range-popup .ant-picker-panel-container .ant-picker-presets {
min-width: 118px;
}
.table-filter-range-popup .table-filter-period-active {
color: var(--ant-color-primary, var(--brand-primary));
font-weight: 600;
}
@media (hover: none) and (pointer: coarse) {
.table-filter-range.ant-picker .ant-picker-clear {
opacity: 1;
pointer-events: auto;
}
.table-filter-range.ant-picker .ant-picker-suffix:not(:last-child) {
opacity: 0;
}
}
@media (max-width: 640px) {
.table-filter-range-popup
.ant-picker-panel-container
.ant-picker-panel-layout {
flex-direction: column;
max-width: calc(100vw - 16px);
}
.table-filter-range-popup .ant-picker-panel-container .ant-picker-presets {
max-width: none;
}
.table-filter-range-popup .ant-picker-panel-container .ant-picker-presets ul {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 4px;
height: auto;
border-inline-end: 0;
border-block-end: 1px solid var(--ant-color-split, var(--ui-color-border));
}
.table-filter-range-popup .ant-picker-panel-container .ant-picker-presets li {
margin-block: 0;
}
.table-filter-range-popup .ant-picker-panel-container .ant-picker-panels {
display: flex;
max-width: calc(100vw - 16px);
overflow-x: auto;
}
.table-filter-range-popup .ant-picker-datetime-panel .ant-picker-date-panel {
width: min(64vw, 272px);
min-width: 0;
}
.table-filter-range-popup .ant-picker-datetime-panel .ant-picker-content th,
.table-filter-range-popup .ant-picker-datetime-panel .ant-picker-content td {
width: auto;
}
.table-filter-range-popup
.ant-picker-datetime-panel
.ant-picker-time-panel-column {
width: min(10vw, 48px);
}
.table-filter-range-popup
.ant-picker-datetime-panel
.ant-picker-time-panel-cell-inner {
width: auto;
padding-inline: 4px;
}
}
@@ -254,6 +254,7 @@ const QualityFilterBar = ({ quality, t, onOpenDetail }) => {
</Radio.Group> </Radio.Group>
{filters.range === 'custom' && ( {filters.range === 'custom' && (
<DatePicker <DatePicker
tableFilter
type='dateTimeRange' type='dateTimeRange'
value={customRange} value={customRange}
style={{ maxWidth: 380, width: '100%' }} style={{ maxWidth: 380, width: '100%' }}
@@ -7,7 +7,8 @@ import { useFilterSearch } from '../../../hooks/common/useFilterSearch';
const AdminTokensFilters = ({ const AdminTokensFilters = ({
formInitValues, formInitValues,
setFormApi, setFormApi,
searchTokens, activePage,
setSelectedRowKeys,
loadTokens, loadTokens,
pageSize, pageSize,
groupOptions, groupOptions,
@@ -17,7 +18,7 @@ const AdminTokensFilters = ({
}) => { }) => {
const formApiRef = useRef(null); const formApiRef = useRef(null);
const { scheduleSearch, submitSearch, cancelPendingSearch } = useFilterSearch( const { scheduleSearch, submitSearch, cancelPendingSearch } = useFilterSearch(
() => searchTokens(pageSize), (_, signal) => loadTokens(activePage, pageSize, null, signal),
); );
const handleReset = () => { const handleReset = () => {
@@ -25,6 +26,7 @@ const AdminTokensFilters = ({
formApiRef.current.reset(); formApiRef.current.reset();
cancelPendingSearch(); cancelPendingSearch();
// 重置后立即用初始值刷新(不走 debounce) // 重置后立即用初始值刷新(不走 debounce)
setSelectedRowKeys([]);
loadTokens(1, pageSize, formInitValues); loadTokens(1, pageSize, formInitValues);
}; };
+3 -4
View File
@@ -52,8 +52,6 @@ const AdminTokensPage = () => {
setFormApi, setFormApi,
loadTokens, loadTokens,
searchTokens,
debouncedSearch,
refresh, refresh,
manageToken, manageToken,
batchManageTokens, batchManageTokens,
@@ -132,8 +130,8 @@ const AdminTokensPage = () => {
<AdminTokensFilters <AdminTokensFilters
formInitValues={formInitValues} formInitValues={formInitValues}
setFormApi={setFormApi} setFormApi={setFormApi}
searchTokens={searchTokens} activePage={activePage}
debouncedSearch={debouncedSearch} setSelectedRowKeys={setSelectedRowKeys}
loadTokens={loadTokens} loadTokens={loadTokens}
pageSize={pageSize} pageSize={pageSize}
groupOptions={groupOptions} groupOptions={groupOptions}
@@ -155,6 +153,7 @@ const AdminTokensPage = () => {
</div> </div>
} }
paginationArea={createCardProPagination({ paginationArea={createCardProPagination({
preservePage: true,
showRange: false, showRange: false,
currentPage: activePage, currentPage: activePage,
pageSize: pageSize, pageSize: pageSize,
@@ -8,6 +8,9 @@ const ChannelsFilters = ({
formInitValues, formInitValues,
setFormApi, setFormApi,
searchChannels, searchChannels,
activePage,
setActivePage,
setSelectedChannels,
enableTagMode, enableTagMode,
formApi, formApi,
groupOptions, groupOptions,
@@ -20,7 +23,16 @@ const ChannelsFilters = ({
t, t,
}) => { }) => {
const { scheduleSearch, submitSearch, cancelPendingSearch } = useFilterSearch( const { scheduleSearch, submitSearch, cancelPendingSearch } = useFilterSearch(
() => searchChannels(enableTagMode), (_, signal) =>
searchChannels(
enableTagMode,
undefined,
undefined,
activePage,
undefined,
undefined,
signal,
),
); );
return ( return (
<div className='w-full'> <div className='w-full'>
@@ -124,10 +136,9 @@ const ChannelsFilters = ({
setAutoBanExclusionFilter('all'); setAutoBanExclusionFilter('all');
localStorage.setItem('channel-status-filter', 'all'); localStorage.setItem('channel-status-filter', 'all');
localStorage.setItem('channel-autoban-exclusion-filter', 'all'); localStorage.setItem('channel-autoban-exclusion-filter', 'all');
// 重置后立即查询,使用setTimeout确保表单重置完成 setSelectedChannels([]);
setTimeout(() => { setActivePage(1);
searchChannels(enableTagMode, undefined, 'all'); searchChannels(enableTagMode, undefined, 'all').catch(() => {});
}, 100);
} }
}} }}
/> />
+1
View File
@@ -59,6 +59,7 @@ const ChannelsPage = () => {
/> />
} }
paginationArea={createCardProPagination({ paginationArea={createCardProPagination({
preservePage: true,
showRange: false, showRange: false,
currentPage: channelsData.activePage, currentPage: channelsData.activePage,
pageSize: channelsData.pageSize, pageSize: channelsData.pageSize,
@@ -1,4 +1,7 @@
import React, { useState } from 'react'; import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { useEffectEvent } from '@/hooks/common/useEffectEvent';
import { useLocalTableFilters } from '@/hooks/common/useLocalTableFilters';
import { useFilteredTableRows } from '@/hooks/common/useFilteredTableRows';
import { Table } from '@/components/ui'; import { Table } from '@/components/ui';
import { Modal, Button, Input, Tag, Typography, Select } from 'antd'; import { Modal, Button, Input, Tag, Typography, Select } from 'antd';
import { Search } from 'lucide-react'; import { Search } from 'lucide-react';
@@ -17,8 +20,6 @@ const ModelTestModal = ({
handleCloseModal, handleCloseModal,
isBatchTesting, isBatchTesting,
batchTestModels, batchTestModels,
modelSearchKeyword,
setModelSearchKeyword,
selectedModelKeys, selectedModelKeys,
setSelectedModelKeys, setSelectedModelKeys,
modelTestResults, modelTestResults,
@@ -33,14 +34,24 @@ const ModelTestModal = ({
}) => { }) => {
const [paginationSize, setPaginationSize] = useState(MODEL_TABLE_PAGE_SIZE); const [paginationSize, setPaginationSize] = useState(MODEL_TABLE_PAGE_SIZE);
const hasChannel = Boolean(currentTestChannel); const hasChannel = Boolean(currentTestChannel);
const models = const modelList = currentTestChannel?.models;
typeof currentTestChannel?.models === 'string' const models = useMemo(
? currentTestChannel.models.split(',').filter(Boolean) () =>
: []; typeof modelList === 'string' ? modelList.split(',').filter(Boolean) : [],
[modelList],
const filteredModels = models.filter((model) =>
model.toLowerCase().includes(modelSearchKeyword.toLowerCase()),
); );
const { draft, applied, changeFilters, submitSearch, resetFilters } =
useLocalTableFilters({ keyword: '' });
const resetOnClose = useEffectEvent(() => {
if (!showModelTestModal) resetFilters();
});
useEffect(() => resetOnClose(), [showModelTestModal, resetOnClose]);
const keyword = applied.keyword.toLowerCase();
const matches = useCallback(
(model) => model.toLowerCase().includes(keyword),
[keyword],
);
const filteredModels = useFilteredTableRows(models, matches);
const endpointTypeOptions = [ const endpointTypeOptions = [
{ value: '', label: t('自动检测') }, { value: '', label: t('自动检测') },
@@ -80,12 +91,10 @@ const ModelTestModal = ({
const handleSelectSuccess = () => { const handleSelectSuccess = () => {
if (!currentTestChannel) return; if (!currentTestChannel) return;
const successKeys = models const successKeys = filteredModels.filter((m) => {
.filter((m) => m.toLowerCase().includes(modelSearchKeyword.toLowerCase())) const result = modelTestResults[`${currentTestChannel.id}-${m}`];
.filter((m) => { return result && result.success;
const result = modelTestResults[`${currentTestChannel.id}-${m}`]; });
return result && result.success;
});
if (successKeys.length === 0) { if (successKeys.length === 0) {
showInfo(t('暂无成功模型')); showInfo(t('暂无成功模型'));
} }
@@ -224,11 +233,11 @@ const ModelTestModal = ({
<div className='model-test-toolbar'> <div className='model-test-toolbar'>
<Input <Input
placeholder={t('搜索模型...')} placeholder={t('搜索模型...')}
value={modelSearchKeyword} value={draft.keyword}
onChange={(event) => { onChange={(event) =>
setModelSearchKeyword(event.target.value); changeFilters({ keyword: event.target.value })
setModelTablePage(1); }
}} onPressEnter={submitSearch}
prefix={<Search size={16} />} prefix={<Search size={16} />}
allowClear allowClear
/> />
@@ -267,6 +276,7 @@ const ModelTestModal = ({
onChange: (keys) => setSelectedModelKeys(keys), onChange: (keys) => setSelectedModelKeys(keys),
}} }}
pagination={{ pagination={{
preservePage: true,
current: modelTablePage, current: modelTablePage,
pageSize: paginationSize, pageSize: paginationSize,
onChange: (page, size) => { onChange: (page, size) => {
@@ -2,7 +2,8 @@ import TableActionPopconfirm from '@/components/common/table/TableActionPopconfi
import { formatIdReference } from '../../../../helpers/safeDisplay'; import { formatIdReference } from '../../../../helpers/safeDisplay';
import { useEffectEvent } from '../../../../hooks/common/useEffectEvent'; import { useEffectEvent } from '../../../../hooks/common/useEffectEvent';
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect, useRef } from 'react';
import { useFilterSearch } from '@/hooks/common/useFilterSearch';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { import {
Modal, Modal,
@@ -55,14 +56,22 @@ const MultiKeyManageModal = ({ visible, onCancel, channel, onRefresh }) => {
// Filter states // Filter states
const [statusFilter, setStatusFilter] = useState(null); // null=all, 1=enabled, 2=manual_disabled, 3=auto_disabled const [statusFilter, setStatusFilter] = useState(null); // null=all, 1=enabled, 2=manual_disabled, 3=auto_disabled
const appliedStatus = useRef(null);
const activeRequest = useRef(null);
const cancelQuery = () => activeRequest.current?.abort();
// Load key status data // Load key status data
const loadKeyStatus = async ( const loadKeyStatus = async (
page = currentPage, page = currentPage,
size = pageSize, size = pageSize,
status = statusFilter, status = appliedStatus.current,
) => { ) => {
if (!channel?.id) return; if (!channel?.id) return;
cancelQuery();
const controller = new AbortController();
activeRequest.current = controller;
const { signal } = controller;
setLoading(true); setLoading(true);
try { try {
const requestData = { const requestData = {
@@ -77,13 +86,16 @@ const MultiKeyManageModal = ({ visible, onCancel, channel, onRefresh }) => {
requestData.status = status; requestData.status = status;
} }
const res = await API.post('/api/channel/multi_key/manage', requestData); const res = await API.post('/api/channel/multi_key/manage', requestData, {
signal,
});
if (signal.aborted) return;
if (res.data.success) { if (res.data.success) {
const data = res.data.data; const data = res.data.data;
setKeyStatusList(data.keys || []); setKeyStatusList(data.keys || []);
setTotal(data.total || 0); setTotal(data.total || 0);
setCurrentPage(data.page || 1); setCurrentPage(page);
setPageSize(data.page_size || 10); setPageSize(data.page_size || 10);
setTotalPages(data.total_pages || 0); setTotalPages(data.total_pages || 0);
@@ -95,13 +107,19 @@ const MultiKeyManageModal = ({ visible, onCancel, channel, onRefresh }) => {
showError(res.data.message); showError(res.data.message);
} }
} catch (error) { } catch (error) {
if (signal.aborted) return;
console.error(error); console.error(error);
showError(t('获取密钥状态失败')); if (!error?.isAxiosError) showError(t('获取密钥状态失败'));
} finally { } finally {
setLoading(false); if (!signal.aborted) setLoading(false);
} }
}; };
const { scheduleSearch, cancelPendingSearch } = useFilterSearch((status) => {
appliedStatus.current = status;
return loadKeyStatus(currentPage, pageSize, status);
}, cancelQuery);
// Disable a specific key // Disable a specific key
const handleDisableKey = async (keyIndex) => { const handleDisableKey = async (keyIndex) => {
const operationId = `disable_${keyIndex}`; const operationId = `disable_${keyIndex}`;
@@ -269,9 +287,9 @@ const MultiKeyManageModal = ({ visible, onCancel, channel, onRefresh }) => {
// Handle status filter change // Handle status filter change
const handleStatusFilterChange = (status) => { const handleStatusFilterChange = (status) => {
setStatusFilter(status); const value = status ?? null;
setCurrentPage(1); // Reset to first page when filter changes setStatusFilter(value);
loadKeyStatus(1, pageSize, status); scheduleSearch(value);
}; };
// Effect to load data when modal opens // Effect to load data when modal opens
@@ -280,6 +298,7 @@ const MultiKeyManageModal = ({ visible, onCancel, channel, onRefresh }) => {
setCurrentPage(1); // Reset to first page when opening setCurrentPage(1); // Reset to first page when opening
loadKeyStatus(1, pageSize); loadKeyStatus(1, pageSize);
} }
return cancelPendingSearch;
}); });
useEffect( useEffect(
() => onVisibilityChange(), () => onVisibilityChange(),
@@ -296,6 +315,7 @@ const MultiKeyManageModal = ({ visible, onCancel, channel, onRefresh }) => {
setEnabledCount(0); setEnabledCount(0);
setManualDisabledCount(0); setManualDisabledCount(0);
setAutoDisabledCount(0); setAutoDisabledCount(0);
appliedStatus.current = null;
setStatusFilter(null); // Reset filter setStatusFilter(null); // Reset filter
} }
}, [visible]); }, [visible]);
@@ -682,6 +702,7 @@ const MultiKeyManageModal = ({ visible, onCancel, channel, onRefresh }) => {
columns={columns} columns={columns}
dataSource={keyStatusList} dataSource={keyStatusList}
pagination={{ pagination={{
preservePage: true,
currentPage: currentPage, currentPage: currentPage,
pageSize: pageSize, pageSize: pageSize,
total: total, total: total,
+6 -12
View File
@@ -4,19 +4,19 @@ import FilterSearchButton from '../../common/table/FilterSearchButton';
import { useFilterSearch } from '../../../hooks/common/useFilterSearch'; import { useFilterSearch } from '../../../hooks/common/useFilterSearch';
import '../../common/table/log-filters.css'; import '../../common/table/log-filters.css';
import { DATE_RANGE_PRESETS } from '../../../constants/console.constants';
const MjLogsFilters = ({ const MjLogsFilters = ({
formInitValues, formInitValues,
setFormApi, setFormApi,
refresh, refresh,
activePage,
formApi, formApi,
loading, loading,
isAdminUser, isAdminUser,
t, t,
}) => { }) => {
const { scheduleSearch, submitSearch, cancelPendingSearch } = const { scheduleSearch, submitSearch, cancelPendingSearch } = useFilterSearch(
useFilterSearch(refresh); (_, signal) => refresh({ page: activePage, signal }),
);
return ( return (
<Form <Form
initValues={formInitValues} initValues={formInitValues}
@@ -38,14 +38,10 @@ const MjLogsFilters = ({
field='dateRange' field='dateRange'
label={t('时间范围')} label={t('时间范围')}
className='w-full' className='w-full'
tableFilter
type='dateTimeRange' type='dateTimeRange'
placeholder={[t('开始时间'), t('结束时间')]} placeholder={[t('开始时间'), t('结束时间')]}
showClear showClear
presets={DATE_RANGE_PRESETS.map((preset) => ({
text: t(preset.text),
start: preset.start(),
end: preset.end(),
}))}
/> />
</div> </div>
@@ -75,9 +71,7 @@ const MjLogsFilters = ({
if (formApi) { if (formApi) {
formApi.reset(); formApi.reset();
cancelPendingSearch(); cancelPendingSearch();
setTimeout(() => { refresh();
refresh();
}, 100);
} }
}} }}
> >
+1
View File
@@ -34,6 +34,7 @@ const MjLogsPage = () => {
/> />
} }
paginationArea={createCardProPagination({ paginationArea={createCardProPagination({
preservePage: true,
currentPage: mjLogsData.activePage, currentPage: mjLogsData.activePage,
pageSize: mjLogsData.pageSize, pageSize: mjLogsData.pageSize,
total: mjLogsData.logCount, total: mjLogsData.logCount,
@@ -9,12 +9,14 @@ const ModelsFilters = ({
formInitValues, formInitValues,
setFormApi, setFormApi,
searchModels, searchModels,
activePage,
setSelectedKeys,
loading, loading,
searching, searching,
t, t,
}) => { }) => {
const { scheduleSearch, submitSearch, cancelPendingSearch } = useFilterSearch( const { scheduleSearch, submitSearch, cancelPendingSearch } = useFilterSearch(
() => searchModels(), (_, signal) => searchModels(activePage, undefined, signal),
); );
// Handle form reset and immediate search // Handle form reset and immediate search
@@ -24,9 +26,8 @@ const ModelsFilters = ({
if (!formApiRef.current) return; if (!formApiRef.current) return;
formApiRef.current.reset(); formApiRef.current.reset();
cancelPendingSearch(); cancelPendingSearch();
setTimeout(() => { setSelectedKeys([]);
searchModels(); searchModels(1);
}, 100);
}; };
return ( return (
+3
View File
@@ -86,6 +86,8 @@ const ModelsPage = () => {
formInitValues={formInitValues} formInitValues={formInitValues}
setFormApi={setFormApi} setFormApi={setFormApi}
searchModels={searchModels} searchModels={searchModels}
activePage={modelsData.activePage}
setSelectedKeys={setSelectedKeys}
loading={loading} loading={loading}
searching={searching} searching={searching}
t={t} t={t}
@@ -114,6 +116,7 @@ const ModelsPage = () => {
</div> </div>
} }
paginationArea={createCardProPagination({ paginationArea={createCardProPagination({
preservePage: true,
currentPage: modelsData.activePage, currentPage: modelsData.activePage,
pageSize: modelsData.pageSize, pageSize: modelsData.pageSize,
total: modelsData.modelCount, total: modelsData.modelCount,
@@ -1,6 +1,8 @@
import { useLocalTableFilters } from '@/hooks/common/useLocalTableFilters';
import { useFilteredTableRows } from '@/hooks/common/useFilteredTableRows';
import { Trans } from 'react-i18next'; import { Trans } from 'react-i18next';
import { useEffectEvent } from '../../../../hooks/common/useEffectEvent'; import { useEffectEvent } from '../../../../hooks/common/useEffectEvent';
import React, { useEffect, useState } from 'react'; import React, { useCallback, useEffect, useState } from 'react';
import { import {
Modal, Modal,
Table, Table,
@@ -23,7 +25,9 @@ const MissingModelsModal = ({ visible, onClose, onConfigureModel, t }) => {
const [paginationSize, setPaginationSize] = useState(MODEL_TABLE_PAGE_SIZE); const [paginationSize, setPaginationSize] = useState(MODEL_TABLE_PAGE_SIZE);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [missingModels, setMissingModels] = useState([]); const [missingModels, setMissingModels] = useState([]);
const [searchKeyword, setSearchKeyword] = useState(''); const { draft, applied, changeFilters, submitSearch, resetFilters } =
useLocalTableFilters({ searchKeyword: '' });
const keyword = applied.searchKeyword.toLowerCase();
const [currentPage, setCurrentPage] = useState(1); const [currentPage, setCurrentPage] = useState(1);
const isMobile = useIsMobile(); const isMobile = useIsMobile();
@@ -45,7 +49,7 @@ const MissingModelsModal = ({ visible, onClose, onConfigureModel, t }) => {
const onVisibilityChange = useEffectEvent(() => { const onVisibilityChange = useEffectEvent(() => {
if (visible) { if (visible) {
fetchMissing(); fetchMissing();
setSearchKeyword(''); resetFilters();
setCurrentPage(1); setCurrentPage(1);
} else { } else {
setMissingModels([]); setMissingModels([]);
@@ -54,9 +58,11 @@ const MissingModelsModal = ({ visible, onClose, onConfigureModel, t }) => {
useEffect(() => onVisibilityChange(), [onVisibilityChange, visible]); useEffect(() => onVisibilityChange(), [onVisibilityChange, visible]);
// 过滤和分页逻辑 // 过滤和分页逻辑
const filteredModels = missingModels.filter((model) => const matches = useCallback(
model.toLowerCase().includes(searchKeyword.toLowerCase()), (model) => model.toLowerCase().includes(keyword),
[keyword],
); );
const filteredModels = useFilteredTableRows(missingModels, matches);
const dataSource = (() => { const dataSource = (() => {
const start = (currentPage - 1) * paginationSize; const start = (currentPage - 1) * paginationSize;
@@ -137,11 +143,9 @@ const MissingModelsModal = ({ visible, onClose, onConfigureModel, t }) => {
<div className='flex items-center justify-end gap-2 w-full mb-4'> <div className='flex items-center justify-end gap-2 w-full mb-4'>
<Input <Input
placeholder={t('搜索模型...')} placeholder={t('搜索模型...')}
value={searchKeyword} value={draft.searchKeyword}
onChange={(v) => { onChange={(searchKeyword) => changeFilters({ searchKeyword })}
setSearchKeyword(v); onEnterPress={submitSearch}
setCurrentPage(1);
}}
className='!w-full' className='!w-full'
prefix={<IconSearch />} prefix={<IconSearch />}
showClear showClear
@@ -149,7 +153,7 @@ const MissingModelsModal = ({ visible, onClose, onConfigureModel, t }) => {
</div> </div>
{/* 表格 */} {/* 表格 */}
{filteredModels.length > 0 ? ( {filteredModels.length > 0 || currentPage > 1 ? (
<Table <Table
// 列宽合计远超窄屏视口;没有 scroll 时表格会压缩到 min-content 硬塞进去, // 列宽合计远超窄屏视口;没有 scroll 时表格会压缩到 min-content 硬塞进去,
// 末尾的操作列落在视口外,且 iOS 上滚动条不可见、毫无可拖动提示 // 末尾的操作列落在视口外,且 iOS 上滚动条不可见、毫无可拖动提示
@@ -157,6 +161,7 @@ const MissingModelsModal = ({ visible, onClose, onConfigureModel, t }) => {
columns={columns} columns={columns}
dataSource={dataSource} dataSource={dataSource}
pagination={{ pagination={{
preservePage: true,
currentPage: currentPage, currentPage: currentPage,
pageSize: paginationSize, pageSize: paginationSize,
total: filteredModels.length, total: filteredModels.length,
@@ -178,7 +183,7 @@ const MissingModelsModal = ({ visible, onClose, onConfigureModel, t }) => {
/> />
} }
description={ description={
searchKeyword ? t('未找到匹配的模型') : t('暂无缺失模型') keyword ? t('未找到匹配的模型') : t('暂无缺失模型')
} }
style={{ padding: 20 }} style={{ padding: 20 }}
/> />
@@ -1,3 +1,6 @@
import { useLocalTableFilters } from '@/hooks/common/useLocalTableFilters';
import { useFilteredTableRows } from '@/hooks/common/useFilteredTableRows';
import { useEffectEvent } from '@/hooks/common/useEffectEvent';
import React, { useEffect, useMemo, useState, useCallback } from 'react'; import React, { useEffect, useMemo, useState, useCallback } from 'react';
import { import {
Modal, Modal,
@@ -39,7 +42,9 @@ const UpstreamConflictModal = ({
const [selections, setSelections] = useState({}); const [selections, setSelections] = useState({});
const isMobile = useIsMobile(); const isMobile = useIsMobile();
const [currentPage, setCurrentPage] = useState(1); const [currentPage, setCurrentPage] = useState(1);
const [searchKeyword, setSearchKeyword] = useState(''); const { draft, applied, changeFilters, submitSearch, resetFilters } =
useLocalTableFilters({ searchKeyword: '' });
const keyword = applied.searchKeyword.toLowerCase();
const formatValue = (v) => { const formatValue = (v) => {
if (v === null || v === undefined) return '-'; if (v === null || v === undefined) return '-';
@@ -51,6 +56,7 @@ const UpstreamConflictModal = ({
} }
}; };
const resetSearch = useEffectEvent(resetFilters);
useEffect(() => { useEffect(() => {
if (visible) { if (visible) {
const init = {}; const init = {};
@@ -59,11 +65,11 @@ const UpstreamConflictModal = ({
}); });
setSelections(init); setSelections(init);
setCurrentPage(1); setCurrentPage(1);
setSearchKeyword(''); resetSearch();
} else { } else {
setSelections({}); setSelections({});
} }
}, [visible, conflicts]); }, [visible, conflicts, resetSearch]);
const toggleField = useCallback((modelName, field, checked) => { const toggleField = useCallback((modelName, field, checked) => {
setSelections((prev) => { setSelections((prev) => {
@@ -87,13 +93,11 @@ const UpstreamConflictModal = ({
[conflicts], [conflicts],
); );
const filteredDataSource = useMemo(() => { const matches = useCallback(
const kw = (searchKeyword || '').toLowerCase(); (item) => (item.model_name || '').toLowerCase().includes(keyword),
if (!kw) return dataSource; [keyword],
return dataSource.filter((item) => );
(item.model_name || '').toLowerCase().includes(kw), const filteredDataSource = useFilteredTableRows(dataSource, matches);
);
}, [dataSource, searchKeyword]);
// 列头工具:当前过滤范围内可操作的行集合/勾选状态/批量设置 // 列头工具:当前过滤范围内可操作的行集合/勾选状态/批量设置
const getPresentRowsForField = useCallback( const getPresentRowsForField = useCallback(
@@ -261,21 +265,20 @@ const UpstreamConflictModal = ({
<div className='flex items-center justify-end gap-2 w-full mb-4'> <div className='flex items-center justify-end gap-2 w-full mb-4'>
<Input <Input
placeholder={t('搜索模型...')} placeholder={t('搜索模型...')}
value={searchKeyword} value={draft.searchKeyword}
onChange={(v) => { onChange={(searchKeyword) => changeFilters({ searchKeyword })}
setSearchKeyword(v); onEnterPress={submitSearch}
setCurrentPage(1);
}}
className='!w-full' className='!w-full'
prefix={<IconSearch />} prefix={<IconSearch />}
showClear showClear
/> />
</div> </div>
{filteredDataSource.length > 0 ? ( {filteredDataSource.length > 0 || currentPage > 1 ? (
<Table <Table
columns={columns} columns={columns}
dataSource={pagedDataSource} dataSource={pagedDataSource}
pagination={{ pagination={{
preservePage: true,
currentPage: currentPage, currentPage: currentPage,
pageSize: paginationSize, pageSize: paginationSize,
total: filteredDataSource.length, total: filteredDataSource.length,
@@ -289,9 +292,7 @@ const UpstreamConflictModal = ({
/> />
) : ( ) : (
<Empty <Empty
description={ description={keyword ? t('未找到匹配的模型') : t('无冲突项')}
searchKeyword ? t('未找到匹配的模型') : t('无冲突项')
}
className='p-6' className='p-6'
/> />
)} )}
@@ -1,4 +1,5 @@
import React, { useRef } from 'react'; import React, { useRef } from 'react';
import { useFilterSearch } from '../../../hooks/common/useFilterSearch';
import { Form } from '@/components/ui'; import { Form } from '@/components/ui';
import { ConsoleSearchActions } from '../../console/ConsolePrimitives'; import { ConsoleSearchActions } from '../../console/ConsolePrimitives';
import { IconSearch } from '@/components/ui/icons'; import { IconSearch } from '@/components/ui/icons';
@@ -7,19 +8,24 @@ const RedemptionsFilters = ({
formInitValues, formInitValues,
setFormApi, setFormApi,
searchRedemptions, searchRedemptions,
activePage,
setSelectedKeys,
loading, loading,
searching, searching,
t, t,
}) => { }) => {
// Handle form reset and immediate search // Handle form reset and immediate search
const formApiRef = useRef(null); const formApiRef = useRef(null);
const { scheduleSearch, submitSearch, cancelPendingSearch } = useFilterSearch(
(_, signal) => searchRedemptions(activePage, signal),
);
const handleReset = () => { const handleReset = () => {
if (!formApiRef.current) return; if (!formApiRef.current) return;
formApiRef.current.reset(); formApiRef.current.reset();
setTimeout(() => { cancelPendingSearch();
searchRedemptions(); setSelectedKeys([]);
}, 100); searchRedemptions(1);
}; };
return ( return (
@@ -29,7 +35,8 @@ const RedemptionsFilters = ({
setFormApi(api); setFormApi(api);
formApiRef.current = api; formApiRef.current = api;
}} }}
onSubmit={searchRedemptions} onSubmit={submitSearch}
onValueChange={scheduleSearch}
allowEmpty={true} allowEmpty={true}
autoComplete='off' autoComplete='off'
layout='vertical' layout='vertical'
@@ -57,6 +57,8 @@ const RedemptionsPage = () => {
formInitValues={formInitValues} formInitValues={formInitValues}
setFormApi={setFormApi} setFormApi={setFormApi}
searchRedemptions={searchRedemptions} searchRedemptions={searchRedemptions}
activePage={redemptionsData.activePage}
setSelectedKeys={redemptionsData.setSelectedKeys}
loading={loading} loading={loading}
searching={searching} searching={searching}
t={t} t={t}
@@ -81,6 +83,7 @@ const RedemptionsPage = () => {
</div> </div>
} }
paginationArea={createCardProPagination({ paginationArea={createCardProPagination({
preservePage: true,
currentPage: redemptionsData.activePage, currentPage: redemptionsData.activePage,
pageSize: redemptionsData.pageSize, pageSize: redemptionsData.pageSize,
total: redemptionsData.tokenCount, total: redemptionsData.tokenCount,
@@ -12,7 +12,6 @@ import {
Layers, Layers,
} from 'lucide-react'; } from 'lucide-react';
import { DATE_RANGE_PRESETS } from '../../../constants/console.constants';
import { useConsolePage } from '../../console/ConsoleContext'; import { useConsolePage } from '../../console/ConsoleContext';
import FilterSearchButton from '../../common/table/FilterSearchButton'; import FilterSearchButton from '../../common/table/FilterSearchButton';
import { useFilterSearch } from '../../../hooks/common/useFilterSearch'; import { useFilterSearch } from '../../../hooks/common/useFilterSearch';
@@ -29,6 +28,7 @@ const TaskLogsFilters = ({
formInitValues, formInitValues,
setFormApi, setFormApi,
refresh, refresh,
activePage,
formApi, formApi,
loading, loading,
isAdminUser, isAdminUser,
@@ -38,8 +38,9 @@ const TaskLogsFilters = ({
t, t,
}) => { }) => {
const consolePage = useConsolePage(); const consolePage = useConsolePage();
const { scheduleSearch, submitSearch, cancelPendingSearch } = const { scheduleSearch, submitSearch, cancelPendingSearch } = useFilterSearch(
useFilterSearch(refresh); (_, signal) => refresh({ page: activePage, signal }),
);
const SearchIcon = Search; const SearchIcon = Search;
const ResetIcon = RotateCcw; const ResetIcon = RotateCcw;
const primaryButtonClass = const primaryButtonClass =
@@ -63,9 +64,7 @@ const TaskLogsFilters = ({
: formInitValues; : formInitValues;
formApi.setValues(fresh, { isOverride: true }); formApi.setValues(fresh, { isOverride: true });
cancelPendingSearch(); cancelPendingSearch();
setTimeout(() => { refresh();
refresh();
}, 100);
} }
}; };
@@ -105,12 +104,6 @@ const TaskLogsFilters = ({
} }
}; };
const datePresets = DATE_RANGE_PRESETS.map((preset) => ({
text: t(preset.text),
start: preset.start(),
end: preset.end(),
}));
const statusOptions = ( const statusOptions = (
<> <>
<Form.Select.Option value=''>{t('全部状态')}</Form.Select.Option> <Form.Select.Option value=''>{t('全部状态')}</Form.Select.Option>
@@ -156,8 +149,8 @@ const TaskLogsFilters = ({
<Form <Form
initValues={formInitValues} initValues={formInitValues}
getFormApi={(api) => setFormApi(api)} getFormApi={(api) => setFormApi(api)}
onSubmit={consolePage ? submitSearch : refresh} onSubmit={submitSearch}
onValueChange={consolePage ? scheduleSearch : undefined} onValueChange={scheduleSearch}
allowEmpty={true} allowEmpty={true}
autoComplete='off' autoComplete='off'
layout='vertical' layout='vertical'
@@ -170,10 +163,10 @@ const TaskLogsFilters = ({
field='dateRange' field='dateRange'
label={t('时间范围')} label={t('时间范围')}
className='usage-record-filter-wide' className='usage-record-filter-wide'
tableFilter
type='dateTimeRange' type='dateTimeRange'
placeholder={[t('开始时间'), t('结束时间')]} placeholder={[t('开始时间'), t('结束时间')]}
showClear showClear
presets={datePresets}
/> />
<Form.Input <Form.Input
field='task_id' field='task_id'
@@ -240,7 +233,8 @@ const TaskLogsFilters = ({
<Form <Form
initValues={formInitValues} initValues={formInitValues}
getFormApi={(api) => setFormApi(api)} getFormApi={(api) => setFormApi(api)}
onSubmit={refresh} onSubmit={submitSearch}
onValueChange={scheduleSearch}
allowEmpty={true} allowEmpty={true}
autoComplete='off' autoComplete='off'
layout='vertical' layout='vertical'
@@ -269,13 +263,13 @@ const TaskLogsFilters = ({
<Form.DatePicker <Form.DatePicker
field='dateRange' field='dateRange'
className='w-full' className='w-full'
tableFilter
type='dateTimeRange' type='dateTimeRange'
placeholder={[t('开始时间'), t('结束时间')]} placeholder={[t('开始时间'), t('结束时间')]}
showClear showClear
pure pure
size='small' size='small'
prefix={<InputPrefix icon={Calendar} />} prefix={<InputPrefix icon={Calendar} />}
presets={datePresets}
/> />
</div> </div>
</div> </div>
+1
View File
@@ -149,6 +149,7 @@ const TaskLogsPage = ({
/> />
} }
paginationArea={createCardProPagination({ paginationArea={createCardProPagination({
preservePage: true,
showRange: false, showRange: false,
currentPage: taskLogsData.activePage, currentPage: taskLogsData.activePage,
pageSize: taskLogsData.pageSize, pageSize: taskLogsData.pageSize,
@@ -5,12 +5,11 @@ import '../../common/table/log-filters.css';
import FilterSearchButton from '../../common/table/FilterSearchButton'; import FilterSearchButton from '../../common/table/FilterSearchButton';
import { useFilterSearch } from '../../../hooks/common/useFilterSearch'; import { useFilterSearch } from '../../../hooks/common/useFilterSearch';
import { DATE_RANGE_PRESETS } from '../../../constants/console.constants';
const LogsFilters = ({ const LogsFilters = ({
formInitValues, formInitValues,
setFormApi, setFormApi,
refresh, refresh,
activePage,
formApi, formApi,
loading, loading,
isAdminUser, isAdminUser,
@@ -18,8 +17,9 @@ const LogsFilters = ({
usageRecordMode = false, usageRecordMode = false,
t, t,
}) => { }) => {
const { scheduleSearch, submitSearch, cancelPendingSearch } = const { scheduleSearch, submitSearch, cancelPendingSearch } = useFilterSearch(
useFilterSearch(refresh); (_, signal) => refresh({ page: activePage, signal }),
);
// 用户 ID 仅允许数字:键入过滤与粘贴清洗(两种布局共用) // 用户 ID 仅允许数字:键入过滤与粘贴清洗(两种布局共用)
const digitsOnlyKeyDown = (e) => { const digitsOnlyKeyDown = (e) => {
if ( if (
@@ -64,24 +64,17 @@ const LogsFilters = ({
: formInitValues; : formInitValues;
formApi.setValues(fresh, { isOverride: true }); formApi.setValues(fresh, { isOverride: true });
cancelPendingSearch(); cancelPendingSearch();
setTimeout(() => { refresh();
refresh();
}, 100);
}; };
const datePresets = DATE_RANGE_PRESETS.map((preset) => ({
text: t(preset.text),
start: preset.start(),
end: preset.end(),
}));
// 个人端使用记录:原型为带字段标签的五列筛选卡,重置/搜索位于右下;列设置与导出移至表格卡片标题栏 // 个人端使用记录:原型为带字段标签的五列筛选卡,重置/搜索位于右下;列设置与导出移至表格卡片标题栏
if (usageRecordMode) { if (usageRecordMode) {
return ( return (
<Form <Form
initValues={formInitValues} initValues={formInitValues}
getFormApi={(api) => setFormApi(api)} getFormApi={(api) => setFormApi(api)}
onSubmit={refresh} onSubmit={submitSearch}
onValueChange={scheduleSearch}
allowEmpty={true} allowEmpty={true}
autoComplete='off' autoComplete='off'
layout='vertical' layout='vertical'
@@ -94,10 +87,10 @@ const LogsFilters = ({
field='dateRange' field='dateRange'
label={t('时间范围')} label={t('时间范围')}
className='usage-record-filter-wide' className='usage-record-filter-wide'
tableFilter
type='dateTimeRange' type='dateTimeRange'
placeholder={[t('开始时间'), t('结束时间')]} placeholder={[t('开始时间'), t('结束时间')]}
showClear showClear
presets={datePresets}
/> />
<Form.Input <Form.Input
field='token_name' field='token_name'
@@ -147,11 +140,6 @@ const LogsFilters = ({
label={t('类型')} label={t('类型')}
placeholder={t('全部类型')} placeholder={t('全部类型')}
showClear showClear
onChange={() => {
setTimeout(() => {
refresh();
}, 0);
}}
> >
<Form.Select.Option value='0'>{t('全部类型')}</Form.Select.Option> <Form.Select.Option value='0'>{t('全部类型')}</Form.Select.Option>
<Form.Select.Option value='1'>{t('充值')}</Form.Select.Option> <Form.Select.Option value='1'>{t('充值')}</Form.Select.Option>
@@ -199,10 +187,10 @@ const LogsFilters = ({
label={t('时间范围')} label={t('时间范围')}
className='log-filter-wide' className='log-filter-wide'
dropdownClassName='usage-logs-date-panel' dropdownClassName='usage-logs-date-panel'
tableFilter
type='dateTimeRange' type='dateTimeRange'
placeholder={[t('开始时间'), t('结束时间')]} placeholder={[t('开始时间'), t('结束时间')]}
showClear showClear
presets={datePresets}
/> />
<Form.Input <Form.Input
@@ -103,6 +103,7 @@ const LogsPage = ({ usageRecordMode = false }) => {
</> </>
} }
paginationArea={createCardProPagination({ paginationArea={createCardProPagination({
preservePage: true,
currentPage: logsData.activePage, currentPage: logsData.activePage,
pageSize: logsData.pageSize, pageSize: logsData.pageSize,
total: logsData.logCount, total: logsData.logCount,
+3 -4
View File
@@ -17,7 +17,8 @@ const UsersFilters = ({
t, t,
}) => { }) => {
const { scheduleSearch, submitSearch, cancelPendingSearch } = useFilterSearch( const { scheduleSearch, submitSearch, cancelPendingSearch } = useFilterSearch(
() => searchUsers(1, pageSize), (_, signal) =>
searchUsers(Math.max(1, activePage), pageSize, null, null, signal),
); );
const formApiRef = useRef(null); const formApiRef = useRef(null);
@@ -26,9 +27,7 @@ const UsersFilters = ({
if (!formApiRef.current) return; if (!formApiRef.current) return;
formApiRef.current.reset(); formApiRef.current.reset();
cancelPendingSearch(); cancelPendingSearch();
setTimeout(() => { loadUsers(1, pageSize).catch(() => {});
loadUsers(1, pageSize);
}, 100);
}; };
return ( return (
+1
View File
@@ -84,6 +84,7 @@ const UsersPage = () => {
} }
tableActions={<UsersActions setShowAddUser={setShowAddUser} t={t} />} tableActions={<UsersActions setShowAddUser={setShowAddUser} t={t} />}
paginationArea={createCardProPagination({ paginationArea={createCardProPagination({
preservePage: true,
showRange: false, showRange: false,
currentPage: usersData.activePage, currentPage: usersData.activePage,
pageSize: usersData.pageSize, pageSize: usersData.pageSize,
+65 -8
View File
@@ -17,6 +17,9 @@ import {
Space as AntSpace, Space as AntSpace,
} from 'antd'; } from 'antd';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import { useTranslation } from 'react-i18next';
import { DATE_RANGE_PRESETS } from '../../constants/console.constants';
import '../common/table/table-filter-range.css';
import { import {
useConsoleControlSize, useConsoleControlSize,
useConsolePage, useConsolePage,
@@ -391,6 +394,7 @@ export function DatePicker({
disabledDate, disabledDate,
density, density,
presets, presets,
tableFilter = false,
size, size,
inputReadOnly, inputReadOnly,
dropdownClassName, dropdownClassName,
@@ -398,18 +402,68 @@ export function DatePicker({
format, format,
...props ...props
}) { }) {
const { t } = useTranslation();
const range = type?.toLowerCase().includes('range'); const range = type?.toLowerCase().includes('range');
const Component = range ? AntDatePicker.RangePicker : AntDatePicker; const Component = range ? AntDatePicker.RangePicker : AntDatePicker;
const convert = (v) => (range ? (v || []).map(toDay) : toDay(v)); const convert = (v) => (range ? (v || []).map(toDay) : toDay(v));
const withTime = type?.toLowerCase().includes('time');
const selected = tableFilter && range ? convert(value ?? defaultValue) : [];
const tablePresets =
tableFilter && range
? DATE_RANGE_PRESETS.map(({ text, start, end }) => {
const bounds = [start, end];
const active = bounds.every((get, index) =>
selected[index]?.isSame(dayjs(get()), withTime ? 'second' : 'day'),
);
return {
label: (
<span
className={active ? 'table-filter-period-active' : undefined}
>
{t(text)}
</span>
),
value: () => bounds.map((get) => dayjs(get())),
};
})
: undefined;
return ( return (
<Component <Component
{...props} {...props}
{...(tableFilter
? {
className: [props.className, 'table-filter-range']
.filter(Boolean)
.join(' '),
placeholder: [t('开始时间'), t('结束时间')],
popupAlign: {
offset: [0, 0],
...props.popupAlign,
overflow: {
adjustX: 1,
adjustY: 1,
shiftX: true,
shiftY: true,
...props.popupAlign?.overflow,
},
},
}
: {})}
{...(tableFilter
? { format: withTime ? 'YYYY-MM-DD HH:mm:ss' : 'YYYY-MM-DD' }
: {})}
{...(format !== undefined ? { format: toDayjsFormat(format) } : {})} {...(format !== undefined ? { format: toDayjsFormat(format) } : {})}
classNames={{ classNames={{
...props.classNames, ...props.classNames,
popup: { popup: {
...props.classNames?.popup, ...props.classNames?.popup,
root: dropdownClassName ?? props.classNames?.popup?.root, root:
[
dropdownClassName ?? props.classNames?.popup?.root,
tableFilter && 'table-filter-range-popup',
]
.filter(Boolean)
.join(' ') || undefined,
}, },
}} }}
styles={{ styles={{
@@ -423,15 +477,18 @@ export function DatePicker({
defaultValue={ defaultValue={
defaultValue === undefined ? undefined : convert(defaultValue) defaultValue === undefined ? undefined : convert(defaultValue)
} }
size={useConsoleControlSize(size)} size={useConsoleControlSize(tableFilter ? 'middle' : size)}
allowClear={showClear} allowClear={tableFilter || showClear}
showTime={type?.toLowerCase().includes('time')} showTime={withTime}
inputReadOnly={inputReadOnly} inputReadOnly={inputReadOnly}
disabledDate={disabledDate ? (d) => disabledDate(d.toDate()) : undefined} disabledDate={disabledDate ? (d) => disabledDate(d.toDate()) : undefined}
presets={presets?.map((p) => ({ presets={
label: p.label || p.text, tablePresets ??
value: convert(p.value || (p.start && [p.start, p.end])), presets?.map((p) => ({
}))} label: p.label || p.text,
value: convert(p.value || (p.start && [p.start, p.end])),
}))
}
onChange={(dates, strings) => onChange={(dates, strings) =>
onChange?.(dates ? toDate(dates) : null, dates ? strings : '') onChange?.(dates ? toDate(dates) : null, dates ? strings : '')
} }
+61 -30
View File
@@ -341,34 +341,60 @@ function LocalPaginatedTable({ component: Component, config, ...props }) {
}, [resetOnDataChange, resetSource]); }, [resetOnDataChange, resetSource]);
const managesSize = !hasPageSizeHandler(config); const managesSize = !hasPageSizeHandler(config);
const pageSize = managesSize ? localSize : (config.pageSize ?? localSize); const pageSize = managesSize ? localSize : (config.pageSize ?? localSize);
const page = config.currentPage ?? config.current ?? localPage;
const total = props.dataSource?.length ?? 0;
const outsideResults =
config.preservePage && page > lastPage(total, pageSize);
const current = useValidPage({ const current = useValidPage({
page: config.currentPage ?? config.current ?? localPage, page,
total: props.dataSource?.length ?? 0, total,
pageSize, pageSize,
loading: props.loading || resetOnDataChange, loading: props.loading || resetOnDataChange || config.preservePage,
onPageChange: onPageChange:
config.onPageChange ?? (config.onChange ? undefined : setLocalPage), config.onPageChange ?? (config.onChange ? undefined : setLocalPage),
onChange: config.onChange, onChange: config.onChange,
}); });
const events = centerPaginationEvents({ ...config, pageSize }); const events = centerPaginationEvents({ ...config, pageSize });
const changePage = (page, size) => {
setLocalPage(size === pageSize ? page : 1);
if (size !== pageSize && managesSize) {
setLocalSize(size);
if (current !== 1) config.onPageChange?.(1);
} else {
events.onChange(page, size);
}
};
return ( return (
<Component <>
{...props} <Component
pagination={{ {...props}
...centerPaginationOptions({ className: config.className }, isMobile), dataSource={outsideResults ? [] : props.dataSource}
current, pagination={
pageSize, outsideResults
onChange: (page, size) => { ? false
setLocalPage(size === pageSize ? page : 1); : {
if (size !== pageSize && managesSize) { ...centerPaginationOptions(
setLocalSize(size); { className: config.className },
if (current !== 1) config.onPageChange?.(1); isMobile,
} else { ),
events.onChange(page, size); current,
} pageSize,
}, onChange: changePage,
}} }
/> }
/>
{outsideResults && (
<Pagination
currentPage={page}
pageSize={pageSize}
total={total}
preservePage
onPageChange={(nextPage) => changePage(nextPage, pageSize)}
onPageSizeChange={(size) => changePage(1, size)}
className='table-pagination-footer'
/>
)}
</>
); );
} }
@@ -407,6 +433,7 @@ export function Pagination({
total = 0, total = 0,
className, className,
loading = false, loading = false,
preservePage = false,
}) { }) {
const isMobile = useIsMobile(); const isMobile = useIsMobile();
const config = { const config = {
@@ -416,23 +443,27 @@ export function Pagination({
onShowSizeChange, onShowSizeChange,
onChange, onChange,
}; };
const resolvedPage = useValidPage({ const page = currentPage ?? current ?? 1;
page: currentPage ?? current ?? 1, const validPage = useValidPage({
page,
total, total,
loading, loading: loading || preservePage,
...config, ...config,
}); });
if (!total) return null; const outsideResults = preservePage && page !== validPage;
if (!total && !outsideResults) return null;
const options = centerPaginationOptions(
{ className, showSizeChanger: hasPageSizeHandler(config) },
isMobile,
);
return ( return (
<Ant.Pagination <Ant.Pagination
{...centerPaginationOptions( {...options}
{ className, showSizeChanger: hasPageSizeHandler(config) },
isMobile,
)}
{...centerPaginationEvents(config)} {...centerPaginationEvents(config)}
current={resolvedPage} current={outsideResults ? page : validPage}
pageSize={pageSize} pageSize={pageSize}
total={total} total={outsideResults ? (page - 1) * pageSize + 1 : total}
showTotal={() => options.showTotal(total)}
/> />
); );
} }
+3 -1
View File
@@ -1046,6 +1046,7 @@ export const formatPriceInfo = (priceData, t) => {
// CardPro 分页配置函数 // CardPro 分页配置函数
// 用于创建 CardPro 的 paginationArea 配置 // 用于创建 CardPro 的 paginationArea 配置
export const createCardProPagination = ({ export const createCardProPagination = ({
preservePage = false,
currentPage, currentPage,
pageSize, pageSize,
total, total,
@@ -1053,8 +1054,9 @@ export const createCardProPagination = ({
onPageSizeChange, onPageSizeChange,
}) => { }) => {
return ( return (
total > 0 && ( (total > 0 || (preservePage && currentPage > 1)) && (
<Pagination <Pagination
preservePage={preservePage}
currentPage={currentPage} currentPage={currentPage}
pageSize={pageSize} pageSize={pageSize}
total={total} total={total}
+11 -29
View File
@@ -110,7 +110,7 @@ export const useAdminTokensData = () => {
// 核心:唯一的列表加载函数(loadTokens 兼容 searchTokens 的所有调用方式) // 核心:唯一的列表加载函数(loadTokens 兼容 searchTokens 的所有调用方式)
const listRequestIdRef = useRef(0); const listRequestIdRef = useRef(0);
const loadTokens = useCallback( const loadTokens = useCallback(
async (page = 1, size = pageSizeRef.current, filters = null) => { async (page = 1, size = pageSizeRef.current, filters = null, signal) => {
const requestId = ++listRequestIdRef.current; const requestId = ++listRequestIdRef.current;
const useFilters = filters || getFormValues(); const useFilters = filters || getFormValues();
const filtered = hasAnyFilter(useFilters); const filtered = hasAnyFilter(useFilters);
@@ -123,27 +123,32 @@ export const useAdminTokensData = () => {
try { try {
const qs = buildQuery(page, size, useFilters); const qs = buildQuery(page, size, useFilters);
const res = await API.get(`/api/token/admin?${qs}`); const res = await API.get(`/api/token/admin?${qs}`, { signal });
if (requestId !== listRequestIdRef.current) return; if (requestId !== listRequestIdRef.current || signal?.aborted) return;
const { success, message, data } = res.data; const { success, message, data } = res.data;
if (success) { if (success) {
// 边界:删除最后一页的所有记录后,page 已超出有效范围 // 边界:删除最后一页的所有记录后,page 已超出有效范围
// 自动回退到上一页(如果 page > 1 且当前页无数据但 total > 0) // 自动回退到上一页(如果 page > 1 且当前页无数据但 total > 0)
if (page > 1 && (data.items || []).length === 0 && data.total > 0) { if (
!signal &&
page > 1 &&
(data.items || []).length === 0 &&
data.total > 0
) {
const lastPage = Math.max(1, Math.ceil(data.total / size)); const lastPage = Math.max(1, Math.ceil(data.total / size));
if (lastPage !== page) { if (lastPage !== page) {
// 递归回退到合法页码(最多回退一次) // 递归回退到合法页码(最多回退一次)
return loadTokens(lastPage, size, useFilters); return loadTokens(lastPage, size, useFilters);
} }
} }
setActivePage(data.page); setActivePage(signal ? page : data.page);
setTokenCount(data.total); setTokenCount(data.total);
setListFormat(data.items || []); setListFormat(data.items || []);
} else { } else {
showError(message); showError(message);
} }
} catch (e) { } catch (e) {
if (requestId !== listRequestIdRef.current) return; if (requestId !== listRequestIdRef.current || signal?.aborted) return;
console.error('[AdminTokens] loadTokens failed:', e); console.error('[AdminTokens] loadTokens failed:', e);
showError(e.message || t('加载失败')); showError(e.message || t('加载失败'));
} finally { } finally {
@@ -157,27 +162,6 @@ export const useAdminTokensData = () => {
[getFormValues, t], [getFormValues, t],
); );
// searchTokens 保留作为对外语义清晰的别名(重置到第 1 页)
const searchTokens = useCallback(
(size = pageSizeRef.current) => loadTokens(1, size),
[loadTokens],
);
// 真正的 debounce 实现(300ms),用于 Filters onChange 联动
const debounceTimerRef = useRef(null);
const debouncedSearch = useCallback(() => {
if (debounceTimerRef.current) clearTimeout(debounceTimerRef.current);
debounceTimerRef.current = setTimeout(() => {
loadTokens(1, pageSizeRef.current);
}, 300);
}, [loadTokens]);
useEffect(() => {
return () => {
if (debounceTimerRef.current) clearTimeout(debounceTimerRef.current);
};
}, []);
const refresh = useCallback( const refresh = useCallback(
(page = activePage) => loadTokens(page, pageSizeRef.current), (page = activePage) => loadTokens(page, pageSizeRef.current),
[activePage, loadTokens], [activePage, loadTokens],
@@ -311,8 +295,6 @@ export const useAdminTokensData = () => {
// 操作 // 操作
loadTokens, loadTokens,
searchTokens,
debouncedSearch,
refresh, refresh,
manageToken, manageToken,
batchManageTokens, batchManageTokens,
+82 -47
View File
@@ -1,5 +1,6 @@
import { useState, useCallback, useEffect, useRef } from 'react'; import { useState, useCallback, useEffect, useRef } from 'react';
import { API, showError } from '../../helpers'; import { API, showError } from '../../helpers';
import { useFilterSearch } from '../common/useFilterSearch';
/** /**
* 运营看板数据获取Hook * 运营看板数据获取Hook
@@ -22,6 +23,10 @@ export const useAnalyticsData = (active = true) => {
const [period, setPeriod] = useState('today'); // today, week, month, quarter, custom const [period, setPeriod] = useState('today'); // today, week, month, quarter, custom
const [dateRange, setDateRange] = useState([null, null]); // 自定义日期范围 [startDate, endDate] const [dateRange, setDateRange] = useState([null, null]); // 自定义日期范围 [startDate, endDate]
const activeRequest = useRef(null);
const cancelQuery = useCallback(() => activeRequest.current?.abort(), []);
useEffect(() => cancelQuery, [cancelQuery]);
// 将 DatePicker 选择的日期转换为 UTC+8 当天零点/末尾的 Unix 时间戳(秒) // 将 DatePicker 选择的日期转换为 UTC+8 当天零点/末尾的 Unix 时间戳(秒)
// DatePicker 返回的 Date 对象,其本地日期分量即用户选的日期,直接当作 CST 日期处理 // DatePicker 返回的 Date 对象,其本地日期分量即用户选的日期,直接当作 CST 日期处理
const toCST = useCallback((date, isEndOfDay = false) => { const toCST = useCallback((date, isEndOfDay = false) => {
@@ -64,35 +69,40 @@ export const useAnalyticsData = (active = true) => {
); );
// 获取概览数据。后端对概览结果做了 60s 缓存,force=true 时穿透(用户主动点刷新) // 获取概览数据。后端对概览结果做了 60s 缓存,force=true 时穿透(用户主动点刷新)
const fetchOverview = useCallback(async (force = false) => { const fetchOverview = useCallback(async (force, signal) => {
setOverviewLoading(true); setOverviewLoading(true);
try { try {
const res = await API.get( const res = await API.get(
`/api/analytics/overview${force ? '?refresh=true' : ''}`, `/api/analytics/overview${force ? '?refresh=true' : ''}`,
{ signal },
); );
if (signal.aborted) return;
if (res.data.success) { if (res.data.success) {
setOverview(res.data.data); setOverview(res.data.data);
} else { } else {
showError(res.data.message); showError(res.data.message);
} }
} catch (error) { } catch (error) {
console.error('获取概览数据失败:', error); if (!signal.aborted) console.error('获取概览数据失败:', error);
} finally { } finally {
setOverviewLoading(false); if (!signal.aborted) setOverviewLoading(false);
} }
}, []); }, []);
// 获取用户趋势 // 获取用户趋势
const fetchUserTrend = useCallback( const fetchUserTrend = useCallback(
async (currentPeriod, currentDateRange) => { async (currentPeriod, currentDateRange, signal) => {
try { try {
const queryParams = buildQueryParams(currentPeriod, currentDateRange); const queryParams = buildQueryParams(currentPeriod, currentDateRange);
const res = await API.get(`/api/analytics/user-trend?${queryParams}`); const res = await API.get(`/api/analytics/user-trend?${queryParams}`, {
signal,
});
if (signal.aborted) return;
if (res.data.success) { if (res.data.success) {
setUserTrend(res.data.data || []); setUserTrend(res.data.data || []);
} }
} catch (error) { } catch (error) {
console.error('获取用户趋势失败:', error); if (!signal.aborted) console.error('获取用户趋势失败:', error);
} }
}, },
[buildQueryParams], [buildQueryParams],
@@ -100,17 +110,19 @@ export const useAnalyticsData = (active = true) => {
// 获取收支趋势 // 获取收支趋势
const fetchFinanceTrend = useCallback( const fetchFinanceTrend = useCallback(
async (currentPeriod, currentDateRange) => { async (currentPeriod, currentDateRange, signal) => {
try { try {
const queryParams = buildQueryParams(currentPeriod, currentDateRange); const queryParams = buildQueryParams(currentPeriod, currentDateRange);
const res = await API.get( const res = await API.get(
`/api/analytics/finance-trend?${queryParams}`, `/api/analytics/finance-trend?${queryParams}`,
{ signal },
); );
if (signal.aborted) return;
if (res.data.success) { if (res.data.success) {
setFinanceTrend(res.data.data || []); setFinanceTrend(res.data.data || []);
} }
} catch (error) { } catch (error) {
console.error('获取收支趋势失败:', error); if (!signal.aborted) console.error('获取收支趋势失败:', error);
} }
}, },
[buildQueryParams], [buildQueryParams],
@@ -118,18 +130,20 @@ export const useAnalyticsData = (active = true) => {
// 获取渠道消耗排行 // 获取渠道消耗排行
const fetchChannelConsumption = useCallback( const fetchChannelConsumption = useCallback(
async (currentPeriod, currentDateRange) => { async (currentPeriod, currentDateRange, signal) => {
try { try {
const queryParams = buildQueryParams(currentPeriod, currentDateRange); const queryParams = buildQueryParams(currentPeriod, currentDateRange);
const separator = queryParams ? '&' : ''; const separator = queryParams ? '&' : '';
const res = await API.get( const res = await API.get(
`/api/analytics/channel-consumption?${queryParams}${separator}limit=30`, `/api/analytics/channel-consumption?${queryParams}${separator}limit=30`,
{ signal },
); );
if (signal.aborted) return;
if (res.data.success) { if (res.data.success) {
setChannelConsumption(res.data.data || []); setChannelConsumption(res.data.data || []);
} }
} catch (error) { } catch (error) {
console.error('获取渠道消耗排行失败:', error); if (!signal.aborted) console.error('获取渠道消耗排行失败:', error);
} }
}, },
[buildQueryParams], [buildQueryParams],
@@ -137,18 +151,20 @@ export const useAnalyticsData = (active = true) => {
// 获取用户排行 // 获取用户排行
const fetchUserRanking = useCallback( const fetchUserRanking = useCallback(
async (currentPeriod, currentDateRange) => { async (currentPeriod, currentDateRange, signal) => {
try { try {
const queryParams = buildQueryParams(currentPeriod, currentDateRange); const queryParams = buildQueryParams(currentPeriod, currentDateRange);
const separator = queryParams ? '&' : ''; const separator = queryParams ? '&' : '';
const res = await API.get( const res = await API.get(
`/api/analytics/user-ranking?${queryParams}${separator}limit=100`, `/api/analytics/user-ranking?${queryParams}${separator}limit=100`,
{ signal },
); );
if (signal.aborted) return;
if (res.data.success) { if (res.data.success) {
setUserRanking(res.data.data || []); setUserRanking(res.data.data || []);
} }
} catch (error) { } catch (error) {
console.error('获取用户排行失败:', error); if (!signal.aborted) console.error('获取用户排行失败:', error);
} }
}, },
[buildQueryParams], [buildQueryParams],
@@ -159,15 +175,18 @@ export const useAnalyticsData = (active = true) => {
// 获取每日统计 // 获取每日统计
const fetchDailyStats = useCallback( const fetchDailyStats = useCallback(
async (currentPeriod, currentDateRange) => { async (currentPeriod, currentDateRange, signal) => {
try { try {
const queryParams = buildQueryParams(currentPeriod, currentDateRange); const queryParams = buildQueryParams(currentPeriod, currentDateRange);
const res = await API.get(`/api/analytics/daily-stats?${queryParams}`); const res = await API.get(`/api/analytics/daily-stats?${queryParams}`, {
signal,
});
if (signal.aborted) return;
if (res.data.success) { if (res.data.success) {
setDailyStats(res.data.data || []); setDailyStats(res.data.data || []);
} }
} catch (error) { } catch (error) {
console.error('获取每日统计失败:', error); if (!signal.aborted) console.error('获取每日统计失败:', error);
} }
}, },
[buildQueryParams], [buildQueryParams],
@@ -175,18 +194,20 @@ export const useAnalyticsData = (active = true) => {
// 获取用户充值排行 // 获取用户充值排行
const fetchUserTopupRanking = useCallback( const fetchUserTopupRanking = useCallback(
async (currentPeriod, currentDateRange) => { async (currentPeriod, currentDateRange, signal) => {
try { try {
const queryParams = buildQueryParams(currentPeriod, currentDateRange); const queryParams = buildQueryParams(currentPeriod, currentDateRange);
const separator = queryParams ? '&' : ''; const separator = queryParams ? '&' : '';
const res = await API.get( const res = await API.get(
`/api/analytics/user-topup-ranking?${queryParams}${separator}limit=50`, `/api/analytics/user-topup-ranking?${queryParams}${separator}limit=50`,
{ signal },
); );
if (signal.aborted) return;
if (res.data.success) { if (res.data.success) {
setUserTopupRanking(res.data.data || []); setUserTopupRanking(res.data.data || []);
} }
} catch (error) { } catch (error) {
console.error('获取用户充值排行失败:', error); if (!signal.aborted) console.error('获取用户充值排行失败:', error);
} }
}, },
[buildQueryParams], [buildQueryParams],
@@ -198,23 +219,28 @@ export const useAnalyticsData = (active = true) => {
// 返回的 Promise 仍然等齐全部 7 个请求,刷新按钮据此显示完整进度。 // 返回的 Promise 仍然等齐全部 7 个请求,刷新按钮据此显示完整进度。
const refreshAll = useCallback( const refreshAll = useCallback(
async (currentPeriod, currentDateRange, force = false) => { async (currentPeriod, currentDateRange, force = false) => {
const overviewTask = fetchOverview(force); cancelQuery();
const controller = new AbortController();
activeRequest.current = controller;
const { signal } = controller;
const overviewTask = fetchOverview(force, signal);
setLoading(true); setLoading(true);
try { try {
await Promise.all([ await Promise.all([
fetchUserTrend(currentPeriod, currentDateRange), fetchUserTrend(currentPeriod, currentDateRange, signal),
fetchFinanceTrend(currentPeriod, currentDateRange), fetchFinanceTrend(currentPeriod, currentDateRange, signal),
fetchChannelConsumption(currentPeriod, currentDateRange), fetchChannelConsumption(currentPeriod, currentDateRange, signal),
fetchUserRanking(currentPeriod, currentDateRange), fetchUserRanking(currentPeriod, currentDateRange, signal),
fetchDailyStats(currentPeriod, currentDateRange), fetchDailyStats(currentPeriod, currentDateRange, signal),
fetchUserTopupRanking(currentPeriod, currentDateRange), fetchUserTopupRanking(currentPeriod, currentDateRange, signal),
]); ]);
} finally { } finally {
setLoading(false); if (!signal.aborted) setLoading(false);
} }
await overviewTask; await overviewTask;
}, },
[ [
cancelQuery,
fetchOverview, fetchOverview,
fetchUserTrend, fetchUserTrend,
fetchFinanceTrend, fetchFinanceTrend,
@@ -225,29 +251,37 @@ export const useAnalyticsData = (active = true) => {
], ],
); );
// 切换时间周期 const { scheduleSearch, submitSearch, cancelPendingSearch } = useFilterSearch(
const handlePeriodChange = useCallback( (conditions) =>
(newPeriod) => { refreshAll(
setPeriod(newPeriod); conditions?.period ?? period,
if (newPeriod !== 'custom') { conditions?.dateRange ?? dateRange,
setDateRange([null, null]); !conditions,
refreshAll(newPeriod, [null, null]); ),
} cancelQuery,
},
[refreshAll],
); );
// 更新自定义日期范围 const handlePeriodChange = (newPeriod) => {
const handleDateRangeChange = useCallback( setPeriod(newPeriod);
(newRange) => { if (newPeriod !== 'custom') {
setDateRange(newRange); const emptyRange = [null, null];
if (newRange[0] && newRange[1]) { setDateRange(emptyRange);
setPeriod('custom'); scheduleSearch({ period: newPeriod, dateRange: emptyRange });
refreshAll('custom', newRange); }
} };
},
[refreshAll], const handleDateRangeChange = (newRange) => {
); const range = newRange ?? [null, null];
setDateRange(range);
scheduleSearch({ period: 'custom', dateRange: range });
};
const resetFilters = () => {
cancelPendingSearch();
setPeriod('today');
setDateRange([null, null]);
void refreshAll('today', [null, null]);
};
// 懒加载:仅在 active 第一次为 true 时拉数据。 // 懒加载:仅在 active 第一次为 true 时拉数据。
// 由调用方传入 activeTab === 'operations',避免在 audit / risk Tab 时白白发起 8 个 API。 // 由调用方传入 activeTab === 'operations',避免在 audit / risk Tab 时白白发起 8 个 API。
@@ -273,7 +307,8 @@ export const useAnalyticsData = (active = true) => {
dateRange, dateRange,
setPeriod: handlePeriodChange, setPeriod: handlePeriodChange,
setDateRange: handleDateRangeChange, setDateRange: handleDateRangeChange,
refreshAll, submitSearch,
resetFilters,
}; };
}; };
+53 -40
View File
@@ -63,7 +63,6 @@ export const useChannelsData = () => {
// Model test states // Model test states
const [showModelTestModal, setShowModelTestModal] = useState(false); const [showModelTestModal, setShowModelTestModal] = useState(false);
const [currentTestChannel, setCurrentTestChannel] = useState(null); const [currentTestChannel, setCurrentTestChannel] = useState(null);
const [modelSearchKeyword, setModelSearchKeyword] = useState('');
const [modelTestResults, setModelTestResults] = useState({}); const [modelTestResults, setModelTestResults] = useState({});
const [testingModels, setTestingModels] = useState(new Set()); const [testingModels, setTestingModels] = useState(new Set());
const [selectedModelKeys, setSelectedModelKeys] = useState([]); const [selectedModelKeys, setSelectedModelKeys] = useState([]);
@@ -290,6 +289,7 @@ export const useChannelsData = () => {
enableTagMode, enableTagMode,
typeKey = activeTypeKey, typeKey = activeTypeKey,
statusF, statusF,
signal,
) => { ) => {
if (statusF === undefined) statusF = statusFilter; if (statusF === undefined) statusF = statusFilter;
@@ -303,41 +303,51 @@ export const useChannelsData = () => {
page, page,
pageSize, pageSize,
idSort, idSort,
signal,
); );
setLoading(false); setLoading(false);
return; return;
} }
const reqId = ++requestCounter.current; const reqId = ++requestCounter.current;
setSearching(false);
setLoading(true); setLoading(true);
const typeParam = typeKey !== 'all' ? `&type=${typeKey}` : ''; const typeParam = typeKey !== 'all' ? `&type=${typeKey}` : '';
const statusParam = statusF !== 'all' ? `&status=${statusF}` : ''; const statusParam = statusF !== 'all' ? `&status=${statusF}` : '';
const res = await API.get( try {
`/api/channel/?p=${page}&page_size=${pageSize}&id_sort=${idSort}&tag_mode=${enableTagMode}${typeParam}${statusParam}`, const res = await API.get(
); `/api/channel/?p=${page}&page_size=${pageSize}&id_sort=${idSort}&tag_mode=${enableTagMode}${typeParam}${statusParam}`,
{ signal },
);
if (res === undefined || reqId !== requestCounter.current) { if (
return; res === undefined ||
} signal?.aborted ||
reqId !== requestCounter.current
const { success, message, data } = res.data; ) {
if (success) { return;
const { items, total, type_counts } = data;
if (type_counts) {
const sumAll = Object.values(type_counts).reduce(
(acc, v) => acc + v,
0,
);
setTypeCounts({ ...type_counts, all: sumAll });
} }
setChannelFormat(items, enableTagMode);
setChannelCount(total); const { success, message, data } = res.data;
// 获取日消耗数据 if (success) {
fetchDailyQuotaInfo(items); const { items, total, type_counts } = data;
} else { if (type_counts) {
showError(message); const sumAll = Object.values(type_counts).reduce(
(acc, v) => acc + v,
0,
);
setTypeCounts({ ...type_counts, all: sumAll });
}
setChannelFormat(items, enableTagMode);
setChannelCount(total);
// 获取日消耗数据
fetchDailyQuotaInfo(items);
} else {
showError(message);
}
} finally {
if (reqId === requestCounter.current) setLoading(false);
} }
setLoading(false);
}; };
// Search channels // Search channels
@@ -348,23 +358,28 @@ export const useChannelsData = () => {
page = 1, page = 1,
pageSz = pageSize, pageSz = pageSize,
sortFlag = idSort, sortFlag = idSort,
signal,
) => { ) => {
const { searchKeyword, searchGroup, searchModel } = getFormValues(); const { searchKeyword, searchGroup, searchModel } = getFormValues();
if (searchKeyword === '' && searchGroup === '' && searchModel === '') {
await loadChannels(
page,
pageSz,
sortFlag,
enableTagMode,
typeKey,
statusF,
signal,
);
return;
}
const reqId = ++requestCounter.current;
setLoading(false);
setSearching(true); setSearching(true);
try { try {
if (searchKeyword === '' && searchGroup === '' && searchModel === '') {
await loadChannels(
page,
pageSz,
sortFlag,
enableTagMode,
typeKey,
statusF,
);
return;
}
const res = await API.get('/api/channel/search', { const res = await API.get('/api/channel/search', {
signal,
params: { params: {
keyword: searchKeyword, keyword: searchKeyword,
group: searchGroup, group: searchGroup,
@@ -377,6 +392,7 @@ export const useChannelsData = () => {
status: statusF === 'all' ? undefined : statusF, status: statusF === 'all' ? undefined : statusF,
}, },
}); });
if (signal?.aborted || reqId !== requestCounter.current) return;
const { success, message, data } = res.data; const { success, message, data } = res.data;
if (success) { if (success) {
const { items = [], total = 0, type_counts = {} } = data; const { items = [], total = 0, type_counts = {} } = data;
@@ -394,7 +410,7 @@ export const useChannelsData = () => {
showError(message); showError(message);
} }
} finally { } finally {
setSearching(false); if (reqId === requestCounter.current) setSearching(false);
} }
}; };
@@ -1060,7 +1076,6 @@ export const useChannelsData = () => {
} }
setShowModelTestModal(false); setShowModelTestModal(false);
setModelSearchKeyword('');
setIsBatchTesting(false); setIsBatchTesting(false);
setTestingModels(new Set()); setTestingModels(new Set());
setSelectedModelKeys([]); setSelectedModelKeys([]);
@@ -1153,8 +1168,6 @@ export const useChannelsData = () => {
setShowModelTestModal, setShowModelTestModal,
currentTestChannel, currentTestChannel,
setCurrentTestChannel, setCurrentTestChannel,
modelSearchKeyword,
setModelSearchKeyword,
modelTestResults, modelTestResults,
testingModels, testingModels,
selectedModelKeys, selectedModelKeys,
+54 -7
View File
@@ -1,15 +1,62 @@
import { useEffect, useRef } from 'react';
import { useDebouncedCallback } from 'use-debounce'; import { useDebouncedCallback } from 'use-debounce';
import { showError } from '../../helpers';
export function useFilterSearch(search) { export function useFilterSearch(search, cancelQuery) {
const scheduleSearch = useDebouncedCallback(search, 300); const request = useRef(null);
const submitSearch = () => { const run = (value) => {
scheduleSearch.cancel(); const controller = new AbortController();
return search(); const current = { controller };
request.current = current;
current.result = (async () => {
try {
return await search(value, controller.signal);
} catch (error) {
if (!controller.signal.aborted && !error?.isAxiosError)
showError(error);
} finally {
if (request.current === current) request.current = null;
}
})();
return current.result;
};
const debouncedSearch = useDebouncedCallback(run, 300);
const cancelRequest = () => {
request.current?.controller.abort();
request.current = null;
};
useEffect(
() => () => {
debouncedSearch.cancel();
cancelRequest();
},
[debouncedSearch],
);
const scheduleSearch = (value) => {
cancelRequest();
cancelQuery?.();
debouncedSearch(value);
}; };
return { return {
scheduleSearch, scheduleSearch,
submitSearch, changeFilter(setValue) {
cancelPendingSearch: scheduleSearch.cancel, return (value) => {
setValue(value);
scheduleSearch();
};
},
submitSearch() {
if (debouncedSearch.isPending()) return debouncedSearch.flush();
return request.current?.result ?? run();
},
cancelPendingSearch() {
debouncedSearch.cancel();
cancelRequest();
cancelQuery?.();
},
}; };
} }
+26
View File
@@ -0,0 +1,26 @@
import { useEffect, useMemo, useState } from 'react';
import { filterTableRows } from '../../components/common/table/filterTableRows';
export function useFilteredTableRows(items, matches) {
const [filtered, setFiltered] = useState([]);
const small = items.length <= 500;
useEffect(() => {
if (small) return;
const controller = new AbortController();
const { signal } = controller;
void filterTableRows(items, matches, signal)
.then((result) => {
if (!signal.aborted) setFiltered(result);
})
.catch((error) => {
if (!signal.aborted) throw error;
});
return () => controller.abort();
}, [items, matches, small]);
return useMemo(
() => (small ? items.filter(matches) : filtered),
[filtered, items, matches, small],
);
}
+27
View File
@@ -0,0 +1,27 @@
import { useState } from 'react';
import { useFilterSearch } from './useFilterSearch';
export function useLocalTableFilters(defaults) {
const [draft, setDraft] = useState(defaults);
const [applied, setApplied] = useState(defaults);
const { scheduleSearch, submitSearch, cancelPendingSearch } = useFilterSearch(
(filters) => setApplied(filters ?? draft),
);
const changeFilters = (fields) => {
setDraft((current) => ({ ...current, ...fields }));
scheduleSearch();
};
return {
draft,
applied,
changeFilters,
submitSearch,
resetFilters() {
cancelPendingSearch();
setDraft(defaults);
setApplied(defaults);
},
};
}
+21
View File
@@ -0,0 +1,21 @@
import { useCallback, useEffect, useRef } from 'react';
export function useTableFilterQuery(query, version) {
const activeRequest = useRef(null);
const cancelQuery = useCallback(() => activeRequest.current?.abort(), []);
const reloadQuery = useCallback(() => {
cancelQuery();
const controller = new AbortController();
activeRequest.current = controller;
return query(controller.signal);
}, [cancelQuery, query]);
useEffect(() => {
void reloadQuery();
return cancelQuery;
// The version changes when the caller refreshes with the same conditions.
}, [cancelQuery, reloadQuery, version]);
return { cancelQuery, reloadQuery };
}
+7 -6
View File
@@ -202,7 +202,7 @@ export const useMjLogsData = () => {
// Load logs function // Load logs function
const listRequestIdRef = useRef(0); const listRequestIdRef = useRef(0);
const loadLogs = async (page = 1, size = pageSize) => { const loadLogs = async (page = 1, size = pageSize, signal) => {
const requestId = ++listRequestIdRef.current; const requestId = ++listRequestIdRef.current;
setLoading(true); setLoading(true);
const { channel_id, mj_id, start_timestamp, end_timestamp } = const { channel_id, mj_id, start_timestamp, end_timestamp } =
@@ -213,16 +213,17 @@ export const useMjLogsData = () => {
? `/api/mj/?p=${page}&page_size=${size}&channel_id=${channel_id}&mj_id=${mj_id}&start_timestamp=${localStartTimestamp}&end_timestamp=${localEndTimestamp}` ? `/api/mj/?p=${page}&page_size=${size}&channel_id=${channel_id}&mj_id=${mj_id}&start_timestamp=${localStartTimestamp}&end_timestamp=${localEndTimestamp}`
: `/api/mj/self/?p=${page}&page_size=${size}&mj_id=${mj_id}&start_timestamp=${localStartTimestamp}&end_timestamp=${localEndTimestamp}`; : `/api/mj/self/?p=${page}&page_size=${size}&mj_id=${mj_id}&start_timestamp=${localStartTimestamp}&end_timestamp=${localEndTimestamp}`;
try { try {
const res = await API.get(url); const res = await API.get(url, { signal });
if (requestId !== listRequestIdRef.current) return; if (requestId !== listRequestIdRef.current || signal?.aborted) return;
const { success, message, data } = res.data; const { success, message, data } = res.data;
if (success) { if (success) {
syncPageData(data); syncPageData(data);
if (signal) setActivePage(page);
} else { } else {
showError(message); showError(message);
} }
} catch (error) { } catch (error) {
if (requestId === listRequestIdRef.current) { if (requestId === listRequestIdRef.current && !signal?.aborted) {
showError(error.message || error); showError(error.message || error);
} }
} finally { } finally {
@@ -241,8 +242,8 @@ export const useMjLogsData = () => {
}; };
// Refresh function // Refresh function
const refresh = async () => { const refresh = async ({ page = 1, signal } = {}) => {
await loadLogs(1, pageSize); await loadLogs(page, pageSize, signal);
}; };
// Copy text function // Copy text function
+55 -56
View File
@@ -130,25 +130,18 @@ export const useModelsData = () => {
} }
}; };
// Load models data const listRequest = useRef(0);
const loadModels = async ( const fetchModels = async (url, params, page, signal, isSearch = false) => {
page = 1, const id = ++listRequest.current;
size = pageSize, setLoading(!isSearch);
vendorKey = activeVendorKey, setSearching(isSearch);
) => {
setLoading(true);
try { try {
let url = `/api/models/?p=${page}&page_size=${size}`; const res = await API.get(url, { params, signal });
if (vendorKey && vendorKey !== 'all') { if (signal?.aborted || id !== listRequest.current) return;
// Filter by vendor ID
url = `/api/models/search?vendor=${vendorKey}&p=${page}&page_size=${size}`;
}
const res = await API.get(url);
const { success, message, data } = res.data; const { success, message, data } = res.data;
if (success) { if (success) {
const newPageData = extractItems(data); const newPageData = extractItems(data);
setActivePage(data.page || page); setActivePage(signal ? page : data.page || page);
setModelCount(data.total || newPageData.length); setModelCount(data.total || newPageData.length);
setModelFormat(newPageData); setModelFormat(newPageData);
} else { } else {
@@ -156,16 +149,39 @@ export const useModelsData = () => {
setModels([]); setModels([]);
} }
} catch (error) { } catch (error) {
console.error(error); if (signal?.aborted || id !== listRequest.current) return;
showError(t('获取模型列表失败')); if (!error.isAxiosError)
showError(t(isSearch ? '搜索模型失败' : '获取模型列表失败'));
setModels([]); setModels([]);
} finally {
if (id === listRequest.current) {
setLoading(false);
setSearching(false);
}
} }
setLoading(false);
}; };
// Refresh data const loadModels = (
page = 1,
size = pageSize,
vendorKey = activeVendorKey,
signal,
) => {
const vendor = vendorKey && vendorKey !== 'all' ? vendorKey : undefined;
return fetchModels(
vendor ? '/api/models/search' : '/api/models/',
{
p: page,
page_size: size,
vendor,
},
page,
signal,
);
};
const refresh = async (page = activePage) => { const refresh = async (page = activePage) => {
await Promise.all([loadModels(page, pageSize), loadVendorCounts()]); await Promise.all([searchModels(page, pageSize), loadVendorCounts()]);
}; };
// Sync upstream models/vendors for missing models only // Sync upstream models/vendors for missing models only
@@ -255,41 +271,24 @@ export const useModelsData = () => {
} }
}; };
// Search models with keyword and vendor const searchModels = (page = activePage, size = pageSize, signal) => {
const searchModels = async () => { const { searchKeyword, searchVendor, searchCategory } = getFormValues();
const { if (!searchKeyword && !searchVendor && !searchCategory) {
searchKeyword = '', return loadModels(page, size, activeVendorKey, signal);
searchVendor = '',
searchCategory = '',
} = getFormValues();
if (searchKeyword === '' && searchVendor === '' && searchCategory === '') {
// If all filters are blank, load models instead
await loadModels(1, pageSize);
return;
} }
return fetchModels(
setSearching(true); '/api/models/search',
try { {
const res = await API.get( keyword: searchKeyword,
`/api/models/search?keyword=${searchKeyword}&vendor=${searchVendor}&category=${searchCategory}&p=1&page_size=${pageSize}`, vendor: searchVendor,
); category: searchCategory,
const { success, message, data } = res.data; p: page,
if (success) { page_size: size,
const newPageData = extractItems(data); },
setActivePage(data.page || 1); page,
setModelCount(data.total || newPageData.length); signal,
setModelFormat(newPageData); true,
} else { );
showError(message);
setModels([]);
}
} catch (error) {
console.error(error);
showError(t('搜索模型失败'));
setModels([]);
}
setSearching(false);
}; };
// Manage model (enable/disable/delete) // Manage model (enable/disable/delete)
@@ -333,7 +332,7 @@ export const useModelsData = () => {
// Handle page change // Handle page change
const handlePageChange = (page) => { const handlePageChange = (page) => {
setActivePage(page); setActivePage(page);
loadModels(page, pageSize, activeVendorKey); searchModels(page, pageSize);
}; };
// Reload models when activeVendorKey changes // Reload models when activeVendorKey changes
@@ -346,7 +345,7 @@ export const useModelsData = () => {
const handlePageSizeChange = async (size) => { const handlePageSizeChange = async (size) => {
setPageSize(size); setPageSize(size);
setActivePage(1); setActivePage(1);
await loadModels(1, size, activeVendorKey); await searchModels(1, size);
}; };
// Handle row click and styling // Handle row click and styling
+37 -13
View File
@@ -117,7 +117,7 @@ export function useOrgAuditLogs(orgId) {
}, [orgId]); }, [orgId]);
const fetch = useCallback( const fetch = useCallback(
async (page = 1, pageSize = 20, action = '') => { async (page = 1, pageSize = 20, action = '', signal) => {
if (!orgId) return; if (!orgId) return;
const requestOrgId = orgId; const requestOrgId = orgId;
const seq = ++seqRef.current; const seq = ++seqRef.current;
@@ -126,8 +126,10 @@ export function useOrgAuditLogs(orgId) {
const res = await API.get('/api/org/audit', { const res = await API.get('/api/org/audit', {
headers: getOrgHeaders(requestOrgId), headers: getOrgHeaders(requestOrgId),
params: { p: page, page_size: pageSize, action }, params: { p: page, page_size: pageSize, action },
signal,
}); });
if ( if (
!signal?.aborted &&
seq === seqRef.current && seq === seqRef.current &&
requestOrgId === orgRef.current && requestOrgId === orgRef.current &&
res.data.success res.data.success
@@ -136,7 +138,12 @@ export function useOrgAuditLogs(orgId) {
setTotal(res.data.data?.total || 0); setTotal(res.data.data?.total || 0);
} }
} catch (err) { } catch (err) {
if (seq === seqRef.current && requestOrgId === orgRef.current) if (
!signal?.aborted &&
seq === seqRef.current &&
requestOrgId === orgRef.current &&
!err.isAxiosError
)
showError(err.message); showError(err.message);
} finally { } finally {
if (seq === seqRef.current && requestOrgId === orgRef.current) if (seq === seqRef.current && requestOrgId === orgRef.current)
@@ -173,6 +180,7 @@ export function useOrgPromptRecords(orgId) {
page = 1, page = 1,
pageSize = 20, pageSize = 20,
{ memberId, modelName, keyword, startTimestamp, endTimestamp } = {}, { memberId, modelName, keyword, startTimestamp, endTimestamp } = {},
signal,
) => { ) => {
if (!orgId) return; if (!orgId) return;
const seq = ++seqRef.current; const seq = ++seqRef.current;
@@ -189,8 +197,9 @@ export function useOrgPromptRecords(orgId) {
const res = await API.get('/api/org/prompt-archive/records', { const res = await API.get('/api/org/prompt-archive/records', {
headers: getOrgHeaders(orgId), headers: getOrgHeaders(orgId),
params, params,
signal,
}); });
if (seq !== seqRef.current) return; if (signal?.aborted || seq !== seqRef.current) return;
if (res.data.success) { if (res.data.success) {
setRecords(res.data.data?.items || []); setRecords(res.data.data?.items || []);
setTotal(res.data.data?.total || 0); setTotal(res.data.data?.total || 0);
@@ -200,7 +209,7 @@ export function useOrgPromptRecords(orgId) {
setError(res.data.message || i18next.t('查询失败')); setError(res.data.message || i18next.t('查询失败'));
} }
} catch (err) { } catch (err) {
if (seq !== seqRef.current) return; if (signal?.aborted || seq !== seqRef.current) return;
setRecords([]); setRecords([]);
setTotal(0); setTotal(0);
setError(err.message); setError(err.message);
@@ -222,9 +231,11 @@ export function useOrgMemberLogs(orgId) {
const [total, setTotal] = useState(0); const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const request = useRef(0);
const fetch = useCallback( const fetch = useCallback(
async (page = 1, pageSize = 20, filters = {}) => { async (page = 1, pageSize = 20, filters = {}, signal) => {
if (!orgId) return; if (!orgId) return;
const id = ++request.current;
setLoading(true); setLoading(true);
try { try {
const params = { const params = {
@@ -236,7 +247,9 @@ export function useOrgMemberLogs(orgId) {
const res = await API.get('/api/org/logs', { const res = await API.get('/api/org/logs', {
headers: getOrgHeaders(orgId), headers: getOrgHeaders(orgId),
params, params,
signal,
}); });
if (signal?.aborted || id !== request.current) return;
if (res.data.success) { if (res.data.success) {
setLogs(res.data.data?.items || []); setLogs(res.data.data?.items || []);
// 后端在翻页(page>1)时跳过 COUNT 并返回 total=-1,此处保留首页已知总数,避免分页器异常 // 后端在翻页(page>1)时跳过 COUNT 并返回 total=-1,此处保留首页已知总数,避免分页器异常
@@ -250,9 +263,10 @@ export function useOrgMemberLogs(orgId) {
showError(res.data.message || i18next.t('加载消耗明细失败')); showError(res.data.message || i18next.t('加载消耗明细失败'));
} }
} catch (err) { } catch (err) {
showError(err.message); if (!signal?.aborted && id === request.current && !err.isAxiosError)
showError(err.message);
} finally { } finally {
setLoading(false); if (id === request.current) setLoading(false);
} }
}, },
[orgId], [orgId],
@@ -271,9 +285,11 @@ export function useOrgLogsStat(orgId) {
}); });
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const request = useRef(0);
const fetch = useCallback( const fetch = useCallback(
async (filters = {}, noCache = false) => { async (filters = {}, noCache = false, signal) => {
if (!orgId) return; if (!orgId) return;
const id = ++request.current;
setLoading(true); setLoading(true);
try { try {
const params = buildOrgLogFilters(filters); const params = buildOrgLogFilters(filters);
@@ -282,7 +298,9 @@ export function useOrgLogsStat(orgId) {
const res = await API.get('/api/org/logs/stat', { const res = await API.get('/api/org/logs/stat', {
headers: getOrgHeaders(orgId), headers: getOrgHeaders(orgId),
params, params,
signal,
}); });
if (signal?.aborted || id !== request.current) return;
if (res.data.success) { if (res.data.success) {
setStat( setStat(
res.data.data || { res.data.data || {
@@ -302,9 +320,10 @@ export function useOrgLogsStat(orgId) {
showError(res.data.message || i18next.t('加载消耗统计失败')); showError(res.data.message || i18next.t('加载消耗统计失败'));
} }
} catch (err) { } catch (err) {
showError(err.message); if (!signal?.aborted && id === request.current && !err.isAxiosError)
showError(err.message);
} finally { } finally {
setLoading(false); if (id === request.current) setLoading(false);
} }
}, },
[orgId], [orgId],
@@ -318,9 +337,11 @@ export function useOrgMemberRanking(orgId) {
const [ranking, setRanking] = useState([]); const [ranking, setRanking] = useState([]);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const request = useRef(0);
const fetch = useCallback( const fetch = useCallback(
async ({ limit, ...filters } = {}, noCache = false) => { async ({ limit, ...filters } = {}, noCache = false, signal) => {
if (!orgId) return; if (!orgId) return;
const id = ++request.current;
setLoading(true); setLoading(true);
try { try {
const params = buildOrgLogFilters(filters); const params = buildOrgLogFilters(filters);
@@ -330,7 +351,9 @@ export function useOrgMemberRanking(orgId) {
const res = await API.get('/api/org/logs/ranking', { const res = await API.get('/api/org/logs/ranking', {
headers: getOrgHeaders(orgId), headers: getOrgHeaders(orgId),
params, params,
signal,
}); });
if (signal?.aborted || id !== request.current) return;
if (res.data.success) { if (res.data.success) {
setRanking(res.data.data || []); setRanking(res.data.data || []);
} else { } else {
@@ -338,9 +361,10 @@ export function useOrgMemberRanking(orgId) {
showError(res.data.message || i18next.t('加载成员排行失败')); showError(res.data.message || i18next.t('加载成员排行失败'));
} }
} catch (err) { } catch (err) {
showError(err.message); if (!signal?.aborted && id === request.current && !err.isAxiosError)
showError(err.message);
} finally { } finally {
setLoading(false); if (id === request.current) setLoading(false);
} }
}, },
[orgId], [orgId],
+41 -23
View File
@@ -1,3 +1,4 @@
import { useFilterSearch } from '../common/useFilterSearch';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { API } from '../../helpers'; import { API } from '../../helpers';
import { import {
@@ -117,13 +118,14 @@ const useQualityDashboard = (scope, enabled, orgId) => {
[scope, orgId], [scope, orgId],
); );
const [filters, setFiltersState] = useState(readFiltersFromURL); const [filters, setFiltersState] = useState(readFiltersFromURL);
const [appliedFilters, setAppliedFilters] = useState(filters);
const [options, setOptions] = useState({}); const [options, setOptions] = useState({});
const [summary, setSummary] = useState(null); const [summary, setSummary] = useState(null);
const [trend, setTrend] = useState(null); const [trend, setTrend] = useState(null);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [error, setError] = useState(''); const [error, setError] = useState('');
const [refreshKey, setRefreshKey] = useState(0); const [refreshKey, setRefreshKey] = useState(0);
const seq = useRef(0); const activeRequest = useRef(null);
// 统一把 HTTP 错误与 success:false 归一成带 code 的 Error,由看板就地展示可读文案 // 统一把 HTTP 错误与 success:false 归一成带 code 的 Error,由看板就地展示可读文案
// (skipErrorHandler:不走全局 toast,避免同一错误弹两次) // (skipErrorHandler:不走全局 toast,避免同一错误弹两次)
@@ -149,9 +151,14 @@ const useQualityDashboard = (scope, enabled, orgId) => {
}; };
const get = useCallback( const get = useCallback(
(path, params) => (path, params, signal) =>
unwrap( unwrap(
API.get(`${base}${path}`, { params, headers, skipErrorHandler: true }), API.get(`${base}${path}`, {
params,
headers,
signal,
skipErrorHandler: true,
}),
), ),
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
[base, headers], [base, headers],
@@ -171,26 +178,31 @@ const useQualityDashboard = (scope, enabled, orgId) => {
[base, headers], [base, headers],
); );
const setFilters = useCallback((patch) => { const { scheduleSearch, submitSearch, cancelPendingSearch } = useFilterSearch(
setFiltersState((prev) => { () => {
const next = { ...prev, ...patch }; writeFiltersToURL(filters);
writeFiltersToURL(next); setAppliedFilters(filters);
return next; setRefreshKey((key) => key + 1);
}); },
}, []); () => activeRequest.current?.abort(),
);
const resetFilters = useCallback(() => { const setFilters = (patch) => {
setFiltersState((prev) => ({ ...prev, ...patch }));
scheduleSearch();
};
const resetFilters = () => {
cancelPendingSearch();
writeFiltersToURL(DEFAULT_FILTERS); writeFiltersToURL(DEFAULT_FILTERS);
setFiltersState({ ...DEFAULT_FILTERS }); setFiltersState({ ...DEFAULT_FILTERS });
}, []); setAppliedFilters({ ...DEFAULT_FILTERS });
};
const refresh = useCallback(() => setRefreshKey((k) => k + 1), []);
const params = useMemo( const params = useMemo(
() => buildQualityParams(filters), () => buildQualityParams(appliedFilters),
// refreshKey 参与依赖:预设时间范围在刷新时重新以当前时刻为终点
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
[filters, refreshKey], [appliedFilters, refreshKey],
); );
useEffect(() => { useEffect(() => {
@@ -202,24 +214,30 @@ const useQualityDashboard = (scope, enabled, orgId) => {
useEffect(() => { useEffect(() => {
if (!enabled) return; if (!enabled) return;
const current = ++seq.current; const controller = new AbortController();
activeRequest.current = controller;
const { signal } = controller;
setLoading(true); setLoading(true);
setError(''); setError('');
Promise.all([get('/summary', params), get('/trend', params)]) Promise.all([
get('/summary', params, signal),
get('/trend', params, signal),
])
.then(([s, tr]) => { .then(([s, tr]) => {
if (current !== seq.current) return; if (signal.aborted) return;
setSummary(s); setSummary(s);
setTrend(tr); setTrend(tr);
}) })
.catch((err) => { .catch((err) => {
if (current !== seq.current) return; if (signal.aborted) return;
setSummary(null); setSummary(null);
setTrend(null); setTrend(null);
setError(err.code || err.message || 'query_failed'); setError(err.code || err.message || 'query_failed');
}) })
.finally(() => { .finally(() => {
if (current === seq.current) setLoading(false); if (activeRequest.current === controller) setLoading(false);
}); });
return () => controller.abort();
}, [enabled, get, params]); }, [enabled, get, params]);
return { return {
@@ -235,7 +253,7 @@ const useQualityDashboard = (scope, enabled, orgId) => {
trend, trend,
loading, loading,
error, error,
refresh, refresh: submitSearch,
refreshKey, refreshKey,
get, get,
send, send,
+19 -12
View File
@@ -54,59 +54,64 @@ export const useRedemptionsData = () => {
}; };
// Load redemption list // Load redemption list
const loadRedemptions = async (page = 1, pageSize) => { const loadRedemptions = async (page = 1, pageSize, signal) => {
setLoading(true); setLoading(true);
try { try {
const res = await API.get( const res = await API.get(
`/api/redemption/?p=${page}&page_size=${pageSize}`, `/api/redemption/?p=${page}&page_size=${pageSize}`,
{ signal },
); );
if (signal?.aborted) return;
const { success, message, data } = res.data; const { success, message, data } = res.data;
if (success) { if (success) {
const newPageData = data.items; const newPageData = data.items;
setActivePage(data.page <= 0 ? 1 : data.page); setActivePage(signal ? page : data.page <= 0 ? 1 : data.page);
setTokenCount(data.total); setTokenCount(data.total);
setRedemptionFormat(newPageData); setRedemptionFormat(newPageData);
} else { } else {
showError(message); showError(message);
} }
} catch (error) { } catch (error) {
showError(error.message); if (!signal?.aborted && !error.isAxiosError) showError(error.message);
} finally {
setLoading(false);
} }
setLoading(false);
}; };
// Search redemption codes // Search redemption codes
const loadSearchResults = async (keyword, page, size) => { const loadSearchResults = async (keyword, page, size, signal) => {
setSearching(true); setSearching(true);
try { try {
const res = await API.get('/api/redemption/search', { const res = await API.get('/api/redemption/search', {
params: { keyword, p: page, page_size: size }, params: { keyword, p: page, page_size: size },
signal,
}); });
if (signal?.aborted) return;
const { success, message, data } = res.data; const { success, message, data } = res.data;
if (success) { if (success) {
const newPageData = data.items; const newPageData = data.items;
setActivePage(data.page || 1); setActivePage(signal ? page : data.page || 1);
setTokenCount(data.total); setTokenCount(data.total);
setRedemptionFormat(newPageData); setRedemptionFormat(newPageData);
} else { } else {
showError(message); showError(message);
} }
} catch (error) { } catch (error) {
showError(error.message); if (!signal?.aborted && !error.isAxiosError) showError(error.message);
} finally { } finally {
setSearching(false); setSearching(false);
} }
}; };
const loadPage = (page, size, keyword = appliedKeyword) => const loadPage = (page, size, keyword = appliedKeyword, signal) =>
keyword keyword
? loadSearchResults(keyword, page, size) ? loadSearchResults(keyword, page, size, signal)
: loadRedemptions(page, size); : loadRedemptions(page, size, signal);
const searchRedemptions = () => { const searchRedemptions = (page = activePage, signal) => {
const { searchKeyword } = getFormValues(); const { searchKeyword } = getFormValues();
setAppliedKeyword(searchKeyword); setAppliedKeyword(searchKeyword);
return loadPage(1, pageSize, searchKeyword); return loadPage(page, pageSize, searchKeyword, signal);
}; };
// Manage redemption codes (CRUD operations) // Manage redemption codes (CRUD operations)
@@ -171,6 +176,8 @@ export const useRedemptionsData = () => {
// Row selection configuration // Row selection configuration
const rowSelection = { const rowSelection = {
selectedRowKeys: selectedKeys.map((record) => record.key),
preserveSelectedRowKeys: true,
onSelect: (record, selected) => {}, onSelect: (record, selected) => {},
onSelectAll: (selected, selectedRows) => {}, onSelectAll: (selected, selectedRows) => {},
onChange: (selectedRowKeys, selectedRows) => { onChange: (selectedRowKeys, selectedRows) => {
+12 -6
View File
@@ -304,7 +304,12 @@ export const useTaskLogsData = ({
// Load logs function // Load logs function
// silent=true 时用于后台轮询,不触发 loading spinner,避免表格每 10s 闪烁 // silent=true 时用于后台轮询,不触发 loading spinner,避免表格每 10s 闪烁
const loadLogs = async (page = 1, size = pageSize, silent = false) => { const loadLogs = async (
page = 1,
size = pageSize,
silent = false,
signal,
) => {
const reqId = ++requestIdRef.current; const reqId = ++requestIdRef.current;
if (!silent) setLoading(true); if (!silent) setLoading(true);
const { const {
@@ -351,17 +356,18 @@ export const useTaskLogsData = ({
? `/api/task/?${params.toString()}` ? `/api/task/?${params.toString()}`
: `/api/task/self?${params.toString()}`; : `/api/task/self?${params.toString()}`;
try { try {
const res = await API.get(url); const res = await API.get(url, { signal });
// 过时响应直接丢弃:reqId 小于最新值说明更新的请求已经发出 // 过时响应直接丢弃:reqId 小于最新值说明更新的请求已经发出
if (reqId !== requestIdRef.current) return; if (reqId !== requestIdRef.current || signal?.aborted) return;
const { success, message, data } = res.data; const { success, message, data } = res.data;
if (success) { if (success) {
syncPageData(data); syncPageData(data);
if (signal) setActivePage(page);
} else if (!silent) { } else if (!silent) {
showError(message); showError(message);
} }
} catch (err) { } catch (err) {
if (reqId !== requestIdRef.current) return; if (reqId !== requestIdRef.current || signal?.aborted) return;
if (!silent) showError(err); if (!silent) showError(err);
} finally { } finally {
// 只有当自己仍是最新请求时才结束 loading,防止旧请求提前关闭 spinner // 只有当自己仍是最新请求时才结束 loading,防止旧请求提前关闭 spinner
@@ -400,9 +406,9 @@ export const useTaskLogsData = ({
}; };
// Refresh function // Refresh function
const refresh = async () => { const refresh = async ({ page = 1, signal } = {}) => {
syncFiltersToUrl(); syncFiltersToUrl();
await loadLogs(1, pageSize); await loadLogs(page, pageSize, false, signal);
}; };
// Copy text function // Copy text function
+15 -8
View File
@@ -70,16 +70,23 @@ export const useTokensData = (openFluentNotification) => {
}; };
// Load tokens function // Load tokens function
const loadTokens = async (page = 1, size = pageSize) => { const loadTokens = async (page = 1, size = pageSize, signal) => {
setLoading(true); setLoading(true);
const res = await API.get(`/api/token/?p=${page}&size=${size}`); try {
const { success, message, data } = res.data; const res = await API.get(`/api/token/?p=${page}&size=${size}`, {
if (success) { signal,
syncPageData(data); });
} else { if (signal?.aborted) return;
showError(message); const { success, message, data } = res.data;
if (success) {
syncPageData(data);
if (signal) setActivePage(page);
} else {
showError(message);
}
} finally {
setLoading(false);
} }
setLoading(false);
}; };
// Refresh function // Refresh function
+29 -22
View File
@@ -282,7 +282,8 @@ export const useLogsData = () => {
}; };
// Statistics functions // Statistics functions
const getLogSelfStat = async () => { const statRequest = useRef(0);
const getLogSelfStat = async (signal, requestId) => {
const { const {
token_name, token_name,
model_name, model_name,
@@ -304,7 +305,8 @@ export const useLogsData = () => {
group, group,
}); });
const url = `/api/log/self/stat?${params.toString()}`; const url = `/api/log/self/stat?${params.toString()}`;
let res = await API.get(url); const res = await API.get(url, { signal });
if (signal?.aborted || requestId !== statRequest.current) return;
const { success, message, data } = res.data; const { success, message, data } = res.data;
if (success) { if (success) {
setStat(data); setStat(data);
@@ -313,7 +315,7 @@ export const useLogsData = () => {
} }
}; };
const getLogStat = async () => { const getLogStat = async (signal, requestId) => {
const { const {
username, username,
token_name, token_name,
@@ -341,7 +343,8 @@ export const useLogsData = () => {
user_id, user_id,
}); });
const url = `/api/log/stat?${params.toString()}`; const url = `/api/log/stat?${params.toString()}`;
let res = await API.get(url); const res = await API.get(url, { signal });
if (signal?.aborted || requestId !== statRequest.current) return;
const { success, message, data } = res.data; const { success, message, data } = res.data;
if (success) { if (success) {
setStat(data); setStat(data);
@@ -350,18 +353,19 @@ export const useLogsData = () => {
} }
}; };
const handleEyeClick = async () => { const handleEyeClick = async (signal) => {
if (loadingStat) { const requestId = ++statRequest.current;
return;
}
setLoadingStat(true); setLoadingStat(true);
if (isAdminUser) { try {
await getLogStat(); const getStat = isAdminUser ? getLogStat : getLogSelfStat;
} else { await getStat(signal, requestId);
await getLogSelfStat(); if (!signal?.aborted && requestId === statRequest.current)
setShowStat(true);
} catch (error) {
if (!signal?.aborted && !error.isAxiosError) showError(error);
} finally {
if (requestId === statRequest.current) setLoadingStat(false);
} }
setShowStat(true);
setLoadingStat(false);
}; };
// User info function // User info function
@@ -491,7 +495,7 @@ export const useLogsData = () => {
const logsRequestIdRef = useRef(0); const logsRequestIdRef = useRef(0);
// Load logs function // Load logs function
const loadLogs = async (startIdx, pageSize, customLogType = null) => { const loadLogs = async (startIdx, pageSize, customLogType = null, signal) => {
const reqId = ++logsRequestIdRef.current; const reqId = ++logsRequestIdRef.current;
setLoading(true); setLoading(true);
@@ -553,13 +557,13 @@ export const useLogsData = () => {
url = `/api/log/self?${params.toString()}`; url = `/api/log/self?${params.toString()}`;
} }
try { try {
const res = await API.get(url); const res = await API.get(url, { signal });
// 丢弃过期响应,只处理仍然是最新的请求 // 丢弃过期响应,只处理仍然是最新的请求
if (reqId !== logsRequestIdRef.current) return; if (reqId !== logsRequestIdRef.current || signal?.aborted) return;
const { success, message, data } = res.data; const { success, message, data } = res.data;
if (success) { if (success) {
const newPageData = Array.isArray(data?.items) ? data.items : []; const newPageData = Array.isArray(data?.items) ? data.items : [];
setActivePage(data?.page || 1); setActivePage(signal ? startIdx : data?.page || 1);
setPageSize(data?.page_size || pageSize); setPageSize(data?.page_size || pageSize);
setLogCount(data?.total || 0); setLogCount(data?.total || 0);
@@ -581,7 +585,8 @@ export const useLogsData = () => {
showError(message); showError(message);
} }
} catch (error) { } catch (error) {
if (reqId === logsRequestIdRef.current) showError(error.message || error); if (!signal?.aborted && reqId === logsRequestIdRef.current)
showError(error.message || error);
} finally { } finally {
if (reqId === logsRequestIdRef.current) setLoading(false); if (reqId === logsRequestIdRef.current) setLoading(false);
} }
@@ -624,11 +629,13 @@ export const useLogsData = () => {
}; };
// Refresh function // Refresh function
const refresh = async () => { const refresh = async ({ page = 1, signal } = {}) => {
syncFiltersToUrl(); syncFiltersToUrl();
setActivePage(1);
// 并行触发但等待两者完成,避免 stat 与 list 结果基于不同过滤条件导致错乱 // 并行触发但等待两者完成,避免 stat 与 list 结果基于不同过滤条件导致错乱
await Promise.all([handleEyeClick(), loadLogs(1, pageSize)]); await Promise.all([
handleEyeClick(signal),
loadLogs(page, pageSize, null, signal),
]);
}; };
// Copy text function // Copy text function
+17 -7
View File
@@ -1,5 +1,5 @@
import { useEffectEvent } from '../common/useEffectEvent'; import { useEffectEvent } from '../common/useEffectEvent';
import { useState, useEffect } from 'react'; import { useState, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { API, showError, showSuccess } from '../../helpers'; import { API, showError, showSuccess } from '../../helpers';
import { ITEMS_PER_PAGE } from '../../constants'; import { ITEMS_PER_PAGE } from '../../constants';
@@ -52,23 +52,28 @@ export const useUsersData = () => {
}; };
// Load users data // Load users data
const loadUsers = async (startIdx, pageSize) => { const listRequest = useRef(0);
const loadUsers = async (startIdx, pageSize, signal) => {
const id = ++listRequest.current;
setSearching(false);
setLoading(true); setLoading(true);
try { try {
const res = await API.get( const res = await API.get(
`/api/user/?p=${startIdx}&page_size=${pageSize}`, `/api/user/?p=${startIdx}&page_size=${pageSize}`,
{ signal },
); );
if (id !== listRequest.current || signal?.aborted) return;
const { success, message, data } = res.data; const { success, message, data } = res.data;
if (success) { if (success) {
const newPageData = data.items; const newPageData = data.items;
setActivePage(data.page); setActivePage(signal ? startIdx : data.page);
setUserCount(data.total); setUserCount(data.total);
setUserFormat(newPageData); setUserFormat(newPageData);
} else { } else {
showError(message); showError(message);
} }
} finally { } finally {
setLoading(false); if (id === listRequest.current) setLoading(false);
} }
}; };
@@ -78,6 +83,7 @@ export const useUsersData = () => {
pageSize, pageSize,
searchKeyword = null, searchKeyword = null,
searchGroup = null, searchGroup = null,
signal,
) => { ) => {
// If no parameters passed, get values from form // If no parameters passed, get values from form
if (searchKeyword === null || searchGroup === null) { if (searchKeyword === null || searchGroup === null) {
@@ -88,12 +94,15 @@ export const useUsersData = () => {
if (searchKeyword === '' && searchGroup === '') { if (searchKeyword === '' && searchGroup === '') {
// If both filters are blank, load users instead // If both filters are blank, load users instead
await loadUsers(startIdx, pageSize); await loadUsers(startIdx, pageSize, signal);
return; return;
} }
const id = ++listRequest.current;
setLoading(false);
setSearching(true); setSearching(true);
try { try {
const res = await API.get('/api/user/search', { const res = await API.get('/api/user/search', {
signal,
params: { params: {
keyword: searchKeyword, keyword: searchKeyword,
group: searchGroup, group: searchGroup,
@@ -101,17 +110,18 @@ export const useUsersData = () => {
page_size: pageSize, page_size: pageSize,
}, },
}); });
if (id !== listRequest.current || signal?.aborted) return;
const { success, message, data } = res.data; const { success, message, data } = res.data;
if (success) { if (success) {
const newPageData = data.items; const newPageData = data.items;
setActivePage(data.page); setActivePage(signal ? startIdx : data.page);
setUserCount(data.total); setUserCount(data.total);
setUserFormat(newPageData); setUserFormat(newPageData);
} else { } else {
showError(message); showError(message);
} }
} finally { } finally {
setSearching(false); if (id === listRequest.current) setSearching(false);
} }
}; };
+5
View File
@@ -55,6 +55,11 @@ async function createHarness() {
}, },
]; ];
}, },
useRef(current) {
const index = cursor++;
if (mounting) states[index] = { current };
return states[index];
},
useEffect(effect) { useEffect(effect) {
if (mounting) effects.push(effect); if (mounting) effects.push(effect);
}, },
+48 -39
View File
@@ -15,7 +15,9 @@ import ConsoleCollection from '../../components/console/ConsoleCollection';
import TableEmpty from '../../components/common/table/TableEmpty'; import TableEmpty from '../../components/common/table/TableEmpty';
import { useIsMobile } from '../../hooks/common/useIsMobile'; import { useIsMobile } from '../../hooks/common/useIsMobile';
import { createCardProPagination } from '../../helpers/utils'; import { createCardProPagination } from '../../helpers/utils';
import React, { useEffect, useState, useCallback } from 'react'; import React, { useState, useCallback } from 'react';
import { useFilterSearch } from '../../hooks/common/useFilterSearch';
import { useTableFilterQuery } from '../../hooks/common/useTableFilterQuery';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { import {
Button, Button,
@@ -64,6 +66,8 @@ const AdminInvoice = () => {
const [keyword, setKeyword] = useState(''); const [keyword, setKeyword] = useState('');
const [searchKeyword, setSearchKeyword] = useState(''); const [searchKeyword, setSearchKeyword] = useState('');
const [statusFilter, setStatusFilter] = useState(''); const [statusFilter, setStatusFilter] = useState('');
const [appliedStatus, setAppliedStatus] = useState('');
const [queryVersion, setQueryVersion] = useState(0);
// 详情弹窗 // 详情弹窗
const [detailVisible, setDetailVisible] = useState(false); const [detailVisible, setDetailVisible] = useState(false);
@@ -82,47 +86,51 @@ const AdminInvoice = () => {
const [adminRemark, setAdminRemark] = useState(''); const [adminRemark, setAdminRemark] = useState('');
const [approveLoading, setApproveLoading] = useState(false); const [approveLoading, setApproveLoading] = useState(false);
const fetchInvoices = useCallback(async () => { const fetchInvoices = useCallback(
setLoading(true); async (signal) => {
try { setLoading(true);
const params = { p: page, page_size: pageSize }; try {
if (searchKeyword) params.keyword = searchKeyword; const params = { p: page, page_size: pageSize };
if (statusFilter) params.status = statusFilter; if (searchKeyword) params.keyword = searchKeyword;
const res = await API.get('/api/invoice/list', { params }); if (appliedStatus) params.status = appliedStatus;
if (res.data.success) { const res = await API.get('/api/invoice/list', { params, signal });
setInvoices(res.data.data?.items || []); if (signal.aborted) return;
setTotal(res.data.data?.total || 0); if (res.data.success) {
} else { setInvoices(res.data.data?.items || []);
showError(res.data.message || t('查询失败')); setTotal(res.data.data?.total || 0);
} else {
showError(res.data.message || t('查询失败'));
}
} catch (err) {
if (!signal.aborted && !err.isAxiosError) showError(err.message);
} finally {
if (!signal.aborted) setLoading(false);
} }
} catch (err) { },
showError(err.message); [page, pageSize, searchKeyword, appliedStatus, t],
} finally { );
setLoading(false);
}
}, [page, pageSize, searchKeyword, statusFilter, t]);
useEffect(() => { const { cancelQuery } = useTableFilterQuery(fetchInvoices, queryVersion);
fetchInvoices(); const reloadInvoices = () => setQueryVersion((version) => version + 1);
}, [fetchInvoices]); const { changeFilter, submitSearch, cancelPendingSearch } = useFilterSearch(
() => {
const handleSearch = () => { setSearchKeyword(keyword);
setPage(1); setAppliedStatus(statusFilter);
setSearchKeyword(keyword); reloadInvoices();
}; },
cancelQuery,
);
const handleReset = () => { const handleReset = () => {
cancelPendingSearch();
setAppliedStatus('');
reloadInvoices();
setPage(1); setPage(1);
setKeyword(''); setKeyword('');
setSearchKeyword(''); setSearchKeyword('');
setStatusFilter(''); setStatusFilter('');
}; };
const handleStatusFilterChange = (value) => {
setPage(1);
setStatusFilter(value || '');
};
// 查看详情 // 查看详情
const handleViewDetail = async (id) => { const handleViewDetail = async (id) => {
setDetailData(null); setDetailData(null);
@@ -157,7 +165,7 @@ const AdminInvoice = () => {
setApproveVisible(false); setApproveVisible(false);
setApproveId(null); setApproveId(null);
setAdminRemark(''); setAdminRemark('');
fetchInvoices(); reloadInvoices();
} else { } else {
showError(res.data.message); showError(res.data.message);
} }
@@ -185,7 +193,7 @@ const AdminInvoice = () => {
setRejectVisible(false); setRejectVisible(false);
setRejectId(null); setRejectId(null);
setRejectReason(''); setRejectReason('');
fetchInvoices(); reloadInvoices();
} else { } else {
showError(res.data.message); showError(res.data.message);
} }
@@ -202,7 +210,7 @@ const AdminInvoice = () => {
const res = await API.post('/api/invoice/retry', { id }); const res = await API.post('/api/invoice/retry', { id });
if (res.data.success) { if (res.data.success) {
showSuccess(t('已重新发起开票')); showSuccess(t('已重新发起开票'));
fetchInvoices(); reloadInvoices();
} else { } else {
showError(res.data.message); showError(res.data.message);
} }
@@ -221,7 +229,7 @@ const AdminInvoice = () => {
const res = await API.post('/api/invoice/fail-cancel', { id }); const res = await API.post('/api/invoice/fail-cancel', { id });
if (res.data.success) { if (res.data.success) {
showSuccess(t('已取消')); showSuccess(t('已取消'));
fetchInvoices(); reloadInvoices();
} else { } else {
showError(res.data.message); showError(res.data.message);
} }
@@ -384,7 +392,7 @@ const AdminInvoice = () => {
searchArea={ searchArea={
<ConsoleFilterGrid <ConsoleFilterGrid
onReset={handleReset} onReset={handleReset}
onSearch={handleSearch} onSearch={submitSearch}
loading={loading} loading={loading}
> >
<ConsoleFilterField label={t('搜索关键字')} id='invoice-keyword'> <ConsoleFilterField label={t('搜索关键字')} id='invoice-keyword'>
@@ -393,7 +401,7 @@ const AdminInvoice = () => {
prefix={<Search size={14} />} prefix={<Search size={14} />}
placeholder={t('搜索抬头/税号/订单号/用户')} placeholder={t('搜索抬头/税号/订单号/用户')}
value={keyword} value={keyword}
onChange={setKeyword} onChange={changeFilter(setKeyword)}
/> />
</ConsoleFilterField> </ConsoleFilterField>
<ConsoleFilterField label={t('状态')} id='invoice-status'> <ConsoleFilterField label={t('状态')} id='invoice-status'>
@@ -401,7 +409,7 @@ const AdminInvoice = () => {
id='invoice-status' id='invoice-status'
placeholder={t('状态')} placeholder={t('状态')}
value={statusFilter || undefined} value={statusFilter || undefined}
onChange={handleStatusFilterChange} onChange={changeFilter((value) => setStatusFilter(value || ''))}
allowClear allowClear
optionList={[ optionList={[
{ label: t('待审核'), value: '1' }, { label: t('待审核'), value: '1' },
@@ -417,6 +425,7 @@ const AdminInvoice = () => {
</ConsoleFilterGrid> </ConsoleFilterGrid>
} }
paginationArea={createCardProPagination({ paginationArea={createCardProPagination({
preservePage: true,
currentPage: page, currentPage: page,
pageSize, pageSize,
total, total,
+76 -80
View File
@@ -9,7 +9,9 @@ import {
ConsoleCard, ConsoleCard,
ConsoleSearchBar, ConsoleSearchBar,
} from '../../components/console/ConsolePrimitives'; } from '../../components/console/ConsolePrimitives';
import React, { useEffect, useState, useCallback } from 'react'; import React, { useState, useCallback } from 'react';
import { useFilterSearch } from '../../hooks/common/useFilterSearch';
import { useTableFilterQuery } from '../../hooks/common/useTableFilterQuery';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { Search } from 'lucide-react'; import { Search } from 'lucide-react';
import { import {
@@ -85,59 +87,64 @@ const AdminOrder = () => {
const [copiedId, setCopiedId] = useState(null); const [copiedId, setCopiedId] = useState(null);
const [paymentMethodFilter, setPaymentMethodFilter] = useState(''); const [paymentMethodFilter, setPaymentMethodFilter] = useState('');
const [dateRange, setDateRange] = useState(null); const [dateRange, setDateRange] = useState(null);
const [appliedDateRange, setAppliedDateRange] = useState(null);
const [appliedStatus, setAppliedStatus] = useState('');
const [appliedPaymentMethod, setAppliedPaymentMethod] = useState('');
const [minMoney, setMinMoney] = useState(undefined); const [minMoney, setMinMoney] = useState(undefined);
const [maxMoney, setMaxMoney] = useState(undefined); const [maxMoney, setMaxMoney] = useState(undefined);
const [appliedMinMoney, setAppliedMinMoney] = useState(undefined); const [appliedMinMoney, setAppliedMinMoney] = useState(undefined);
const [appliedMaxMoney, setAppliedMaxMoney] = useState(undefined); const [appliedMaxMoney, setAppliedMaxMoney] = useState(undefined);
const fetchOrders = useCallback(async () => { const fetchOrders = useCallback(
setLoading(true); async (signal) => {
try { setLoading(true);
const params = { p: page, page_size: pageSize }; try {
if (searchKeyword) params.keyword = searchKeyword; const params = { p: page, page_size: pageSize };
if (appliedOrderId) params.order_id = appliedOrderId; if (searchKeyword) params.keyword = searchKeyword;
if (appliedUserId) params.user_id = appliedUserId; if (appliedOrderId) params.order_id = appliedOrderId;
if (statusFilter) params.status = statusFilter; if (appliedUserId) params.user_id = appliedUserId;
if (paymentMethodFilter) params.payment_method = paymentMethodFilter; if (appliedStatus) params.status = appliedStatus;
if (dateRange && dateRange[0]) if (appliedPaymentMethod) params.payment_method = appliedPaymentMethod;
params.start_time = Math.floor(dateRange[0].getTime() / 1000); if (appliedDateRange?.[0])
if (dateRange && dateRange[1]) params.start_time = Math.floor(appliedDateRange[0].getTime() / 1000);
params.end_time = Math.floor(dateRange[1].getTime() / 1000); if (appliedDateRange?.[1])
if (appliedMinMoney !== undefined && appliedMinMoney !== null) params.end_time = Math.floor(appliedDateRange[1].getTime() / 1000);
params.min_money = appliedMinMoney; if (appliedMinMoney !== undefined && appliedMinMoney !== null)
if (appliedMaxMoney !== undefined && appliedMaxMoney !== null) params.min_money = appliedMinMoney;
params.max_money = appliedMaxMoney; if (appliedMaxMoney !== undefined && appliedMaxMoney !== null)
const res = await API.get('/api/order/search', { params }); params.max_money = appliedMaxMoney;
if (res.data.success) { const res = await API.get('/api/order/search', { params, signal });
setOrders(res.data.data?.items || []); if (signal?.aborted) return;
setTotal(res.data.data?.total || 0); if (res.data.success) {
} else { setOrders(res.data.data?.items || []);
showError(res.data.message || t('查询失败')); setTotal(res.data.data?.total || 0);
} else {
showError(res.data.message || t('查询失败'));
}
} catch (err) {
if (!signal?.aborted && !err.isAxiosError) showError(err.message);
} finally {
if (!signal?.aborted) setLoading(false);
} }
} catch (err) { },
showError(err.message); [
} finally { page,
setLoading(false); pageSize,
} searchKeyword,
}, [ appliedOrderId,
page, appliedUserId,
pageSize, appliedStatus,
searchKeyword, appliedPaymentMethod,
appliedOrderId, appliedDateRange,
appliedUserId, appliedMinMoney,
statusFilter, appliedMaxMoney,
paymentMethodFilter, t,
dateRange, ],
appliedMinMoney, );
appliedMaxMoney,
t,
]);
useEffect(() => { const { cancelQuery } = useTableFilterQuery(fetchOrders, queryVersion);
fetchOrders();
}, [fetchOrders, queryVersion]);
const handleSearch = () => { const applyFilters = () => {
const trimmedKeyword = keyword.trim(); const trimmedKeyword = keyword.trim();
const normalizedOrderId = const normalizedOrderId =
orderId && Number(orderId) > 0 ? Math.floor(Number(orderId)) : undefined; orderId && Number(orderId) > 0 ? Math.floor(Number(orderId)) : undefined;
@@ -149,7 +156,6 @@ const AdminOrder = () => {
: undefined; : undefined;
const ignoreNumericKeyword = const ignoreNumericKeyword =
normalizedOrderId && /^\d+$/.test(trimmedKeyword); normalizedOrderId && /^\d+$/.test(trimmedKeyword);
setPage(1);
setSearchKeyword( setSearchKeyword(
numericKeywordAsOrderId || ignoreNumericKeyword ? '' : trimmedKeyword, numericKeywordAsOrderId || ignoreNumericKeyword ? '' : trimmedKeyword,
); );
@@ -157,33 +163,22 @@ const AdminOrder = () => {
setAppliedUserId(normalizedUserId); setAppliedUserId(normalizedUserId);
setAppliedMinMoney(minMoney); setAppliedMinMoney(minMoney);
setAppliedMaxMoney(maxMoney); setAppliedMaxMoney(maxMoney);
setAppliedStatus(statusFilter || '');
setAppliedPaymentMethod(paymentMethodFilter || '');
setAppliedDateRange(dateRange);
setQueryVersion((version) => version + 1); setQueryVersion((version) => version + 1);
}; };
const handleStatusFilterChange = (value) => { const { changeFilter, submitSearch, cancelPendingSearch } = useFilterSearch(
setPage(1); applyFilters,
setStatusFilter(value || ''); cancelQuery,
}; );
const handlePaymentMethodChange = (value) => {
setPage(1);
setPaymentMethodFilter(value || '');
};
const handleDateRangeChange = (dates) => {
setPage(1);
setDateRange(dates || null);
};
const handleMinMoneyChange = (value) => {
setMinMoney(value);
};
const handleMaxMoneyChange = (value) => {
setMaxMoney(value);
};
const handleReset = () => { const handleReset = () => {
cancelPendingSearch();
setAppliedStatus('');
setAppliedPaymentMethod('');
setAppliedDateRange(null);
setQueryVersion((version) => version + 1); setQueryVersion((version) => version + 1);
setPage(1); setPage(1);
setKeyword(''); setKeyword('');
@@ -407,7 +402,7 @@ const AdminOrder = () => {
<ConsoleSearchBar <ConsoleSearchBar
formProps={{ formProps={{
layout: 'vertical', layout: 'vertical',
onFinish: handleSearch, onFinish: submitSearch,
className: 'console-module-filter-form', className: 'console-module-filter-form',
}} }}
> >
@@ -417,15 +412,14 @@ const AdminOrder = () => {
prefix={<Search size={14} />} prefix={<Search size={14} />}
placeholder={t('搜索昵称/订单号')} placeholder={t('搜索昵称/订单号')}
value={keyword} value={keyword}
onChange={setKeyword} onChange={changeFilter(setKeyword)}
onEnterPress={handleSearch}
/> />
</ConsoleFilterField> </ConsoleFilterField>
<ConsoleFilterField label={t('订单ID')}> <ConsoleFilterField label={t('订单ID')}>
<InputNumber <InputNumber
placeholder={t('订单ID')} placeholder={t('订单ID')}
value={orderId} value={orderId}
onChange={setOrderId} onChange={changeFilter(setOrderId)}
min={1} min={1}
hideButtons hideButtons
/> />
@@ -434,7 +428,7 @@ const AdminOrder = () => {
<InputNumber <InputNumber
placeholder={t('用户ID')} placeholder={t('用户ID')}
value={userId} value={userId}
onChange={setUserId} onChange={changeFilter(setUserId)}
min={1} min={1}
hideButtons hideButtons
/> />
@@ -443,7 +437,7 @@ const AdminOrder = () => {
<Select <Select
placeholder={t('状态')} placeholder={t('状态')}
value={statusFilter || undefined} value={statusFilter || undefined}
onChange={handleStatusFilterChange} onChange={changeFilter(setStatusFilter)}
allowClear allowClear
optionList={[ optionList={[
{ label: t('待支付'), value: 'pending' }, { label: t('待支付'), value: 'pending' },
@@ -456,7 +450,7 @@ const AdminOrder = () => {
<Select <Select
placeholder={t('支付方式')} placeholder={t('支付方式')}
value={paymentMethodFilter || undefined} value={paymentMethodFilter || undefined}
onChange={handlePaymentMethodChange} onChange={changeFilter(setPaymentMethodFilter)}
allowClear allowClear
optionList={Object.entries(paymentMethodMap).map( optionList={Object.entries(paymentMethodMap).map(
([value, label]) => ({ label, value }), ([value, label]) => ({ label, value }),
@@ -465,9 +459,10 @@ const AdminOrder = () => {
</ConsoleFilterField> </ConsoleFilterField>
<ConsoleFilterField label={t('创建时间')}> <ConsoleFilterField label={t('创建时间')}>
<DatePicker <DatePicker
tableFilter
type='dateTimeRange' type='dateTimeRange'
value={dateRange} value={dateRange}
onChange={handleDateRangeChange} onChange={changeFilter(setDateRange)}
placeholder={[t('开始时间'), t('结束时间')]} placeholder={[t('开始时间'), t('结束时间')]}
density='compact' density='compact'
/> />
@@ -477,7 +472,7 @@ const AdminOrder = () => {
<InputNumber <InputNumber
placeholder={t('最小金额')} placeholder={t('最小金额')}
value={minMoney} value={minMoney}
onChange={handleMinMoneyChange} onChange={changeFilter(setMinMoney)}
min={0} min={0}
precision={2} precision={2}
prefix='¥' prefix='¥'
@@ -486,7 +481,7 @@ const AdminOrder = () => {
<InputNumber <InputNumber
placeholder={t('最大金额')} placeholder={t('最大金额')}
value={maxMoney} value={maxMoney}
onChange={handleMaxMoneyChange} onChange={changeFilter(setMaxMoney)}
min={0} min={0}
precision={2} precision={2}
prefix='¥' prefix='¥'
@@ -496,7 +491,7 @@ const AdminOrder = () => {
</div> </div>
<ConsoleFilterActions <ConsoleFilterActions
onReset={handleReset} onReset={handleReset}
onSearch={handleSearch} onSearch={submitSearch}
loading={loading} loading={loading}
/> />
</ConsoleSearchBar> </ConsoleSearchBar>
@@ -510,6 +505,7 @@ const AdminOrder = () => {
loading={loading} loading={loading}
rowKey='id' rowKey='id'
pagination={{ pagination={{
preservePage: true,
currentPage: page, currentPage: page,
total, total,
pageSize, pageSize,
+84 -94
View File
@@ -16,6 +16,8 @@ import {
} from '../../components/console/ConsolePrimitives'; } from '../../components/console/ConsolePrimitives';
import { ConsolePageActions } from '../../components/console/ConsolePageContainer'; import { ConsolePageActions } from '../../components/console/ConsolePageContainer';
import React, { useEffect, useState, useCallback, useRef } from 'react'; import React, { useEffect, useState, useCallback, useRef } from 'react';
import { useFilterSearch } from '../../hooks/common/useFilterSearch';
import { useTableFilterQuery } from '../../hooks/common/useTableFilterQuery';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { Search } from 'lucide-react'; import { Search } from 'lucide-react';
@@ -152,6 +154,7 @@ const AdminOrganizations = () => {
// 用户ID筛选:输入框值与已应用值分离,回车才下推请求(与关键字框同一交互) // 用户ID筛选:输入框值与已应用值分离,回车才下推请求(与关键字框同一交互)
const [userIdInput, setUserIdInput] = useState(''); const [userIdInput, setUserIdInput] = useState('');
const [userIdFilter, setUserIdFilter] = useState(''); const [userIdFilter, setUserIdFilter] = useState('');
const [appliedFilters, setAppliedFilters] = useState({});
const [salesRepOptions, setSalesRepOptions] = useState([]); const [salesRepOptions, setSalesRepOptions] = useState([]);
const [sortBy, setSortBy] = useState(''); const [sortBy, setSortBy] = useState('');
const [sortOrder, setSortOrder] = useState(''); const [sortOrder, setSortOrder] = useState('');
@@ -306,49 +309,58 @@ const AdminOrganizations = () => {
// 筛选/排序可高频连续触发请求,用递增序号丢弃过期响应,防止慢网下旧结果覆盖新筛选 // 筛选/排序可高频连续触发请求,用递增序号丢弃过期响应,防止慢网下旧结果覆盖新筛选
const fetchSeqRef = useRef(0); const fetchSeqRef = useRef(0);
const fetchOrgs = useCallback(async () => { const fetchOrgs = useCallback(
const seq = ++fetchSeqRef.current; async (signal) => {
setLoading(true); const { statusFilter, levelFilter, salesRepFilter } = appliedFilters;
try { const seq = ++fetchSeqRef.current;
const params = { p: page, page_size: pageSize }; setLoading(true);
if (searchKeyword) params.keyword = searchKeyword; try {
if (statusFilter != null) params.status = statusFilter; const params = { p: page, page_size: pageSize };
if (levelFilter) params.level = levelFilter; if (searchKeyword) params.keyword = searchKeyword;
if (salesRepFilter) params.sales_rep = salesRepFilter; if (statusFilter != null) params.status = statusFilter;
if (userIdFilter) params.user_id = userIdFilter; if (levelFilter) params.level = levelFilter;
if (sortBy) { if (salesRepFilter) params.sales_rep = salesRepFilter;
params.sort_by = sortBy; if (userIdFilter) params.user_id = userIdFilter;
params.sort_order = sortOrder || 'desc'; if (sortBy) {
params.sort_by = sortBy;
params.sort_order = sortOrder || 'desc';
}
const res = await API.get('/api/admin/organizations/', {
params,
signal,
});
if (signal?.aborted || seq !== fetchSeqRef.current) return;
if (res.data.success) {
setOrgs(res.data.data?.items || []);
setTotal(res.data.data?.total || 0);
} else {
showError(res.data.message || t('查询失败'));
}
} catch (err) {
if (
!signal?.aborted &&
seq === fetchSeqRef.current &&
!err.isAxiosError
)
showError(err.message);
} finally {
if (seq === fetchSeqRef.current) setLoading(false);
} }
const res = await API.get('/api/admin/organizations/', { params }); },
if (seq !== fetchSeqRef.current) return; [
if (res.data.success) { page,
setOrgs(res.data.data?.items || []); pageSize,
setTotal(res.data.data?.total || 0); searchKeyword,
} else { appliedFilters,
showError(res.data.message || t('查询失败')); userIdFilter,
} sortBy,
} catch (err) { sortOrder,
if (seq === fetchSeqRef.current) showError(err.message); t,
} finally { ],
if (seq === fetchSeqRef.current) setLoading(false); );
}
}, [
page,
pageSize,
searchKeyword,
statusFilter,
levelFilter,
salesRepFilter,
userIdFilter,
sortBy,
sortOrder,
t,
]);
useEffect(() => { const { cancelQuery } = useTableFilterQuery(fetchOrgs, queryVersion);
fetchOrgs(); const reloadOrgs = () => setQueryVersion((version) => version + 1);
}, [fetchOrgs, queryVersion]);
useEffect(() => { useEffect(() => {
fetchGroups(); fetchGroups();
@@ -357,21 +369,20 @@ const AdminOrganizations = () => {
fetchAlertExcluded(); fetchAlertExcluded();
}, [fetchGroups, fetchLevels, fetchSalesReps, fetchAlertExcluded]); }, [fetchGroups, fetchLevels, fetchSalesReps, fetchAlertExcluded]);
// 筛选变化统一回到第 1 页,避免停留在筛选后不存在的页码 const { changeFilter, submitSearch, cancelPendingSearch } = useFilterSearch(
const applyFilter = (setter) => (value) => { () => {
setter(value); setSearchKeyword(keyword.trim());
setPage(1); setUserIdFilter(userIdInput);
}; setAppliedFilters({ statusFilter, levelFilter, salesRepFilter });
reloadOrgs();
const handleSearch = () => { },
setPage(1); cancelQuery,
setSearchKeyword(keyword.trim()); );
setUserIdFilter(userIdInput);
setQueryVersion((version) => version + 1);
};
const resetFilters = () => { const resetFilters = () => {
setQueryVersion((version) => version + 1); cancelPendingSearch();
setAppliedFilters({});
reloadOrgs();
setKeyword(''); setKeyword('');
setSearchKeyword(''); setSearchKeyword('');
setStatusFilter(undefined); setStatusFilter(undefined);
@@ -411,7 +422,7 @@ const AdminOrganizations = () => {
}); });
if (res.data.success) { if (res.data.success) {
Toast.success(t('状态已更新')); Toast.success(t('状态已更新'));
fetchOrgs(); reloadOrgs();
return true; return true;
} else { } else {
showError(res.data.message); showError(res.data.message);
@@ -443,7 +454,7 @@ const AdminOrganizations = () => {
if (res.data.success) { if (res.data.success) {
Toast.success(t('功能开关已更新')); Toast.success(t('功能开关已更新'));
setFeatureModalOrg(null); setFeatureModalOrg(null);
fetchOrgs(); reloadOrgs();
} else { } else {
showError(res.data.message); showError(res.data.message);
} }
@@ -457,7 +468,7 @@ const AdminOrganizations = () => {
const res = await API.put(`/api/admin/organizations/${orgId}/activate`); const res = await API.put(`/api/admin/organizations/${orgId}/activate`);
if (res.data.success) { if (res.data.success) {
Toast.success(t('企业已激活')); Toast.success(t('企业已激活'));
fetchOrgs(); reloadOrgs();
} else { } else {
showError(res.data.message); showError(res.data.message);
} }
@@ -476,7 +487,7 @@ const AdminOrganizations = () => {
if (res.data.success) { if (res.data.success) {
Toast.success(t('额度已调整')); Toast.success(t('额度已调整'));
setQuotaModalVisible(false); setQuotaModalVisible(false);
fetchOrgs(); reloadOrgs();
} else { } else {
showError(res.data.message); showError(res.data.message);
} }
@@ -555,7 +566,7 @@ const AdminOrganizations = () => {
setCreateModalVisible(false); setCreateModalVisible(false);
resetCreateForm(); resetCreateForm();
} }
fetchOrgs(); reloadOrgs();
fetchSalesReps(); fetchSalesReps();
} else { } else {
showError(res.data.message); showError(res.data.message);
@@ -640,7 +651,7 @@ const AdminOrganizations = () => {
if (res.data.success) { if (res.data.success) {
Toast.success(t('企业信息已更新')); Toast.success(t('企业信息已更新'));
setEditModalVisible(false); setEditModalVisible(false);
fetchOrgs(); reloadOrgs();
fetchSalesReps(); fetchSalesReps();
} else { } else {
showError(res.data.message); showError(res.data.message);
@@ -663,7 +674,7 @@ const AdminOrganizations = () => {
const res = await API.delete(`/api/admin/organizations/${orgId}`); const res = await API.delete(`/api/admin/organizations/${orgId}`);
if (res.data.success) { if (res.data.success) {
Toast.success(t('企业已删除')); Toast.success(t('企业已删除'));
fetchOrgs(); reloadOrgs();
// 被删企业可能是某商务唯一跟进的企业,同步刷新筛选下拉防残留失效姓名 // 被删企业可能是某商务唯一跟进的企业,同步刷新筛选下拉防残留失效姓名
fetchSalesReps(); fetchSalesReps();
return true; return true;
@@ -935,7 +946,7 @@ const AdminOrganizations = () => {
<ConsoleSearchBar <ConsoleSearchBar
formProps={{ formProps={{
layout: 'vertical', layout: 'vertical',
onFinish: handleSearch, onFinish: submitSearch,
className: 'console-module-filter-form', className: 'console-module-filter-form',
}} }}
> >
@@ -944,52 +955,30 @@ const AdminOrganizations = () => {
<Input <Input
prefix={<Search size={16} />} prefix={<Search size={16} />}
value={keyword} value={keyword}
onChange={(v) => { onChange={changeFilter(setKeyword)}
setKeyword(v);
// 退格删空/点清除都会走到这里:输入框空了就同步解除过滤,
// 避免"框已空但表格仍按旧关键字过滤"的幽灵状态
if (v === '' && searchKeyword) {
setSearchKeyword('');
setPage(1);
}
}}
placeholder={t('搜索企业名称、代码、联系人、商务...')} placeholder={t('搜索企业名称、代码、联系人、商务...')}
showClear showClear
onEnterPress={() => {
setPage(1);
setSearchKeyword(keyword);
}}
/> />
</ConsoleFilterField> </ConsoleFilterField>
<ConsoleFilterField label={t('用户ID')}> <ConsoleFilterField label={t('用户ID')}>
<Input <Input
value={userIdInput} value={userIdInput}
onChange={(v) => { onChange={changeFilter((value) => {
// 只留数字并剥前导零:杜绝 "0"/"007" 这类后端会静默忽略的值, setUserIdInput(
// 否则 UI 显示筛选生效、实际返回全量列表(幽灵筛选态) (value || '').replace(/\D/g, '').replace(/^0+/, ''),
const digits = (v || '').replace(/\D/g, '').replace(/^0+/, ''); );
setUserIdInput(digits); })}
// 与关键字框同款:删空/点清除即解除过滤
if (digits === '' && userIdFilter) {
setUserIdFilter('');
setPage(1);
}
}}
placeholder={t('用户ID(owner或成员)')} placeholder={t('用户ID(owner或成员)')}
showClear showClear
// 10 位封顶:真实用户ID 不会更长,且远离后端 Atoi 溢出边界(19 位) // 10 位封顶:真实用户ID 不会更长,且远离后端 Atoi 溢出边界(19 位)
maxLength={10} maxLength={10}
aria-label={t('按用户ID筛选')} aria-label={t('按用户ID筛选')}
onEnterPress={() => {
setPage(1);
setUserIdFilter(userIdInput);
}}
/> />
</ConsoleFilterField> </ConsoleFilterField>
<ConsoleFilterField label={t('状态')}> <ConsoleFilterField label={t('状态')}>
<Select <Select
value={statusFilter} value={statusFilter}
onChange={applyFilter(setStatusFilter)} onChange={changeFilter(setStatusFilter)}
optionList={[ optionList={[
{ value: 1, label: t('正常') }, { value: 1, label: t('正常') },
{ value: 2, label: t('冻结') }, { value: 2, label: t('冻结') },
@@ -1004,7 +993,7 @@ const AdminOrganizations = () => {
<ConsoleFilterField label={t('企业等级')}> <ConsoleFilterField label={t('企业等级')}>
<Select <Select
value={levelFilter} value={levelFilter}
onChange={applyFilter(setLevelFilter)} onChange={changeFilter(setLevelFilter)}
optionList={levelOptions} optionList={levelOptions}
placeholder={t('全部等级')} placeholder={t('全部等级')}
showClear showClear
@@ -1015,7 +1004,7 @@ const AdminOrganizations = () => {
<ConsoleFilterField label={t('商务人员')}> <ConsoleFilterField label={t('商务人员')}>
<Select <Select
value={salesRepFilter} value={salesRepFilter}
onChange={applyFilter(setSalesRepFilter)} onChange={changeFilter(setSalesRepFilter)}
optionList={[ optionList={[
{ value: '__none__', label: t('未分配') }, { value: '__none__', label: t('未分配') },
...salesRepOptions, ...salesRepOptions,
@@ -1029,7 +1018,7 @@ const AdminOrganizations = () => {
</div> </div>
<ConsoleFilterActions <ConsoleFilterActions
onReset={resetFilters} onReset={resetFilters}
onSearch={handleSearch} onSearch={submitSearch}
loading={loading} loading={loading}
/> />
{isAdmin() && ( {isAdmin() && (
@@ -1080,6 +1069,7 @@ const AdminOrganizations = () => {
style={{ width: '100%' }} style={{ width: '100%' }}
onChange={handleTableChange} onChange={handleTableChange}
pagination={{ pagination={{
preservePage: true,
currentPage: page, currentPage: page,
pageSize, pageSize,
total, total,
+23 -4
View File
@@ -118,6 +118,7 @@ const Analytics = () => {
const [channelOpen, setChannelOpen] = useState(false); const [channelOpen, setChannelOpen] = useState(false);
const [topupRankOpen, setTopupRankOpen] = useState(false); const [topupRankOpen, setTopupRankOpen] = useState(false);
const [dailyStatsOpen, setDailyStatsOpen] = useState(false); const [dailyStatsOpen, setDailyStatsOpen] = useState(false);
const [dailyStatsReset, setDailyStatsReset] = useState(0);
const [banLogsOpen, setBanLogsOpen] = useState(true); const [banLogsOpen, setBanLogsOpen] = useState(true);
const [activeTab, setActiveTab] = useState(readTabFromURL); const [activeTab, setActiveTab] = useState(readTabFromURL);
@@ -158,7 +159,8 @@ const Analytics = () => {
dateRange, dateRange,
setPeriod, setPeriod,
setDateRange, setDateRange,
refreshAll, submitSearch,
resetFilters,
} = useAnalyticsData( } = useAnalyticsData(
activeTab === 'operations' && isAnalyticsTabVisible('operations'), activeTab === 'operations' && isAnalyticsTabVisible('operations'),
); );
@@ -189,7 +191,9 @@ const Analytics = () => {
const curDateRange = isOrgTab ? org.dateRange : dateRange; const curDateRange = isOrgTab ? org.dateRange : dateRange;
const curSetPeriod = isOrgTab ? org.setPeriod : setPeriod; const curSetPeriod = isOrgTab ? org.setPeriod : setPeriod;
const curSetDateRange = isOrgTab ? org.setDateRange : setDateRange; const curSetDateRange = isOrgTab ? org.setDateRange : setDateRange;
const curRefresh = isOrgTab ? org.refreshAll : refreshAll; const curRefresh = isOrgTab
? () => org.refreshAll(curPeriod, curDateRange, true)
: submitSearch;
const curLoading = isOrgTab ? org.loading : loading; const curLoading = isOrgTab ? org.loading : loading;
// 概览卡片自己带骨架屏,不进全页遮罩;但刷新按钮要等它一起转完才算刷新结束 // 概览卡片自己带骨架屏,不进全页遮罩;但刷新按钮要等它一起转完才算刷新结束
const curOverviewLoading = isOrgTab ? false : overviewLoading; const curOverviewLoading = isOrgTab ? false : overviewLoading;
@@ -238,10 +242,13 @@ const Analytics = () => {
</Radio.Group> </Radio.Group>
{curPeriod === 'custom' && ( {curPeriod === 'custom' && (
<DatePicker <DatePicker
tableFilter={isOperationsTab}
type='dateRange' type='dateRange'
value={curDateRange} value={curDateRange}
onChange={curSetDateRange} onChange={curSetDateRange}
placeholder={[t('开始日期'), t('结束日期')]} placeholder={
isOrgTab ? [t('开始日期'), t('结束日期')] : undefined
}
format='yyyy-MM-dd' format='yyyy-MM-dd'
style={{ width: 260 }} style={{ width: 260 }}
presets={[ presets={[
@@ -265,11 +272,22 @@ const Analytics = () => {
)} )}
<Button <Button
icon={<IconRefresh />} icon={<IconRefresh />}
onClick={() => curRefresh(curPeriod, curDateRange, true)} onClick={curRefresh}
loading={curLoading || curOverviewLoading} loading={curLoading || curOverviewLoading}
> >
{t('刷新')} {t('刷新')}
</Button> </Button>
{isOperationsTab && (
<Button
onClick={() => {
resetFilters();
setDailyStatsOpen(false);
setDailyStatsReset((version) => version + 1);
}}
>
{t('重置')}
</Button>
)}
</> </>
)} )}
</ConsolePageActions> </ConsolePageActions>
@@ -468,6 +486,7 @@ const Analytics = () => {
<Collapsible isOpen={dailyStatsOpen} keepDOM> <Collapsible isOpen={dailyStatsOpen} keepDOM>
<div> <div>
<DailyStatsTable <DailyStatsTable
key={dailyStatsReset}
embedded embedded
data={dailyStats} data={dailyStats}
title={t('每日统计明细')} title={t('每日统计明细')}
+53 -38
View File
@@ -1,13 +1,8 @@
import React, { import React, { useCallback, useMemo, useRef, useState } from 'react';
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { Alert, Button } from 'antd'; import { Alert, Button } from 'antd';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import ListPanel from './ListPanel'; import ListPanel from './ListPanel';
import { useTableFilterQuery } from '../../hooks/common/useTableFilterQuery';
import { latestTierURL, fetchAllLatestTiers } from './latestTiers'; import { latestTierURL, fetchAllLatestTiers } from './latestTiers';
export default function LatestTierPanel({ export default function LatestTierPanel({
@@ -34,39 +29,55 @@ export default function LatestTierPanel({
error: '', error: '',
}); });
const [exporting, setExporting] = useState(false); const [exporting, setExporting] = useState(false);
const load = useCallback(async () => { const [version, setVersion] = useState(0);
const current = ++generation.current; const load = useCallback(
setExporting(false); async (signal) => {
setState((old) => ({ ...old, context, items: [], busy: true, error: '' })); const current = ++generation.current;
try { setExporting(false);
const result = await fetchJSON(latestTierURL(query, query.page)); setState((old) => ({
if (current !== generation.current || activeContext.current !== context) ...old,
return;
setState({
...result,
context, context,
items: result.items.map((item) => ({ ...item, __asOf: result.as_of })), items: [],
busy: false, busy: true,
error: '', error: '',
}); }));
} catch (error) { try {
if (current === generation.current && activeContext.current === context) const result = await fetchJSON(latestTierURL(query, query.page), {
setState((old) => ({ signal,
...old, });
items: [], if (
signal.aborted ||
current !== generation.current ||
activeContext.current !== context
)
return;
setState({
...result,
context,
items: result.items.map((item) => ({
...item,
__asOf: result.as_of,
})),
busy: false, busy: false,
error: error.message, error: '',
})); });
} } catch (error) {
}, [fetchJSON, query, context]); if (
useEffect(() => { !signal.aborted &&
load(); current === generation.current &&
return () => { activeContext.current === context
// 卸载或重新加载时作废进行中的请求(原有逻辑)。 )
// eslint-disable-next-line react-hooks/exhaustive-deps setState((old) => ({
generation.current++; ...old,
}; items: [],
}, [load]); busy: false,
error: error.message,
}));
}
},
[fetchJSON, query, context],
);
const { cancelQuery } = useTableFilterQuery(load, version);
const exportAll = async () => { const exportAll = async () => {
if ( if (
exportRequest.current?.context === context || exportRequest.current?.context === context ||
@@ -112,7 +123,10 @@ export default function LatestTierPanel({
className='commission-inline-alert' className='commission-inline-alert'
title={visible.error} title={visible.error}
action={ action={
<Button size='small' onClick={load}> <Button
size='small'
onClick={() => setVersion((value) => value + 1)}
>
{t('重试')} {t('重试')}
</Button> </Button>
} }
@@ -131,6 +145,7 @@ export default function LatestTierPanel({
page: query.page, page: query.page,
pageSize: query.pageSize, pageSize: query.pageSize,
exporting, exporting,
cancelQuery,
onChange: (next) => { onChange: (next) => {
generation.current++; generation.current++;
exportRequest.current = null; exportRequest.current = null;
+30 -24
View File
@@ -1,4 +1,4 @@
import React, { useState } from 'react'; import React, { useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { Button, Empty, Input, Select } from 'antd'; import { Button, Empty, Input, Select } from 'antd';
import { Table } from '@/components/ui'; import { Table } from '@/components/ui';
@@ -9,7 +9,9 @@ import {
ConsoleTabs, ConsoleTabs,
} from '../../components/console/ConsolePrimitives'; } from '../../components/console/ConsolePrimitives';
import { ConsoleCollectionSearch } from '../../components/console/ConsoleCollection'; import { ConsoleCollectionSearch } from '../../components/console/ConsoleCollection';
import { filterCommissionRows, matchesStatus } from './listFilters'; import { useFilteredTableRows } from '../../hooks/common/useFilteredTableRows';
import { useFilterSearch } from '../../hooks/common/useFilterSearch';
import { createCommissionRowFilter, matchesStatus } from './listFilters';
export default function ListPanel({ export default function ListPanel({
section, section,
@@ -29,8 +31,17 @@ export default function ListPanel({
const [status, setStatus] = useState('all'); const [status, setStatus] = useState('all');
const [page, setPage] = useState(1); const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(10); const [pageSize, setPageSize] = useState(10);
const set = (key, value) => const { scheduleSearch, submitSearch, cancelPendingSearch } = useFilterSearch(
() => {
setFilters(draft);
server?.onChange({ ...draft, status, page: server.page });
},
server?.cancelQuery,
);
const set = (key, value) => {
setDraft((current) => ({ ...current, [key]: value })); setDraft((current) => ({ ...current, [key]: value }));
scheduleSearch();
};
const tabSets = { const tabSets = {
assignments: [ assignments: [
['all', '全部'], ['all', '全部'],
@@ -86,26 +97,19 @@ export default function ListPanel({
audit: '搜索操作 / 实体 / 操作人', audit: '搜索操作 / 实体 / 操作人',
exceptions: '搜索异常码 / 计费事实 / 说明', exceptions: '搜索异常码 / 计费事实 / 说明',
}; };
const scopedRows = scopedIds const matches = useMemo(() => {
? rows.filter((row) => scopedIds.includes(row.id)) if (server) return () => true;
: rows; const ids = scopedIds && new Set(scopedIds);
const filtered = server const matchesFilters = createCommissionRowFilter(
? rows { ...filters, status: section === 'partners' ? filters.status : status },
: filterCommissionRows( section,
scopedRows, searchableText,
{ );
...filters, return (row) => (!ids || ids.has(row.id)) && matchesFilters(row);
status: section === 'partners' ? filters.status : status, }, [filters, scopedIds, section, searchableText, status, server]);
}, const filtered = useFilteredTableRows(rows, matches);
section,
searchableText,
);
const query = () => {
setFilters(draft);
setPage(1);
server?.onChange({ ...draft, status, page: 1 });
};
const reset = () => { const reset = () => {
cancelPendingSearch();
setDraft({ query: '', type: '', partner: '' }); setDraft({ query: '', type: '', partner: '' });
setFilters({}); setFilters({});
setStatus('all'); setStatus('all');
@@ -160,7 +164,7 @@ export default function ListPanel({
<ConsoleCollectionSearch className='commission-filter-card'> <ConsoleCollectionSearch className='commission-filter-card'>
<ConsoleFilterGrid <ConsoleFilterGrid
onReset={reset} onReset={reset}
onSearch={query} onSearch={submitSearch}
loading={server?.busy} loading={server?.busy}
> >
<label className='console-search-field commission-search-field'> <label className='console-search-field commission-search-field'>
@@ -275,11 +279,13 @@ export default function ListPanel({
size='middle' size='middle'
scroll={{ x: 'max-content' }} scroll={{ x: 'max-content' }}
pagination={ pagination={
(server ? server.total : filtered.length) (server ? server.total : filtered.length) > 0 ||
(server ? server.page : page) > 1
? { ? {
size: 'small', size: 'small',
pageSize: server ? server.pageSize : pageSize, pageSize: server ? server.pageSize : pageSize,
total: server?.total, total: server?.total,
preservePage: true,
currentPage: server ? server.page : page, currentPage: server ? server.page : page,
onPageChange: (next) => { onPageChange: (next) => {
setPage(next); setPage(next);
+69 -37
View File
@@ -1,5 +1,7 @@
import { formatIdReference } from '../../helpers/safeDisplay'; import { formatIdReference } from '../../helpers/safeDisplay';
import { useFilterSearch } from '../../hooks/common/useFilterSearch';
import { useFilteredTableRows } from '../../hooks/common/useFilteredTableRows';
import { ConsoleCollectionSearch } from '@/components/console/ConsoleCollection'; import { ConsoleCollectionSearch } from '@/components/console/ConsoleCollection';
import { import {
ConsoleFilterField, ConsoleFilterField,
@@ -136,6 +138,27 @@ export default function PartnerPortal({
const [customerStatus, setCustomerStatus] = useState('all'); const [customerStatus, setCustomerStatus] = useState('all');
const [billMonth, setBillMonth] = useState('all'); const [billMonth, setBillMonth] = useState('all');
const [billStatus, setBillStatus] = useState('all'); const [billStatus, setBillStatus] = useState('all');
const [appliedDetail, setAppliedDetail] = useState('');
const [appliedCustomer, setAppliedCustomer] = useState({
keyword: '',
status: 'all',
});
const [appliedBill, setAppliedBill] = useState({
month: 'all',
status: 'all',
});
const detailSearch = useFilterSearch(() =>
setAppliedDetail(query.toLowerCase()),
);
const customerSearch = useFilterSearch(() =>
setAppliedCustomer({
keyword: customerQuery.toLowerCase(),
status: customerStatus,
}),
);
const billSearch = useFilterSearch(() =>
setAppliedBill({ month: billMonth, status: billStatus }),
);
const [billPage, setBillPage] = useState(1); const [billPage, setBillPage] = useState(1);
const [customerPage, setCustomerPage] = useState(1); const [customerPage, setCustomerPage] = useState(1);
const [detailPage, setDetailPage] = useState(1); const [detailPage, setDetailPage] = useState(1);
@@ -243,6 +266,9 @@ export default function PartnerPortal({
setDetailLoading(true); setDetailLoading(true);
setError(''); setError('');
setQuery(''); setQuery('');
detailSearch.cancelPendingSearch();
setQuery('');
setAppliedDetail('');
setDetailPage(1); setDetailPage(1);
setAction(null); setAction(null);
setReason(''); setReason('');
@@ -369,9 +395,9 @@ export default function PartnerPortal({
const currentStatements = rows.filter( const currentStatements = rows.filter(
(row) => row.statement_month === currentMonth, (row) => row.statement_month === currentMonth,
); );
const detailItems = items.filter( const matchesDetail = useCallback(
(item) => (item) =>
!query || !appliedDetail ||
[ [
item.customer_name, item.customer_name,
item.model_name, item.model_name,
@@ -380,24 +406,32 @@ export default function PartnerPortal({
].some((value) => ].some((value) =>
String(value || '') String(value || '')
.toLowerCase() .toLowerCase()
.includes(query.toLowerCase()), .includes(appliedDetail),
), ),
[appliedDetail],
); );
const visibleCustomers = customers.filter( const detailItems = useFilteredTableRows(items, matchesDetail);
const matchesCustomer = useCallback(
(row) => (row) =>
(customerStatus === 'all' || row.status === customerStatus) && (appliedCustomer.status === 'all' ||
(!customerQuery || row.status === appliedCustomer.status) &&
(!appliedCustomer.keyword ||
[row.customer_name, row.subject_name, row.subject_id].some((value) => [row.customer_name, row.subject_name, row.subject_id].some((value) =>
String(value || '') String(value || '')
.toLowerCase() .toLowerCase()
.includes(customerQuery.toLowerCase()), .includes(appliedCustomer.keyword),
)), )),
[appliedCustomer],
); );
const visibleBills = rows.filter( const visibleCustomers = useFilteredTableRows(customers, matchesCustomer);
const matchesBill = useCallback(
(row) => (row) =>
(billMonth === 'all' || row.statement_month === billMonth) && (appliedBill.month === 'all' ||
(billStatus === 'all' || row.status === billStatus), row.statement_month === appliedBill.month) &&
(appliedBill.status === 'all' || row.status === appliedBill.status),
[appliedBill],
); );
const visibleBills = useFilteredTableRows(rows, matchesBill);
const adjustmentImpact = adjustments const adjustmentImpact = adjustments
.filter((row) => row.status !== 'voided') .filter((row) => row.status !== 'voided')
.reduce( .reduce(
@@ -553,20 +587,19 @@ export default function PartnerPortal({
<ConsoleCollectionSearch> <ConsoleCollectionSearch>
<ConsoleFilterGrid <ConsoleFilterGrid
onReset={() => { onReset={() => {
billSearch.cancelPendingSearch();
setAppliedBill({ month: 'all', status: 'all' });
setBillMonth('all'); setBillMonth('all');
setBillStatus('all'); setBillStatus('all');
setBillPage(1); setBillPage(1);
}} }}
onSearch={() => setBillPage(1)} onSearch={billSearch.submitSearch}
> >
<ConsoleFilterField label={t('账期')} id='partner-bill-month'> <ConsoleFilterField label={t('账期')} id='partner-bill-month'>
<Select <Select
id='partner-bill-month' id='partner-bill-month'
value={billMonth} value={billMonth}
onChange={(value) => { onChange={billSearch.changeFilter(setBillMonth)}
setBillMonth(value);
setBillPage(1);
}}
optionList={[ optionList={[
{ value: 'all', label: t('全部账期') }, { value: 'all', label: t('全部账期') },
...Array.from(new Set(rows.map((row) => row.statement_month))) ...Array.from(new Set(rows.map((row) => row.statement_month)))
@@ -580,10 +613,7 @@ export default function PartnerPortal({
<Select <Select
id='partner-bill-status' id='partner-bill-status'
value={billStatus} value={billStatus}
onChange={(value) => { onChange={billSearch.changeFilter(setBillStatus)}
setBillStatus(value);
setBillPage(1);
}}
optionList={[ optionList={[
{ value: 'all', label: t('全部状态') }, { value: 'all', label: t('全部状态') },
...Array.from(new Set(rows.map((row) => row.status))).map( ...Array.from(new Set(rows.map((row) => row.status))).map(
@@ -609,8 +639,13 @@ export default function PartnerPortal({
dataSource={visibleBills} dataSource={visibleBills}
columns={billColumns} columns={billColumns}
pagination={ pagination={
visibleBills.length > 0 visibleBills.length > 0 || billPage > 1
? { pageSize: 10, current: billPage, onPageChange: setBillPage } ? {
pageSize: 10,
current: billPage,
onPageChange: setBillPage,
preservePage: true,
}
: false : false
} }
scroll={{ x: 1120 }} scroll={{ x: 1120 }}
@@ -738,10 +773,12 @@ export default function PartnerPortal({
<ConsoleCollectionSearch> <ConsoleCollectionSearch>
<ConsoleFilterGrid <ConsoleFilterGrid
onReset={() => { onReset={() => {
detailSearch.cancelPendingSearch();
setQuery(''); setQuery('');
setAppliedDetail('');
setDetailPage(1); setDetailPage(1);
}} }}
onSearch={() => setDetailPage(1)} onSearch={detailSearch.submitSearch}
> >
<ConsoleFilterField <ConsoleFilterField
label={t('搜索关键字')} label={t('搜索关键字')}
@@ -751,10 +788,7 @@ export default function PartnerPortal({
id='partner-bill-detail-query' id='partner-bill-detail-query'
prefix={<Search size={16} />} prefix={<Search size={16} />}
value={query} value={query}
onChange={(value) => { onChange={detailSearch.changeFilter(setQuery)}
setQuery(value);
setDetailPage(1);
}}
placeholder={t('搜索客户、模型、计费记录或档位')} placeholder={t('搜索客户、模型、计费记录或档位')}
showClear showClear
/> />
@@ -767,8 +801,9 @@ export default function PartnerPortal({
columns={BillingColumns(t, money, formatDateTime)} columns={BillingColumns(t, money, formatDateTime)}
scroll={{ x: 1800 }} scroll={{ x: 1800 }}
pagination={ pagination={
detailItems.length > 0 detailItems.length > 0 || detailPage > 1
? { ? {
preservePage: true,
pageSize: 10, pageSize: 10,
current: detailPage, current: detailPage,
onPageChange: setDetailPage, onPageChange: setDetailPage,
@@ -1000,11 +1035,13 @@ export default function PartnerPortal({
<ConsoleCollectionSearch> <ConsoleCollectionSearch>
<ConsoleFilterGrid <ConsoleFilterGrid
onReset={() => { onReset={() => {
customerSearch.cancelPendingSearch();
setAppliedCustomer({ keyword: '', status: 'all' });
setCustomerQuery(''); setCustomerQuery('');
setCustomerStatus('all'); setCustomerStatus('all');
setCustomerPage(1); setCustomerPage(1);
}} }}
onSearch={() => setCustomerPage(1)} onSearch={customerSearch.submitSearch}
> >
<ConsoleFilterField <ConsoleFilterField
label={t('搜索关键字')} label={t('搜索关键字')}
@@ -1014,10 +1051,7 @@ export default function PartnerPortal({
id='partner-customer-query' id='partner-customer-query'
prefix={<Search size={16} />} prefix={<Search size={16} />}
value={customerQuery} value={customerQuery}
onChange={(value) => { onChange={customerSearch.changeFilter(setCustomerQuery)}
setCustomerQuery(value);
setCustomerPage(1);
}}
showClear showClear
placeholder={t('搜索客户名称或编号')} placeholder={t('搜索客户名称或编号')}
/> />
@@ -1026,10 +1060,7 @@ export default function PartnerPortal({
<Select <Select
id='partner-customer-status' id='partner-customer-status'
value={customerStatus} value={customerStatus}
onChange={(value) => { onChange={customerSearch.changeFilter(setCustomerStatus)}
setCustomerStatus(value);
setCustomerPage(1);
}}
optionList={[ optionList={[
{ value: 'all', label: t('全部状态') }, { value: 'all', label: t('全部状态') },
...Array.from(new Set(customers.map((row) => row.status))).map( ...Array.from(new Set(customers.map((row) => row.status))).map(
@@ -1054,8 +1085,9 @@ export default function PartnerPortal({
rowKey='id' rowKey='id'
dataSource={visibleCustomers} dataSource={visibleCustomers}
pagination={ pagination={
visibleCustomers.length > 0 visibleCustomers.length > 0 || customerPage > 1
? { ? {
preservePage: true,
pageSize: 10, pageSize: 10,
current: customerPage, current: customerPage,
onPageChange: setCustomerPage, onPageChange: setCustomerPage,
+15 -14
View File
@@ -14,19 +14,20 @@ export function matchesStatus(row, status, key, now = Date.now() / 1000) {
return row.status === status; return row.status === status;
} }
export function filterCommissionRows(rows, filters, key, searchableText) { export function createCommissionRowFilter(filters, key, searchableText) {
const query = (filters.query || '').trim().toLocaleLowerCase(); const query = (filters.query || '').trim().toLocaleLowerCase();
return rows.filter( return (row) =>
(row) => matchesStatus(row, filters.status, key) &&
matchesStatus(row, filters.status, key) && (!filters.type ||
(!filters.type || (key === 'partners'
(key === 'partners' ? row.type
? row.type : key === 'tiers'
: key === 'tiers' ? row.source_type
? row.source_type : row.subject_type) === filters.type) &&
: row.subject_type) === filters.type) && (!filters.partner || Number(row.partner_id) === Number(filters.partner)) &&
(!filters.partner || (!query || searchableText(row).toLocaleLowerCase().includes(query));
Number(row.partner_id) === Number(filters.partner)) && }
(!query || searchableText(row).toLocaleLowerCase().includes(query)),
); export function filterCommissionRows(rows, filters, key, searchableText) {
return rows.filter(createCommissionRowFilter(filters, key, searchableText));
} }
+43 -43
View File
@@ -1,10 +1,12 @@
import { confirmTableAction } from '@/components/common/table/confirmTableAction'; import { confirmTableAction } from '@/components/common/table/confirmTableAction';
import TableStatusSwitch from '@/components/common/table/TableStatusSwitch'; import TableStatusSwitch from '@/components/common/table/TableStatusSwitch';
import TableEmpty from '../../components/common/table/TableEmpty'; import TableEmpty from '../../components/common/table/TableEmpty';
import React, { useEffect, useMemo, useRef, useState } from 'react'; import React, { useCallback, useMemo, useRef, useState } from 'react';
import { Banner, Button, Form, Modal, Spin } from '@/components/ui'; import { Banner, Button, Form, Modal, Spin } from '@/components/ui';
import { Button as AntButton } from 'antd'; import { Button as AntButton } from 'antd';
import { Download as ActionDownload } from '@/components/common/icons/ActionIcons'; import { Download as ActionDownload } from '@/components/common/icons/ActionIcons';
import { useFilterSearch } from '../../hooks/common/useFilterSearch';
import { useTableFilterQuery } from '../../hooks/common/useTableFilterQuery';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import CardPro from '../../components/common/ui/CardPro'; import CardPro from '../../components/common/ui/CardPro';
import CardTable from '../../components/common/ui/CardTable'; import CardTable from '../../components/common/ui/CardTable';
@@ -63,38 +65,40 @@ export default function DemoReservations() {
setQuery(update); setQuery(update);
}; };
useEffect(() => { const load = useCallback(
const controller = new AbortController(); (signal) => {
const { signal } = controller; setLoading(true);
setLoading(true); setError('');
setError(''); fetchDemoReservations(query, { signal })
let changedPage = false; .then((data) => {
fetchDemoReservations(query, { signal }) if (signal.aborted) return;
.then((data) => { setResult(data);
if (signal.aborted) return; })
const lastPage = Math.max(1, Math.ceil(data.total / data.page_size)); .catch((error) => {
if (data.items.length === 0 && query.page > lastPage) { if (!signal.aborted) {
changedPage = true; setError(error.message || '预约信息加载失败,请重新查询');
setSelectedRowKeys([]); setResult({ items: [], total: 0 });
setQuery((previous) => ({ ...previous, page: lastPage })); }
return; })
} .finally(() => {
setResult(data); if (!signal.aborted) setLoading(false);
setSelectedRowKeys((previous) => });
previous.filter((id) => data.items.some((item) => item.id === id)), },
); [query],
}) );
.catch((error) => { const { cancelQuery } = useTableFilterQuery(load);
if (!signal.aborted) { const { scheduleSearch, submitSearch, cancelPendingSearch } = useFilterSearch(
setError(error.message || '预约信息加载失败,请重新查询'); () => {
setResult({ items: [], total: 0 }); const values = formRef.current?.getValues() ?? EMPTY_FILTERS;
} setQuery((previous) => ({
}) ...previous,
.finally(() => { name: (values.name || '').trim(),
if (!signal.aborted && !changedPage) setLoading(false); contact: (values.contact || '').trim(),
}); companyName: (values.companyName || '').trim(),
return () => controller.abort(); }));
}, [query]); },
cancelQuery,
);
const fieldColumns = useMemo( const fieldColumns = useMemo(
() => () =>
@@ -222,6 +226,7 @@ export default function DemoReservations() {
const reset = () => { const reset = () => {
formRef.current?.reset(); formRef.current?.reset();
cancelPendingSearch();
changeQuery((previous) => ({ changeQuery((previous) => ({
...EMPTY_FILTERS, ...EMPTY_FILTERS,
page: 1, page: 1,
@@ -232,7 +237,8 @@ export default function DemoReservations() {
const changePageSize = (pageSize) => const changePageSize = (pageSize) =>
changeQuery((previous) => ({ ...previous, page: 1, pageSize })); changeQuery((previous) => ({ ...previous, page: 1, pageSize }));
const pagination = createCardProPagination({ const pagination = createCardProPagination({
currentPage: result.page ?? query.page, preservePage: true,
currentPage: query.page,
pageSize: result.page_size ?? query.pageSize, pageSize: result.page_size ?? query.pageSize,
total: result.total, total: result.total,
onPageChange: (page) => changeQuery((previous) => ({ ...previous, page })), onPageChange: (page) => changeQuery((previous) => ({ ...previous, page })),
@@ -268,15 +274,8 @@ export default function DemoReservations() {
<Form <Form
initValues={EMPTY_FILTERS} initValues={EMPTY_FILTERS}
getFormApi={(api) => (formRef.current = api)} getFormApi={(api) => (formRef.current = api)}
onSubmit={(values) => onSubmit={submitSearch}
changeQuery((previous) => ({ onValueChange={scheduleSearch}
name: (values.name || '').trim(),
contact: (values.contact || '').trim(),
companyName: (values.companyName || '').trim(),
page: 1,
pageSize: previous.pageSize,
}))
}
allowEmpty allowEmpty
autoComplete='off' autoComplete='off'
layout='vertical' layout='vertical'
@@ -325,6 +324,7 @@ export default function DemoReservations() {
columnWidth: 44, columnWidth: 44,
fixed: true, fixed: true,
selectedRowKeys, selectedRowKeys,
preserveSelectedRowKeys: true,
onChange: setSelectedRowKeys, onChange: setSelectedRowKeys,
getCheckboxProps: () => ({ disabled: busy }), getCheckboxProps: () => ({ disabled: busy }),
}} }}
+82 -84
View File
@@ -1,11 +1,5 @@
import { Download as ActionDownload } from '@/components/common/icons/ActionIcons'; import { Download as ActionDownload } from '@/components/common/icons/ActionIcons';
import React, { import React, { useCallback, useEffect, useMemo, useState } from 'react';
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { import {
Card, Card,
@@ -27,6 +21,8 @@ import {
AlertTriangle, AlertTriangle,
Users, Users,
} from 'lucide-react'; } from 'lucide-react';
import { useFilterSearch } from '../../hooks/common/useFilterSearch';
import { useTableFilterQuery } from '../../hooks/common/useTableFilterQuery';
import { API, showError } from '../../helpers'; import { API, showError } from '../../helpers';
import { exportToCsv, formatTimestampForCsv } from '../../helpers/exportCsv'; import { exportToCsv, formatTimestampForCsv } from '../../helpers/exportCsv';
@@ -114,6 +110,7 @@ export const ExperienceCenterAuditPanel = () => {
const [rangeHours, setRangeHours] = useState(24); const [rangeHours, setRangeHours] = useState(24);
const [eventFilter, setEventFilter] = useState(''); const [eventFilter, setEventFilter] = useState('');
const [filters, setFilters] = useState({ rangeHours: 24, eventFilter: '' });
const [page, setPage] = useState(1); const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(20); const [pageSize, setPageSize] = useState(20);
@@ -123,77 +120,83 @@ export const ExperienceCenterAuditPanel = () => {
const [topUsers, setTopUsers] = useState([]); const [topUsers, setTopUsers] = useState([]);
const [recent, setRecent] = useState({ items: [], total: 0 }); const [recent, setRecent] = useState({ items: [], total: 0 });
// 用单调递增的 request id 给"过期请求"的回写打钩。用户快速切 range/filter 时,多次
// loadAll 会并行飞,只有最后一次的结果应该落到 state — 否则慢响应回来会覆盖新数据,
// 出现"下拉显示 7d 但卡片是 1h 数据"的诡异 UI。
const requestIdRef = useRef(0);
// 单次刷新拉全部四块数据(并行)。任何子接口失败不阻塞其他块,避免一处出错全屏白屏 // 单次刷新拉全部四块数据(并行)。任何子接口失败不阻塞其他块,避免一处出错全屏白屏
const loadAll = useCallback(async () => { const loadAll = useCallback(
const myId = ++requestIdRef.current; async (signal) => {
setLoading(true); const { rangeHours, eventFilter } = filters;
const errors = []; setLoading(true);
const [summaryRes, trendRes, topUsersRes, recentRes] = await Promise.all([ const errors = [];
API.get( const [summaryRes, trendRes, topUsersRes, recentRes] = await Promise.all([
`/api/admin/playground/upload-audit/summary?range_hours=${rangeHours}`, API.get(
).catch((e) => { `/api/admin/playground/upload-audit/summary?range_hours=${rangeHours}`,
errors.push(['summary', e]); { signal },
return null; ).catch((e) => {
}), errors.push(['summary', e]);
API.get( return null;
`/api/admin/playground/upload-audit/trend?range_hours=${rangeHours}&bucket=${rangeHours > 48 ? 'day' : 'hour'}`,
).catch((e) => {
errors.push(['trend', e]);
return null;
}),
API.get(
`/api/admin/playground/upload-audit/top-failing-users?range_hours=${rangeHours}&limit=10`,
).catch((e) => {
errors.push(['top-users', e]);
return null;
}),
API.get(
`/api/admin/playground/upload-audit/recent?range_hours=${rangeHours}&event=${encodeURIComponent(eventFilter)}&page=${page}&page_size=${pageSize}`,
).catch((e) => {
errors.push(['recent', e]);
return null;
}),
]);
// 过期响应直接丢弃:myId 落后于最新 id 说明用户已经发起新请求了
if (myId !== requestIdRef.current) {
return;
}
if (summaryRes?.data?.success) setSummary(summaryRes.data.data);
if (trendRes?.data?.success) setTrend(trendRes.data.data);
if (topUsersRes?.data?.success)
setTopUsers(topUsersRes.data.data?.items || []);
if (recentRes?.data?.success) {
setRecent({
items: recentRes.data.data?.items || [],
total: recentRes.data.data?.total || 0,
});
}
// 多块同时失败时,单独把每一块的错误都告诉用户;showError 内部会去重处理(如果 message 一致)
if (errors.length > 0) {
// 把 4 块名字翻成可读:summary/trend/top-users/recent → 数据看板加载(部分失败)
Toast.warning({
content: t('数据加载部分失败:{{names}}', {
names: errors.map((e) => e[0]).join(', '),
}), }),
duration: 4, API.get(
}); `/api/admin/playground/upload-audit/trend?range_hours=${rangeHours}&bucket=${rangeHours > 48 ? 'day' : 'hour'}`,
// 同时把第一个 axios 错误细节也打到 Toast,方便定位(401/500 等) { signal },
showError(errors[0][1]); ).catch((e) => {
} errors.push(['trend', e]);
setLoading(false); return null;
}, [rangeHours, eventFilter, page, pageSize, t]); }),
API.get(
`/api/admin/playground/upload-audit/top-failing-users?range_hours=${rangeHours}&limit=10`,
{ signal },
).catch((e) => {
errors.push(['top-users', e]);
return null;
}),
API.get(
`/api/admin/playground/upload-audit/recent?range_hours=${rangeHours}&event=${encodeURIComponent(eventFilter)}&page=${page}&page_size=${pageSize}`,
{ signal },
).catch((e) => {
errors.push(['recent', e]);
return null;
}),
]);
useEffect(() => { if (signal.aborted) return;
loadAll();
}, [loadAll]); if (summaryRes?.data?.success) setSummary(summaryRes.data.data);
if (trendRes?.data?.success) setTrend(trendRes.data.data);
if (topUsersRes?.data?.success)
setTopUsers(topUsersRes.data.data?.items || []);
if (recentRes?.data?.success) {
setRecent({
items: recentRes.data.data?.items || [],
total: recentRes.data.data?.total || 0,
});
}
// 多块同时失败时,单独把每一块的错误都告诉用户;showError 内部会去重处理(如果 message 一致)
if (errors.length > 0) {
// 把 4 块名字翻成可读:summary/trend/top-users/recent → 数据看板加载(部分失败)
Toast.warning({
content: t('数据加载部分失败:{{names}}', {
names: errors.map((e) => e[0]).join(', '),
}),
duration: 4,
});
// 同时把第一个 axios 错误细节也打到 Toast,方便定位(401/500 等)
showError(errors[0][1]);
}
setLoading(false);
},
[filters, page, pageSize, t],
);
const { cancelQuery, reloadQuery } = useTableFilterQuery(loadAll);
const { changeFilter, submitSearch } = useFilterSearch(() => {
if (
filters.rangeHours === rangeHours &&
filters.eventFilter === eventFilter
) {
return reloadQuery();
}
setFilters({ rangeHours, eventFilter });
}, cancelQuery);
// ----- 趋势图 spec ----- // ----- 趋势图 spec -----
const chartSpec = useMemo(() => { const chartSpec = useMemo(() => {
@@ -368,17 +371,14 @@ export const ExperienceCenterAuditPanel = () => {
<div className='flex flex-wrap items-center justify-end gap-2'> <div className='flex flex-wrap items-center justify-end gap-2'>
<Select <Select
value={rangeHours} value={rangeHours}
onChange={(v) => { onChange={changeFilter(setRangeHours)}
setPage(1);
setRangeHours(v);
}}
optionList={RANGE_OPTIONS} optionList={RANGE_OPTIONS}
className='min-w-[140px]' className='min-w-[140px]'
/> />
<Button <Button
theme='light' theme='light'
icon={<IconRefresh />} icon={<IconRefresh />}
onClick={loadAll} onClick={submitSearch}
loading={loading} loading={loading}
> >
{t('刷新')} {t('刷新')}
@@ -483,10 +483,7 @@ export const ExperienceCenterAuditPanel = () => {
<div className='flex flex-wrap items-center justify-end gap-2'> <div className='flex flex-wrap items-center justify-end gap-2'>
<Select <Select
value={eventFilter} value={eventFilter}
onChange={(v) => { onChange={changeFilter(setEventFilter)}
setPage(1);
setEventFilter(v);
}}
optionList={EVENT_FILTERS} optionList={EVENT_FILTERS}
className='min-w-[160px]' className='min-w-[160px]'
size='small' size='small'
@@ -508,6 +505,7 @@ export const ExperienceCenterAuditPanel = () => {
size='small' size='small'
rowKey='id' rowKey='id'
pagination={{ pagination={{
preservePage: true,
currentPage: page, currentPage: page,
pageSize, pageSize,
total: recent.total, total: recent.total,
+31 -18
View File
@@ -38,6 +38,7 @@ import { ShieldCheck } from 'lucide-react';
import Joyride, { STATUS, ACTIONS, EVENTS } from 'react-joyride'; import Joyride, { STATUS, ACTIONS, EVENTS } from 'react-joyride';
import { useTokensData } from '../../hooks/tokens/useTokensData'; import { useTokensData } from '../../hooks/tokens/useTokensData';
import { useFilterSearch } from '../../hooks/common/useFilterSearch'; import { useFilterSearch } from '../../hooks/common/useFilterSearch';
import { filterTableRows } from '@/components/common/table/filterTableRows';
import { collectPagedItems } from '../../helpers/paging'; import { collectPagedItems } from '../../helpers/paging';
import EditTokenModal from '../../components/table/tokens/modals/EditTokenModal'; import EditTokenModal from '../../components/table/tokens/modals/EditTokenModal';
import { import {
@@ -737,44 +738,56 @@ const KeyManagement = ({ embedded = false }) => {
if (!handled) showInfo(t('暂无可用客服')); if (!handled) showInfo(t('暂无可用客服'));
}; };
const displayedPage = searchResult?.page ?? activePage;
const displayedPageSize = searchResult?.pageSize ?? pageSize; const displayedPageSize = searchResult?.pageSize ?? pageSize;
const listLoading = loading || searchLoading; const listLoading = loading || searchLoading;
const runSearch = async (value, page = 1) => { const runSearch = async (value, page, signal) => {
const id = ++searchRequest.current; const id = ++searchRequest.current;
const query = value.trim().toLowerCase(); const query = value.trim().toLowerCase();
if (!query) { if (!query) {
setSearchLoading(false); setSearchLoading(false);
setSearchResult(null); setSearchResult(null);
return loadTokens(1, displayedPageSize); return loadTokens(page, displayedPageSize, signal);
} }
setSearchLoading(true); setSearchLoading(true);
try { try {
const { items, total, message, truncated } = await collectPagedItems( const { items, total, message, truncated } = await collectPagedItems(
(p, size) => API.get('/api/token/', { params: { p, page_size: size } }), (p, size) =>
{ shouldAbort: () => id !== searchRequest.current }, API.get('/api/token/', { params: { p, page_size: size }, signal }),
{ shouldAbort: () => signal?.aborted || id !== searchRequest.current },
); );
if (id !== searchRequest.current) return; if (signal?.aborted || id !== searchRequest.current) return;
if (message || truncated || items.length < total) { if (message || truncated || items.length < total) {
showError(message || originalT('加载失败')); showError(message || originalT('加载失败'));
return; return;
} }
const matches = items.filter((token) => const matches = await filterTableRows(
[token.name, token.key, token.group].some((value) => items,
value?.toLowerCase().includes(query), (token) =>
), [
token.name,
token.key,
...(Array.isArray(token.group) ? token.group : [token.group]),
].some(
(value) =>
typeof value === 'string' && value.toLowerCase().includes(query),
),
signal,
); );
if (id !== searchRequest.current) return;
setSearchResult({ setSearchResult({
query, query,
items: matches, items: matches,
page: Math.min( page,
page,
Math.max(1, Math.ceil(matches.length / displayedPageSize)),
),
pageSize: displayedPageSize, pageSize: displayedPageSize,
}); });
} catch (error) { } catch (error) {
if (id === searchRequest.current && !error?.isAxiosError) { if (
!signal?.aborted &&
id === searchRequest.current &&
!error?.isAxiosError
) {
showError(originalT('加载失败')); showError(originalT('加载失败'));
} }
} finally { } finally {
@@ -783,7 +796,7 @@ const KeyManagement = ({ embedded = false }) => {
}; };
const { scheduleSearch, submitSearch, cancelPendingSearch } = useFilterSearch( const { scheduleSearch, submitSearch, cancelPendingSearch } = useFilterSearch(
(value = searchValue) => runSearch(value), (value = searchValue, signal) => runSearch(value, displayedPage, signal),
); );
useEffect( useEffect(
@@ -796,13 +809,12 @@ const KeyManagement = ({ embedded = false }) => {
const resetSearch = () => { const resetSearch = () => {
cancelPendingSearch(); cancelPendingSearch();
setSearchValue(''); setSearchValue('');
runSearch(''); runSearch('', 1);
}; };
const refreshKeyList = () => const refreshKeyList = () =>
searchResult ? runSearch(searchResult.query, searchResult.page) : refresh(); searchResult ? runSearch(searchResult.query, searchResult.page) : refresh();
const displayedPage = searchResult?.page ?? activePage;
const displayedTotal = searchResult?.items.length ?? tokenCount; const displayedTotal = searchResult?.items.length ?? tokenCount;
const displayedTokens = searchResult const displayedTokens = searchResult
? searchResult.items.slice( ? searchResult.items.slice(
@@ -1027,8 +1039,9 @@ const KeyManagement = ({ embedded = false }) => {
t={t} t={t}
/> />
{displayedTotal > 0 ? ( {displayedTotal > 0 || displayedPage > 1 ? (
<Pagination <Pagination
preservePage
className='km-pagination' className='km-pagination'
total={displayedTotal} total={displayedTotal}
currentPage={displayedPage} currentPage={displayedPage}
+26 -10
View File
@@ -6,13 +6,15 @@ import {
ConsoleFilterField, ConsoleFilterField,
ConsoleFilterGrid, ConsoleFilterGrid,
} from '@/components/console/ConsolePrimitives'; } from '@/components/console/ConsolePrimitives';
import React, { useEffect, useState } from 'react'; import React, { useCallback, useEffect, useState } from 'react';
import { getQuotaPerUnit } from '../../helpers'; import { getQuotaPerUnit } from '../../helpers';
import { timestamp2string } from '../../helpers/utils'; import { timestamp2string } from '../../helpers/utils';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { Tabs as AntTabs } from 'antd'; import { Tabs as AntTabs } from 'antd';
import { Table, Select, Button, Tag, Tooltip } from '@/components/ui'; import { Table, Select, Button, Tag, Tooltip } from '@/components/ui';
import { API } from '../../helpers/api'; import { API } from '../../helpers/api';
import { useFilterSearch } from '../../hooks/common/useFilterSearch';
import { useTableFilterQuery } from '../../hooks/common/useTableFilterQuery';
import { useOrgAuditLogs } from '../../hooks/org/useOrgData'; import { useOrgAuditLogs } from '../../hooks/org/useOrgData';
import OrgPageHeader from './components/OrgPageHeader'; import OrgPageHeader from './components/OrgPageHeader';
import { OrgListCard } from './components/OrgListCard'; import { OrgListCard } from './components/OrgListCard';
@@ -203,15 +205,27 @@ const OrgAudit = ({ orgId }) => {
const [page, setPage] = useState(1); const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(20); const [pageSize, setPageSize] = useState(20);
const [actionFilter, setActionFilter] = useState(''); const [actionFilter, setActionFilter] = useState('');
const [appliedAction, setAppliedAction] = useState('');
const [queryVersion, setQueryVersion] = useState(0);
const [activeTab, setActiveTab] = useState('operations'); const [activeTab, setActiveTab] = useState('operations');
// 提示词记录 tab 由企业 feature flag(prompt_archive)控制显隐 // 提示词记录 tab 由企业 feature flag(prompt_archive)控制显隐
const [promptArchiveEnabled, setPromptArchiveEnabled] = useState(false); const [promptArchiveEnabled, setPromptArchiveEnabled] = useState(false);
// 且需当前用户具备查看权限(owner 恒真;admin 需 owner 授予),与后端 RequireOrgAdminPermission 对齐 // 且需当前用户具备查看权限(owner 恒真;admin 需 owner 授予),与后端 RequireOrgAdminPermission 对齐
const [canViewPromptRecords, setCanViewPromptRecords] = useState(false); const [canViewPromptRecords, setCanViewPromptRecords] = useState(false);
useEffect(() => { const query = useCallback(
fetch(page, pageSize, actionFilter); (signal) => fetch(page, pageSize, appliedAction, signal),
}, [fetch, page, pageSize, actionFilter]); [fetch, page, pageSize, appliedAction],
);
const { cancelQuery } = useTableFilterQuery(query, queryVersion);
const refresh = () => setQueryVersion((key) => key + 1);
const { changeFilter, submitSearch, cancelPendingSearch } = useFilterSearch(
() => {
setAppliedAction(actionFilter);
refresh();
},
cancelQuery,
);
useEffect(() => { useEffect(() => {
if (!orgId) return; if (!orgId) return;
@@ -377,22 +391,23 @@ const OrgAudit = ({ orgId }) => {
}, },
]; ];
const refresh = () => fetch(page, pageSize, actionFilter); const resetFilters = () => {
// 选择即筛选(原交互):与原页头 Select 的 onChange 相同 cancelPendingSearch();
const applyAction = (v) => { setActionFilter('');
setActionFilter(v ?? ''); setAppliedAction('');
setPage(1); setPage(1);
refresh();
}; };
const operations = ( const operations = (
<div className='oc-audit-stack'> <div className='oc-audit-stack'>
<ConsoleCollectionSearch className='oc-audit-filter'> <ConsoleCollectionSearch className='oc-audit-filter'>
<ConsoleFilterGrid onReset={() => applyAction('')} onSearch={refresh}> <ConsoleFilterGrid onReset={resetFilters} onSearch={submitSearch}>
<ConsoleFilterField label={t('操作类型')} id='org-audit-action-type'> <ConsoleFilterField label={t('操作类型')} id='org-audit-action-type'>
<Select <Select
id='org-audit-action-type' id='org-audit-action-type'
value={actionFilter} value={actionFilter}
onChange={applyAction} onChange={changeFilter((value) => setActionFilter(value ?? ''))}
optionList={actionOptions} optionList={actionOptions}
placeholder={t('全部操作')} placeholder={t('全部操作')}
filter filter
@@ -420,6 +435,7 @@ const OrgAudit = ({ orgId }) => {
rowKey='id' rowKey='id'
scroll={{ x: 1140 }} scroll={{ x: 1140 }}
pagination={{ pagination={{
preservePage: true,
currentPage: page, currentPage: page,
pageSize, pageSize,
total, total,
+26 -14
View File
@@ -14,6 +14,7 @@ import React, {
} from 'react'; } from 'react';
import { timestamp2string } from '../../helpers/utils'; import { timestamp2string } from '../../helpers/utils';
import { isMiniProgramWebView } from '../../helpers/miniProgram'; import { isMiniProgramWebView } from '../../helpers/miniProgram';
import { useFilterSearch } from '../../hooks/common/useFilterSearch';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { Link, useNavigate } from 'react-router-dom'; import { Link, useNavigate } from 'react-router-dom';
import { Users, Key, ArrowRight, FileText, Activity } from 'lucide-react'; import { Users, Key, ArrowRight, FileText, Activity } from 'lucide-react';
@@ -108,7 +109,7 @@ const MemberUsageSheet = ({ visible, onClose, member, orgId, t }) => {
const pageSizeRef = useRef(20); const pageSizeRef = useRef(20);
const fetchLogs = useCallback( const fetchLogs = useCallback(
async (p = 1, filters = appliedFilters, size = pageSize) => { async (p = 1, filters = appliedFilters, size = pageSize, signal) => {
if (!member || !orgId) return; if (!member || !orgId) return;
const seq = ++requestSeq.current; const seq = ++requestSeq.current;
setLoading(true); setLoading(true);
@@ -122,8 +123,11 @@ const MemberUsageSheet = ({ visible, onClose, member, orgId, t }) => {
} }
if (filters.modelName) if (filters.modelName)
url += `&model_name=${encodeURIComponent(filters.modelName)}`; url += `&model_name=${encodeURIComponent(filters.modelName)}`;
const res = await API.get(url, { headers: getOrgHeaders(orgId) }); const res = await API.get(url, {
if (seq !== requestSeq.current) return; headers: getOrgHeaders(orgId),
signal,
});
if (signal?.aborted || seq !== requestSeq.current) return;
if (res.data.success) { if (res.data.success) {
setLogs(res.data.data?.items || []); setLogs(res.data.data?.items || []);
// 后端在翻页(page>1)时跳过 COUNT 并返回 total=-1,保留首页已知总数, // 后端在翻页(page>1)时跳过 COUNT 并返回 total=-1,保留首页已知总数,
@@ -137,7 +141,8 @@ const MemberUsageSheet = ({ visible, onClose, member, orgId, t }) => {
showError(res.data.message); showError(res.data.message);
} }
} catch (err) { } catch (err) {
if (seq === requestSeq.current) showError(err.message); if (!signal?.aborted && seq === requestSeq.current && !err.isAxiosError)
showError(err.message);
} finally { } finally {
if (seq === requestSeq.current) setLoading(false); if (seq === requestSeq.current) setLoading(false);
} }
@@ -180,11 +185,13 @@ const MemberUsageSheet = ({ visible, onClose, member, orgId, t }) => {
} }
}, [visible, member, orgId]); }, [visible, member, orgId]);
const handleSearch = () => { const { changeFilter, submitSearch, cancelPendingSearch } = useFilterSearch(
const filters = { dateRange, modelName: modelName.trim() }; (_, signal) => {
setAppliedFilters(filters); const filters = { dateRange, modelName: modelName.trim() };
fetchLogs(1, filters); setAppliedFilters(filters);
}; return fetchLogs(page, filters, pageSize, signal);
},
);
const logColumns = useMemo( const logColumns = useMemo(
() => [ () => [
@@ -247,7 +254,10 @@ const MemberUsageSheet = ({ visible, onClose, member, orgId, t }) => {
</div> </div>
} }
visible={visible} visible={visible}
onCancel={onClose} onCancel={() => {
cancelPendingSearch();
onClose();
}}
placement='right' placement='right'
width={640} width={640}
bodyStyle={{ background: 'var(--ui-color-bg-0)' }} bodyStyle={{ background: 'var(--ui-color-bg-0)' }}
@@ -268,10 +278,11 @@ const MemberUsageSheet = ({ visible, onClose, member, orgId, t }) => {
{t('时间范围')} {t('时间范围')}
</div> </div>
<DatePicker <DatePicker
tableFilter
type='dateTimeRange' type='dateTimeRange'
density='compact' density='compact'
value={dateRange} value={dateRange}
onChange={setDateRange} onChange={changeFilter(setDateRange)}
placeholder={[t('开始时间'), t('结束时间')]} placeholder={[t('开始时间'), t('结束时间')]}
style={{ width: '100%' }} style={{ width: '100%' }}
/> />
@@ -284,15 +295,15 @@ const MemberUsageSheet = ({ visible, onClose, member, orgId, t }) => {
size='small' size='small'
placeholder={t('输入模型名称')} placeholder={t('输入模型名称')}
value={modelName} value={modelName}
onChange={setModelName} onChange={changeFilter(setModelName)}
onEnterPress={handleSearch} onEnterPress={submitSearch}
/> />
</div> </div>
<Button <Button
size='small' size='small'
theme='solid' theme='solid'
icon={<ActionSearch size={14} />} icon={<ActionSearch size={14} />}
onClick={handleSearch} onClick={submitSearch}
loading={loading} loading={loading}
> >
{t('查询')} {t('查询')}
@@ -317,6 +328,7 @@ const MemberUsageSheet = ({ visible, onClose, member, orgId, t }) => {
size='small' size='small'
loading={loading} loading={loading}
pagination={{ pagination={{
preservePage: true,
currentPage: page, currentPage: page,
pageSize, pageSize,
total, total,
+35 -19
View File
@@ -8,6 +8,7 @@ import {
} from '@/components/common/icons/ActionIcons'; } from '@/components/common/icons/ActionIcons';
import TableEmpty from '../../components/common/table/TableEmpty'; import TableEmpty from '../../components/common/table/TableEmpty';
import React, { useEffect, useState, useMemo, useCallback } from 'react'; import React, { useEffect, useState, useMemo, useCallback } from 'react';
import { useFilterSearch } from '../../hooks/common/useFilterSearch';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { Wallet, Zap, BarChart3 } from 'lucide-react'; import { Wallet, Zap, BarChart3 } from 'lucide-react';
import { Card as AntCard, Form as AntForm, Tabs as AntTabs } from 'antd'; import { Card as AntCard, Form as AntForm, Tabs as AntTabs } from 'antd';
@@ -329,29 +330,39 @@ const OrgLogs = ({ orgId, orgRole, isDeptManager = false }) => {
// 普通「查询」走缓存,相同条件重复查询不再压数据库。 // 普通「查询」走缓存,相同条件重复查询不再压数据库。
// 默认时间范围未被手动改动时,以当前时刻为终点重新计算(滚动最近 7 天), // 默认时间范围未被手动改动时,以当前时刻为终点重新计算(滚动最近 7 天),
// 确保「刷新」能纳入页面打开后新增的日志。 // 确保「刷新」能纳入页面打开后新增的日志。
const handleSearch = (forceRefresh = false) => { const handleSearch = async (forceRefresh = false, signal) => {
const range = isDefaultRange ? getDefaultDateRange() : dateRange; const range = isDefaultRange ? getDefaultDateRange() : dateRange;
if (isDefaultRange) setDateRange(range); if (isDefaultRange) setDateRange(range);
const filters = buildFilters(range); const filters = buildFilters(range);
setAppliedFilters(filters); setAppliedFilters(filters);
fetch(1, pageSize, filters); const requests = [
fetchStat(filters, forceRefresh); fetch(page, pageSize, filters, signal),
fetchStat(filters, forceRefresh, signal),
];
if (canViewTeamUsage) { if (canViewTeamUsage) {
fetchRanking( requests.push(
{ fetchRanking(
userId: filters.userId, {
startTimestamp: filters.startTimestamp, userId: filters.userId,
endTimestamp: filters.endTimestamp, startTimestamp: filters.startTimestamp,
modelName: filters.modelName, endTimestamp: filters.endTimestamp,
}, modelName: filters.modelName,
forceRefresh, },
forceRefresh,
signal,
),
); );
} }
setPage(1); await Promise.all(requests);
}; };
const { changeFilter, submitSearch, cancelPendingSearch } = useFilterSearch(
(forceRefresh, signal) => handleSearch(forceRefresh, signal),
);
// 重置:回到默认状态(滚动最近 7 天、不限成员/模型) // 重置:回到默认状态(滚动最近 7 天、不限成员/模型)
const handleReset = () => { const handleReset = () => {
cancelPendingSearch();
const range = getDefaultDateRange(); const range = getDefaultDateRange();
const filters = rangeToFilters(range); const filters = rangeToFilters(range);
setSelectedUserId(''); setSelectedUserId('');
@@ -846,7 +857,7 @@ const OrgLogs = ({ orgId, orgRole, isDeptManager = false }) => {
requiredMark={false} requiredMark={false}
autoComplete='off' autoComplete='off'
className='usage-record-filter-form' className='usage-record-filter-form'
onFinish={() => handleSearch(false)} onFinish={submitSearch}
> >
<div className='usage-record-filter-grid'> <div className='usage-record-filter-grid'>
<AntForm.Item <AntForm.Item
@@ -856,12 +867,13 @@ const OrgLogs = ({ orgId, orgRole, isDeptManager = false }) => {
> >
<DatePicker <DatePicker
id={{ start: 'org-logs-start' }} id={{ start: 'org-logs-start' }}
tableFilter
type='dateTimeRange' type='dateTimeRange'
value={dateRange} value={dateRange}
onChange={(v) => { onChange={changeFilter((value) => {
setDateRange(v); setDateRange(value);
setIsDefaultRange(false); setIsDefaultRange(false);
}} })}
placeholder={[t('开始时间'), t('结束时间')]} placeholder={[t('开始时间'), t('结束时间')]}
/> />
</AntForm.Item> </AntForm.Item>
@@ -873,7 +885,7 @@ const OrgLogs = ({ orgId, orgRole, isDeptManager = false }) => {
<Select <Select
id='org-logs-member' id='org-logs-member'
value={selectedUserId} value={selectedUserId}
onChange={setSelectedUserId} onChange={changeFilter(setSelectedUserId)}
optionList={memberOptions} optionList={memberOptions}
placeholder={isAdmin ? t('全部成员') : t('全部部门成员')} placeholder={isAdmin ? t('全部成员') : t('全部部门成员')}
filter filter
@@ -887,7 +899,7 @@ const OrgLogs = ({ orgId, orgRole, isDeptManager = false }) => {
id='org-logs-model' id='org-logs-model'
placeholder={t('请输入模型名称')} placeholder={t('请输入模型名称')}
value={modelName} value={modelName}
onChange={setModelName} onChange={changeFilter(setModelName)}
showClear showClear
/> />
</AntForm.Item> </AntForm.Item>
@@ -918,7 +930,10 @@ const OrgLogs = ({ orgId, orgRole, isDeptManager = false }) => {
</Button> </Button>
<Button <Button
icon={<ActionRefreshCw size={16} />} icon={<ActionRefreshCw size={16} />}
onClick={() => handleSearch(true)} onClick={() => {
cancelPendingSearch();
handleSearch(true);
}}
loading={loading} loading={loading}
> >
{t('刷新')} {t('刷新')}
@@ -944,6 +959,7 @@ const OrgLogs = ({ orgId, orgRole, isDeptManager = false }) => {
rowKey='id' rowKey='id'
scroll={{ x: 1285 }} scroll={{ x: 1285 }}
pagination={{ pagination={{
preservePage: true,
currentPage: page, currentPage: page,
pageSize, pageSize,
total, total,
+25 -16
View File
@@ -4,7 +4,9 @@ import {
Search as ActionSearch, Search as ActionSearch,
RefreshCw as ActionRefreshCw, RefreshCw as ActionRefreshCw,
} from '@/components/common/icons/ActionIcons'; } from '@/components/common/icons/ActionIcons';
import React, { useEffect, useMemo, useState } from 'react'; import { useFilterSearch } from '../../hooks/common/useFilterSearch';
import { useTableFilterQuery } from '../../hooks/common/useTableFilterQuery';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import i18next from 'i18next'; import i18next from 'i18next';
import { Form as AntForm } from 'antd'; import { Form as AntForm } from 'antd';
@@ -233,17 +235,22 @@ const OrgPromptRecords = ({ orgId }) => {
}; };
}, [orgId, t]); }, [orgId, t]);
useEffect(() => { const [refreshKey, setRefreshKey] = useState(0);
if (membersLoading) return; const query = useCallback(
fetch(page, pageSize, appliedFilters); (signal) => {
}, [appliedFilters, fetch, membersLoading, page, pageSize]); if (!membersLoading) return fetch(page, pageSize, appliedFilters, signal);
},
const applyFilter = () => { [appliedFilters, fetch, membersLoading, page, pageSize],
setAppliedFilters(buildFilters()); );
setPage(1); const { cancelQuery } = useTableFilterQuery(query, refreshKey);
}; const { changeFilter, submitSearch, cancelPendingSearch } = useFilterSearch(
() => setAppliedFilters(buildFilters()),
cancelQuery,
);
const resetFilters = () => { const resetFilters = () => {
cancelPendingSearch();
setRefreshKey((key) => key + 1);
setSelectedMemberId(''); setSelectedMemberId('');
setModelName(''); setModelName('');
setKeyword(''); setKeyword('');
@@ -531,7 +538,7 @@ const OrgPromptRecords = ({ orgId }) => {
requiredMark={false} requiredMark={false}
autoComplete='off' autoComplete='off'
className='usage-record-filter-form' className='usage-record-filter-form'
onFinish={applyFilter} onFinish={submitSearch}
> >
<div className='usage-record-filter-grid'> <div className='usage-record-filter-grid'>
<AntForm.Item <AntForm.Item
@@ -541,9 +548,10 @@ const OrgPromptRecords = ({ orgId }) => {
> >
<DatePicker <DatePicker
id={{ start: 'org-prompts-start' }} id={{ start: 'org-prompts-start' }}
tableFilter
type='dateTimeRange' type='dateTimeRange'
value={timeRange} value={timeRange}
onChange={setTimeRange} onChange={changeFilter(setTimeRange)}
placeholder={[t('开始时间'), t('结束时间')]} placeholder={[t('开始时间'), t('结束时间')]}
/> />
</AntForm.Item> </AntForm.Item>
@@ -551,7 +559,7 @@ const OrgPromptRecords = ({ orgId }) => {
<Select <Select
id='org-prompts-member' id='org-prompts-member'
value={selectedMemberId} value={selectedMemberId}
onChange={setSelectedMemberId} onChange={changeFilter(setSelectedMemberId)}
optionList={memberOptions} optionList={memberOptions}
placeholder={t('全部成员')} placeholder={t('全部成员')}
loading={membersLoading} loading={membersLoading}
@@ -562,7 +570,7 @@ const OrgPromptRecords = ({ orgId }) => {
<Input <Input
id='org-prompts-model' id='org-prompts-model'
value={modelName} value={modelName}
onChange={setModelName} onChange={changeFilter(setModelName)}
placeholder={t('输入模型名称')} placeholder={t('输入模型名称')}
showClear showClear
/> />
@@ -571,7 +579,7 @@ const OrgPromptRecords = ({ orgId }) => {
<Input <Input
id='org-prompts-keyword' id='org-prompts-keyword'
value={keyword} value={keyword}
onChange={setKeyword} onChange={changeFilter(setKeyword)}
placeholder={t('搜索提示词关键词')} placeholder={t('搜索提示词关键词')}
showClear showClear
/> />
@@ -604,7 +612,7 @@ const OrgPromptRecords = ({ orgId }) => {
actions={ actions={
<Button <Button
icon={<ActionRefreshCw size={14} />} icon={<ActionRefreshCw size={14} />}
onClick={() => fetch(page, pageSize, appliedFilters)} onClick={() => setRefreshKey((key) => key + 1)}
loading={loading || membersLoading} loading={loading || membersLoading}
> >
{t('刷新')} {t('刷新')}
@@ -625,6 +633,7 @@ const OrgPromptRecords = ({ orgId }) => {
onRow={() => ({ className: 'cursor-pointer' })} onRow={() => ({ className: 'cursor-pointer' })}
scroll={{ x: 'max(100%, 1400px)' }} scroll={{ x: 'max(100%, 1400px)' }}
pagination={{ pagination={{
preservePage: true,
currentPage: page, currentPage: page,
pageSize, pageSize,
total, total,
@@ -8,6 +8,8 @@ import React, {
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { Activity } from 'lucide-react'; import { Activity } from 'lucide-react';
import { Button, Select, Spin, Switch, Table, Tag } from '@/components/ui'; import { Button, Select, Spin, Switch, Table, Tag } from '@/components/ui';
import { useFilterSearch } from '@/hooks/common/useFilterSearch';
import { useTableFilterQuery } from '@/hooks/common/useTableFilterQuery';
import { API } from '../../../helpers/api'; import { API } from '../../../helpers/api';
import { showError } from '../../../helpers'; import { showError } from '../../../helpers';
import OrgPanel from '../components/OrgPanel'; import OrgPanel from '../components/OrgPanel';
@@ -35,12 +37,8 @@ const OrgDsHitLogs = ({ orgId }) => {
const [onlySensitive, setOnlySensitive] = useState(false); const [onlySensitive, setOnlySensitive] = useState(false);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [loadError, setLoadError] = useState(false); const [loadError, setLoadError] = useState(false);
// 请求代次守卫:快速切换时间窗/筛选/翻页时,旧请求的迟到响应不得覆盖新状态——
// 否则统计牌标着"近 30 天"显示的却是 24 小时的迟到数据(R39 修复)。
const statsSeqRef = useRef(0); const statsSeqRef = useRef(0);
const logsSeqRef = useRef(0); const [query, setQuery] = useState({ page: 1, sensitiveOnly: false });
// 记录最后一次尝试的页码:翻页失败后"重试"应重放失败的那次动作,而不是回到上次成功页
const lastAttemptedPageRef = useRef(1);
const fetchStats = useCallback( const fetchStats = useCallback(
async (hours) => { async (hours) => {
@@ -69,17 +67,16 @@ const OrgDsHitLogs = ({ orgId }) => {
); );
const fetchLogs = useCallback( const fetchLogs = useCallback(
async (p, sensitiveOnly) => { async (signal) => {
const seq = ++logsSeqRef.current; const { page: p, sensitiveOnly } = query;
lastAttemptedPageRef.current = p;
setLoading(true); setLoading(true);
setLoadError(false); setLoadError(false);
try { try {
const res = await API.get( const res = await API.get(
`/api/org/data-security/logs?page=${p}&page_size=${pageSize}&only_sensitive=${sensitiveOnly}`, `/api/org/data-security/logs?page=${p}&page_size=${pageSize}&only_sensitive=${sensitiveOnly}`,
{ headers }, { headers, signal },
); );
if (seq !== logsSeqRef.current) return; if (signal.aborted) return;
if (res.data.success) { if (res.data.success) {
setLogs(res.data.data?.items || []); setLogs(res.data.data?.items || []);
setTotal(res.data.data?.total || 0); setTotal(res.data.data?.total || 0);
@@ -89,23 +86,27 @@ const OrgDsHitLogs = ({ orgId }) => {
showError(res.data.message || t('加载命中审计失败')); showError(res.data.message || t('加载命中审计失败'));
} }
} catch (err) { } catch (err) {
if (seq !== logsSeqRef.current) return; if (signal.aborted) return;
setLoadError(true); setLoadError(true);
if (err?.name !== 'AxiosError') showError(err); if (err?.name !== 'AxiosError') showError(err);
} finally { } finally {
if (seq === logsSeqRef.current) setLoading(false); if (!signal.aborted) setLoading(false);
} }
}, },
[headers, t, pageSize], [headers, t, pageSize, query],
); );
useEffect(() => { useEffect(() => {
fetchStats(windowHours); fetchStats(windowHours);
}, [fetchStats, windowHours]); }, [fetchStats, windowHours]);
useEffect(() => { const { cancelQuery, reloadQuery } = useTableFilterQuery(fetchLogs);
fetchLogs(1, onlySensitive); const { scheduleSearch, cancelPendingSearch } = useFilterSearch(
}, [fetchLogs, onlySensitive]); (sensitiveOnly) => {
setQuery({ page, sensitiveOnly });
},
cancelQuery,
);
const w = stats?.window_stats || {}; const w = stats?.window_stats || {};
// 统计未就绪/失败时显示 '-' 而非 0:0 是一个有含义的合规结论,不能由失败态冒充 // 统计未就绪/失败时显示 '-' 而非 0:0 是一个有含义的合规结论,不能由失败态冒充
@@ -202,7 +203,10 @@ const OrgDsHitLogs = ({ orgId }) => {
<div className='flex items-center gap-2'> <div className='flex items-center gap-2'>
<Switch <Switch
checked={onlySensitive} checked={onlySensitive}
onChange={setOnlySensitive} onChange={(value) => {
setOnlySensitive(value);
scheduleSearch(value);
}}
size='small' size='small'
/> />
<span className='text-sm text-gray-600 dark:text-gray-300'> <span className='text-sm text-gray-600 dark:text-gray-300'>
@@ -216,8 +220,7 @@ const OrgDsHitLogs = ({ orgId }) => {
theme='light' theme='light'
onClick={() => { onClick={() => {
if (statsError) fetchStats(windowHours); if (statsError) fetchStats(windowHours);
if (loadError) if (loadError) void reloadQuery();
fetchLogs(lastAttemptedPageRef.current, onlySensitive);
}} }}
> >
{t('加载失败,点击重试')} {t('加载失败,点击重试')}
@@ -242,13 +245,19 @@ const OrgDsHitLogs = ({ orgId }) => {
</span> </span>
} }
pagination={{ pagination={{
preservePage: true,
currentPage: page, currentPage: page,
pageSize, pageSize,
total, total,
onPageChange: (p) => fetchLogs(p, onlySensitive), onPageChange: (p) => {
cancelPendingSearch();
setQuery({ page: p, sensitiveOnly: onlySensitive });
},
onPageSizeChange: (size) => { onPageSizeChange: (size) => {
cancelPendingSearch();
setPage(1); setPage(1);
setPageSize(size); setPageSize(size);
setQuery({ page: 1, sensitiveOnly: onlySensitive });
}, },
}} }}
/> />
@@ -90,7 +90,7 @@ const DeptFundsPanel = ({ orgId, deptId, deptName, refreshKey }) => {
}, [load, refreshKey]); }, [load, refreshKey]);
const fetchLedger = useCallback( const fetchLedger = useCallback(
(id, params) => deptFundApi.ledger(orgId, id, params), (id, params, signal) => deptFundApi.ledger(orgId, id, params, signal),
[orgId], [orgId],
); );
const tree = useMemo(() => buildFundTree(rows, deptId), [rows, deptId]); const tree = useMemo(() => buildFundTree(rows, deptId), [rows, deptId]);
+68 -53
View File
@@ -1,10 +1,11 @@
import { formatIdReference } from '../../../helpers/safeDisplay'; import { formatIdReference } from '../../../helpers/safeDisplay';
import React, { useCallback, useEffect, useRef, useState } from 'react'; import React, { useCallback, useRef, useState } from 'react';
import { useFilterSearch } from '../../../hooks/common/useFilterSearch';
import { useTableFilterQuery } from '../../../hooks/common/useTableFilterQuery';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { Button, DatePicker, Select, Spin, Tag, Typography } from 'antd'; import { Button, Select, Spin, Tag, Typography } from 'antd';
import dayjs from 'dayjs'; import { DatePicker, Table } from '@/components/ui';
import { Table } from '@/components/ui';
import { RefreshCw } from '@/components/common/icons/ActionIcons'; import { RefreshCw } from '@/components/common/icons/ActionIcons';
import OrgSideSheet from '../components/OrgSideSheet'; import OrgSideSheet from '../components/OrgSideSheet';
import OrgStateBlock from '../components/OrgStateBlock'; import OrgStateBlock from '../components/OrgStateBlock';
@@ -32,6 +33,7 @@ const FundLedgerSheet = ({ visible, account, fetchLedger, onClose }) => {
const { t } = useTranslation(); const { t } = useTranslation();
const [range, setRange] = useState(defaultRange); const [range, setRange] = useState(defaultRange);
const [types, setTypes] = useState([]); const [types, setTypes] = useState([]);
const [applied, setApplied] = useState(() => ({ range, types }));
const [page, setPage] = useState(1); const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(DEFAULT_PAGE_SIZE); const [pageSize, setPageSize] = useState(DEFAULT_PAGE_SIZE);
const [items, setItems] = useState([]); const [items, setItems] = useState([]);
@@ -43,43 +45,57 @@ const FundLedgerSheet = ({ visible, account, fetchLedger, onClose }) => {
// 请求序号:快速改筛选或翻页时只采纳最后一次请求的结果。 // 请求序号:快速改筛选或翻页时只采纳最后一次请求的结果。
const seqRef = useRef(0); const seqRef = useRef(0);
const load = useCallback(async () => { const load = useCallback(
if (!visible || !account?.id) return; async (signal) => {
const [start, end] = range || []; const { range, types } = applied;
if (start && end && start > end) { if (!visible || !account?.id) return;
setRangeError(t('开始时间不能晚于结束时间')); const [start, end] = range || [];
return; if (start && end && start > end) {
} setRangeError(t('开始时间不能晚于结束时间'));
setRangeError(''); setLoading(false);
const seq = ++seqRef.current; return;
setLoading(true);
setError('');
try {
const res = await fetchLedger(account.id, {
start_timestamp: start ? Math.floor(start.getTime() / 1000) : undefined,
end_timestamp: end ? Math.floor(end.getTime() / 1000) : undefined,
type: types.length ? types.join(',') : undefined,
p: page,
page_size: pageSize,
});
if (seq !== seqRef.current) return;
if (res?.data?.success) {
setItems(res.data.data?.items || []);
setTotal(res.data.data?.total || 0);
} else {
setError(res?.data?.message || t('加载失败,请重试'));
} }
} catch { setRangeError('');
// 保留旧数据并标识刷新失败,不把旧数据冒充为最新 const seq = ++seqRef.current;
if (seq === seqRef.current) setError(t('数据刷新失败,请重试')); setLoading(true);
} finally { setError('');
if (seq === seqRef.current) setLoading(false); try {
} const res = await fetchLedger(
}, [visible, account?.id, range, types, page, pageSize, fetchLedger, t]); account.id,
{
start_timestamp: start
? Math.floor(start.getTime() / 1000)
: undefined,
end_timestamp: end ? Math.floor(end.getTime() / 1000) : undefined,
type: types.length ? types.join(',') : undefined,
p: page,
page_size: pageSize,
},
signal,
);
if (signal?.aborted || seq !== seqRef.current) return;
if (res?.data?.success) {
setItems(res.data.data?.items || []);
setTotal(res.data.data?.total || 0);
} else {
setError(res?.data?.message || t('加载失败,请重试'));
}
} catch {
// 保留旧数据并标识刷新失败,不把旧数据冒充为最新
if (!signal?.aborted && seq === seqRef.current)
setError(t('数据刷新失败,请重试'));
} finally {
if (seq === seqRef.current) setLoading(false);
}
},
[visible, account?.id, applied, page, pageSize, fetchLedger, t],
);
useEffect(() => { const { cancelQuery } = useTableFilterQuery(load);
load(); const { changeFilter, submitSearch } = useFilterSearch(
}, [load]); () => setApplied({ range, types }),
cancelQuery,
);
const isConsume = (r) => const isConsume = (r) =>
r.entry_type === 'consume' || r.entry_type === 'consume_adjust'; r.entry_type === 'consume' || r.entry_type === 'consume_adjust';
@@ -192,14 +208,11 @@ const FundLedgerSheet = ({ visible, account, fetchLedger, onClose }) => {
title={`${t('资金流水')} · ${account?.name || ''}`} title={`${t('资金流水')} · ${account?.name || ''}`}
> >
<div className='flex flex-wrap items-center gap-2 mb-3'> <div className='flex flex-wrap items-center gap-2 mb-3'>
{/* 状态仍为 Date[](请求换算不变),仅在控件边界与 dayjs 互转 */} <DatePicker
<DatePicker.RangePicker tableFilter
showTime type='dateTimeRange'
value={range?.length ? range.map((d) => dayjs(d)) : null} value={range}
onChange={(v) => { onChange={changeFilter(setRange)}
setRange(v ? v.map((d) => d.toDate()) : []);
setPage(1);
}}
style={{ maxWidth: 380 }} style={{ maxWidth: 380 }}
/> />
<Select <Select
@@ -208,17 +221,18 @@ const FundLedgerSheet = ({ visible, account, fetchLedger, onClose }) => {
maxTagCount={2} maxTagCount={2}
placeholder={t('全部类型')} placeholder={t('全部类型')}
value={types} value={types}
onChange={(v) => { onChange={changeFilter(setTypes)}
setTypes(v);
setPage(1);
}}
style={{ minWidth: 200 }} style={{ minWidth: 200 }}
options={FUND_ENTRY_TYPES.map((k) => ({ options={FUND_ENTRY_TYPES.map((k) => ({
value: k, value: k,
label: fundEntryLabel(t, k), label: fundEntryLabel(t, k),
}))} }))}
/> />
<Button icon={<RefreshCw size={16} />} onClick={load} loading={loading}> <Button
icon={<RefreshCw size={16} />}
onClick={submitSearch}
loading={loading}
>
{t('刷新')} {t('刷新')}
</Button> </Button>
</div> </div>
@@ -232,7 +246,7 @@ const FundLedgerSheet = ({ visible, account, fetchLedger, onClose }) => {
<Typography.Text type='danger' className='text-xs'> <Typography.Text type='danger' className='text-xs'>
{error} {error}
</Typography.Text> </Typography.Text>
<Button size='small' type='link' onClick={load}> <Button size='small' type='link' onClick={submitSearch}>
{t('重试')} {t('重试')}
</Button> </Button>
</div> </div>
@@ -245,6 +259,7 @@ const FundLedgerSheet = ({ visible, account, fetchLedger, onClose }) => {
size='middle' size='middle'
scroll={{ x: 'max-content' }} scroll={{ x: 'max-content' }}
pagination={{ pagination={{
preservePage: true,
currentPage: page, currentPage: page,
pageSize, pageSize,
onPageSizeChange: (size) => { onPageSizeChange: (size) => {
+1 -1
View File
@@ -105,7 +105,7 @@ const OrgDeptFunds = ({ orgId }) => {
const tree = useMemo(() => buildFundTree(rows), [rows]); const tree = useMemo(() => buildFundTree(rows), [rows]);
// 稳定引用:流水抽屉的加载回调依赖它,内联箭头函数会让抽屉每次渲染都重新请求 // 稳定引用:流水抽屉的加载回调依赖它,内联箭头函数会让抽屉每次渲染都重新请求
const fetchLedger = useCallback( const fetchLedger = useCallback(
(id, params) => orgFundApi.ledger(orgId, id, params), (id, params, signal) => orgFundApi.ledger(orgId, id, params, signal),
[orgId], [orgId],
); );
const unallocated = overview?.unallocated; const unallocated = overview?.unallocated;
+4 -4
View File
@@ -21,10 +21,10 @@ export const orgFundApi = {
allocate: (orgId, body) => allocate: (orgId, body) =>
API.post('/api/org/fund/allocate', body, opts(orgId)), API.post('/api/org/fund/allocate', body, opts(orgId)),
recall: (orgId, body) => API.post('/api/org/fund/recall', body, opts(orgId)), recall: (orgId, body) => API.post('/api/org/fund/recall', body, opts(orgId)),
ledger: (orgId, accountId, params) => ledger: (orgId, accountId, params, signal) =>
API.get( API.get(
`/api/org/fund/accounts/${accountId}/ledger`, `/api/org/fund/accounts/${accountId}/ledger`,
opts(orgId, { params }), opts(orgId, { params, signal }),
), ),
transfer: (orgId, opId) => transfer: (orgId, opId) =>
API.get(`/api/org/fund/transfers/${encodeURIComponent(opId)}`, opts(orgId)), API.get(`/api/org/fund/transfers/${encodeURIComponent(opId)}`, opts(orgId)),
@@ -48,10 +48,10 @@ export const deptFundApi = {
API.post('/api/org/dept-managed/fund/allocate', body, opts(orgId)), API.post('/api/org/dept-managed/fund/allocate', body, opts(orgId)),
recall: (orgId, body) => recall: (orgId, body) =>
API.post('/api/org/dept-managed/fund/recall', body, opts(orgId)), API.post('/api/org/dept-managed/fund/recall', body, opts(orgId)),
ledger: (orgId, accountId, params) => ledger: (orgId, accountId, params, signal) =>
API.get( API.get(
`/api/org/dept-managed/fund/accounts/${accountId}/ledger`, `/api/org/dept-managed/fund/accounts/${accountId}/ledger`,
opts(orgId, { params }), opts(orgId, { params, signal }),
), ),
transfer: (orgId, opId) => transfer: (orgId, opId) =>
API.get( API.get(
+54 -37
View File
@@ -1,6 +1,7 @@
import { Search as ActionSearch } from '@/components/common/icons/ActionIcons'; import { Search as ActionSearch } from '@/components/common/icons/ActionIcons';
import { useEffectEvent } from '../../hooks/common/useEffectEvent'; import { useFilterSearch } from '../../hooks/common/useFilterSearch';
import React, { useState, useEffect, useMemo } from 'react'; import { useTableFilterQuery } from '../../hooks/common/useTableFilterQuery';
import React, { useState, useCallback, useMemo } from 'react';
import { Button as AntButton, Empty as AntEmpty, Tag as AntTag } from 'antd'; import { Button as AntButton, Empty as AntEmpty, Tag as AntTag } from 'antd';
import { import {
Typography, Typography,
@@ -30,40 +31,54 @@ const HistoryPanel = ({ t, refreshTrigger }) => {
const [page, setPage] = useState(1); const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(10); const [pageSize, setPageSize] = useState(10);
const [keyword, setKeyword] = useState(''); const [keyword, setKeyword] = useState('');
const [appliedKeyword, setAppliedKeyword] = useState('');
const [queryVersion, setQueryVersion] = useState(0);
const userIsAdmin = useMemo(() => isAdmin(), []); const userIsAdmin = useMemo(() => isAdmin(), []);
// 加载充值记录 // 加载充值记录
const loadTopups = async (currentPage, currentPageSize) => { const query = useCallback(
setLoading(true); async (signal) => {
try { setLoading(true);
const base = userIsAdmin ? '/api/user/topup' : '/api/user/topup/self'; try {
const qs = const base = userIsAdmin ? '/api/user/topup' : '/api/user/topup/self';
`p=${currentPage}&page_size=${currentPageSize}` + const qs =
(keyword ? `&keyword=${encodeURIComponent(keyword)}` : ''); `p=${page}&page_size=${pageSize}` +
const endpoint = `${base}?${qs}`; (appliedKeyword
const res = await API.get(endpoint); ? `&keyword=${encodeURIComponent(appliedKeyword)}`
const { success, message, data } = res.data; : '');
if (success) { const endpoint = `${base}?${qs}`;
setTopups(data.items || []); const res = await API.get(endpoint, { signal });
setTotal(data.total || 0); if (signal?.aborted) return;
} else { const { success, message, data } = res.data;
Toast.error({ content: message || t('加载失败') }); if (success) {
setTopups(data.items || []);
setTotal(data.total || 0);
} else {
Toast.error({ content: message || t('加载失败') });
}
} catch (error) {
if (!signal?.aborted && !error.isAxiosError)
Toast.error({ content: t('加载账单失败') });
} finally {
if (!signal?.aborted) setLoading(false);
} }
} catch (error) { },
console.error('Load topups error:', error); [appliedKeyword, page, pageSize, t, userIsAdmin],
Toast.error({ content: t('加载账单失败') }); );
} finally {
setLoading(false);
}
};
const onScopeChange = useEffectEvent(() => { const version = useMemo(
loadTopups(page, pageSize); () => ({ queryVersion, refreshTrigger }),
}); [queryVersion, refreshTrigger],
useEffect( );
() => onScopeChange(), const { cancelQuery, reloadQuery } = useTableFilterQuery(query, version);
[onScopeChange, page, pageSize, keyword, refreshTrigger], const reload = () => setQueryVersion((key) => key + 1);
const { changeFilter, submitSearch, cancelPendingSearch } = useFilterSearch(
() => {
setAppliedKeyword(keyword);
reload();
},
cancelQuery,
); );
// 管理员补单 // 管理员补单
@@ -75,7 +90,7 @@ const HistoryPanel = ({ t, refreshTrigger }) => {
const { success, message } = res.data; const { success, message } = res.data;
if (success) { if (success) {
Toast.success({ content: t('补单成功') }); Toast.success({ content: t('补单成功') });
await loadTopups(page, pageSize); await reloadQuery();
} else { } else {
Toast.error({ content: message || t('补单失败') }); Toast.error({ content: message || t('补单失败') });
} }
@@ -185,17 +200,18 @@ const HistoryPanel = ({ t, refreshTrigger }) => {
<Input <Input
placeholder={t('请输入订单号')} placeholder={t('请输入订单号')}
value={keyword} value={keyword}
onChange={(value) => { onChange={changeFilter(setKeyword)}
setKeyword(value); onEnterPress={submitSearch}
setPage(1);
}}
showClear showClear
/> />
{/* 重置等同清空订单号;搜索按当前订单号重新加载当前页 */} {/* 重置等同清空订单号;搜索按当前订单号重新加载当前页 */}
<Button <Button
onClick={() => { onClick={() => {
cancelPendingSearch();
setKeyword(''); setKeyword('');
setAppliedKeyword('');
setPage(1); setPage(1);
reload();
}} }}
> >
{t('重置')} {t('重置')}
@@ -203,7 +219,7 @@ const HistoryPanel = ({ t, refreshTrigger }) => {
<Button <Button
type='primary' type='primary'
icon={<ActionSearch size={14} />} icon={<ActionSearch size={14} />}
onClick={() => loadTopups(page, pageSize)} onClick={submitSearch}
> >
{t('搜索')} {t('搜索')}
</Button> </Button>
@@ -226,9 +242,10 @@ const HistoryPanel = ({ t, refreshTrigger }) => {
} }
/> />
{total > 0 && ( {(total > 0 || page > 1) && (
<div className='rc-history-pagination'> <div className='rc-history-pagination'>
<Pagination <Pagination
preservePage
total={total} total={total}
currentPage={page} currentPage={page}
pageSize={pageSize} pageSize={pageSize}
+15 -9
View File
@@ -1,6 +1,8 @@
import { useLocalTableFilters } from '@/hooks/common/useLocalTableFilters';
import { useFilteredTableRows } from '@/hooks/common/useFilteredTableRows';
import TableActionPopconfirm from '@/components/common/table/TableActionPopconfirm'; import TableActionPopconfirm from '@/components/common/table/TableActionPopconfirm';
import { useEffectEvent } from '../../../hooks/common/useEffectEvent'; import { useEffectEvent } from '../../../hooks/common/useEffectEvent';
import React, { useEffect, useState, useRef } from 'react'; import React, { useCallback, useEffect, useState, useRef } from 'react';
import { Button as AntButton } from 'antd'; import { Button as AntButton } from 'antd';
import './settings-chats.css'; import './settings-chats.css';
import { import {
@@ -40,7 +42,10 @@ export default function SettingsChats(props) {
const [modalVisible, setModalVisible] = useState(false); const [modalVisible, setModalVisible] = useState(false);
const [editingConfig, setEditingConfig] = useState(null); const [editingConfig, setEditingConfig] = useState(null);
const [isEdit, setIsEdit] = useState(false); const [isEdit, setIsEdit] = useState(false);
const [searchText, setSearchText] = useState(''); const { draft, applied, changeFilters, submitSearch } = useLocalTableFilters({
searchText: '',
});
const keyword = applied.searchText.toLowerCase();
const modalFormRef = useRef(); const modalFormRef = useRef();
const jsonToConfigs = (jsonString) => { const jsonToConfigs = (jsonString) => {
@@ -244,11 +249,11 @@ export default function SettingsChats(props) {
setEditingConfig(null); setEditingConfig(null);
}; };
const filteredConfigs = chatConfigs.filter( const matches = useCallback(
(config) => (config) => !keyword || config.name.toLowerCase().includes(keyword),
!searchText || [keyword],
config.name.toLowerCase().includes(searchText.toLowerCase()),
); );
const filteredConfigs = useFilteredTableRows(chatConfigs, matches);
const highlightKeywords = (text) => { const highlightKeywords = (text) => {
if (!text) return text; if (!text) return text;
@@ -350,8 +355,9 @@ export default function SettingsChats(props) {
<Input <Input
prefix={<IconSearch />} prefix={<IconSearch />}
placeholder={t('搜索聊天应用名称')} placeholder={t('搜索聊天应用名称')}
value={searchText} value={draft.searchText}
onChange={(value) => setSearchText(value)} onChange={(searchText) => changeFilters({ searchText })}
onEnterPress={submitSearch}
className='settings-chats-search' className='settings-chats-search'
showClear showClear
/> />
@@ -378,7 +384,7 @@ export default function SettingsChats(props) {
columns={columns} columns={columns}
dataSource={filteredConfigs} dataSource={filteredConfigs}
rowKey='id' rowKey='id'
pagination={{ pageSize: 10 }} pagination={{ pageSize: 10, preservePage: true }}
/> />
</div> </div>
) : ( ) : (
+33 -43
View File
@@ -1,3 +1,5 @@
import { useLocalTableFilters } from '@/hooks/common/useLocalTableFilters';
import { useFilteredTableRows } from '@/hooks/common/useFilteredTableRows';
import { confirmTableAction } from '@/components/common/table/confirmTableAction'; import { confirmTableAction } from '@/components/common/table/confirmTableAction';
import { formatIdReference } from '../../../helpers/safeDisplay'; import { formatIdReference } from '../../../helpers/safeDisplay';
@@ -170,8 +172,11 @@ export default function ModelCostSettings() {
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
const [effectiveFrom, setEffectiveFrom] = useState(null); // null = 立即生效 const [effectiveFrom, setEffectiveFrom] = useState(null); // null = 立即生效
const [search, setSearch] = useState(''); const { draft, applied, changeFilters, submitSearch } = useLocalTableFilters({
const [fillFilter, setFillFilter] = useState('all'); search: '',
fillFilter: 'all',
});
const { search, fillFilter } = applied;
const [snapshotTick, setSnapshotTick] = useState(0); const [snapshotTick, setSnapshotTick] = useState(0);
const [selectedRowKeys, setSelectedRowKeys] = useState([]); const [selectedRowKeys, setSelectedRowKeys] = useState([]);
const [currentPage, setCurrentPage] = useState(1); const [currentPage, setCurrentPage] = useState(1);
@@ -501,47 +506,31 @@ export default function ModelCostSettings() {
const orphanRows = useMemo(() => rows.filter((r) => r.orphan), [rows]); const orphanRows = useMemo(() => rows.filter((r) => r.orphan), [rows]);
const filteredRows = useMemo(() => { const keyword = search.trim().toLowerCase();
let result = rows; const matches = useCallback(
const kw = search.trim().toLowerCase(); (r) => {
if (kw) { const matchesKeyword =
result = result.filter( !keyword ||
(r) => r.model_name.toLowerCase().includes(keyword) ||
r.model_name.toLowerCase().includes(kw) || (r.platform_names || []).some((p) => p.toLowerCase().includes(keyword));
(r.platform_names || []).some((p) => p.toLowerCase().includes(kw)), const expected =
);
}
if (fillFilter !== 'all') {
const want =
fillFilter === 'filled' fillFilter === 'filled'
? FILL_FILLED ? FILL_FILLED
: fillFilter === 'partial' : fillFilter === 'partial'
? FILL_PARTIAL ? FILL_PARTIAL
: FILL_EMPTY; : FILL_EMPTY;
result = result.filter((r) => snapshot[r.model_name] === want); return (
} matchesKeyword &&
return result; (fillFilter === 'all' || snapshot[r.model_name] === expected)
}, [rows, search, fillFilter, snapshot]); );
},
[keyword, fillFilter, snapshot],
);
const filteredRows = useFilteredTableRows(rows, matches);
useEffect(() => { useEffect(() => {
setCurrentPage(1); setCurrentPage(1);
}, [search, fillFilter, channelId]); }, [channelId]);
// 数据缩减后钳制当前页,避免停留在越界空页
useEffect(() => {
const maxPage = Math.max(1, Math.ceil(filteredRows.length / pageSize));
if (currentPage > maxPage) setCurrentPage(maxPage);
}, [filteredRows.length, pageSize, currentPage]);
// 选中集始终收敛到可见行:筛选把已选行藏起来后,批量操作不得误伤看不见的行
useEffect(() => {
setSelectedRowKeys((prev) => {
const next = prev.filter((n) =>
filteredRows.some((r) => r.model_name === n),
);
return next.length === prev.length ? prev : next;
});
}, [filteredRows]);
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
// 编辑 // 编辑
@@ -801,9 +790,9 @@ export default function ModelCostSettings() {
const discountTargets = useMemo( const discountTargets = useMemo(
() => () =>
discountTarget === 'selected' discountTarget === 'selected'
? rows.filter((r) => selectedRowKeys.includes(r.model_name)) ? filteredRows.filter((r) => selectedRowKeys.includes(r.model_name))
: filteredRows, : filteredRows,
[discountTarget, rows, selectedRowKeys, filteredRows], [discountTarget, selectedRowKeys, filteredRows],
); );
// 缺官方牌价的模型算不出折扣价,必须在弹窗里先说清楚会漏掉多少 // 缺官方牌价的模型算不出折扣价,必须在弹窗里先说清楚会漏掉多少
@@ -1545,17 +1534,18 @@ export default function ModelCostSettings() {
<Input <Input
prefix={<IconSearch />} prefix={<IconSearch />}
placeholder={t('搜索模型名')} placeholder={t('搜索模型名')}
value={search} value={draft.search}
onChange={setSearch} onChange={(search) => changeFilters({ search })}
onEnterPress={submitSearch}
showClear showClear
style={{ width: 200 }} style={{ width: 200 }}
/> />
<RadioGroup <RadioGroup
type='button' type='button'
buttonSize='default' buttonSize='default'
value={fillFilter} value={draft.fillFilter}
onChange={(e) => { onChange={(e) => {
setFillFilter(e.target.value); changeFilters({ fillFilter: e.target.value });
setSnapshotTick((v) => v + 1); setSnapshotTick((v) => v + 1);
}} }}
> >
@@ -1688,6 +1678,7 @@ export default function ModelCostSettings() {
onChange: (keys) => setSelectedRowKeys(keys || []), onChange: (keys) => setSelectedRowKeys(keys || []),
}} }}
pagination={{ pagination={{
preservePage: true,
currentPage, currentPage,
pageSize, pageSize,
showSizeChanger: true, showSizeChanger: true,
@@ -2003,8 +1994,7 @@ export default function ModelCostSettings() {
onClick={() => { onClick={() => {
setUncoveredVisible(false); setUncoveredVisible(false);
switchChannel(String(r.channel_id)); switchChannel(String(r.channel_id));
setSearch(r.model_name); changeFilters({ search: r.model_name, fillFilter: 'all' });
setFillFilter('all');
setSnapshotTick((v) => v + 1); setSnapshotTick((v) => v + 1);
}} }}
type='link' type='link'
@@ -1,3 +1,5 @@
import { useLocalTableFilters } from '@/hooks/common/useLocalTableFilters';
import { useFilteredTableRows } from '@/hooks/common/useFilteredTableRows';
import { I18N_TECHNICAL_TEXT } from '../../../i18n/technicalText.js'; import { I18N_TECHNICAL_TEXT } from '../../../i18n/technicalText.js';
import React, { import React, {
useCallback, useCallback,
@@ -126,8 +128,11 @@ export default function ModelOfficialPriceSettings(props) {
const [conflict, setConflict] = useState(false); const [conflict, setConflict] = useState(false);
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
const [search, setSearch] = useState(''); const { draft, applied, changeFilters, submitSearch } = useLocalTableFilters({
const [fillFilter, setFillFilter] = useState('all'); // all | filled | partial | unfilled search: '',
fillFilter: 'all',
});
const { search, fillFilter } = applied;
const [snapshotTick, setSnapshotTick] = useState(0); const [snapshotTick, setSnapshotTick] = useState(0);
const [currentPage, setCurrentPage] = useState(1); const [currentPage, setCurrentPage] = useState(1);
const [pageSize, setPageSize] = useState(10); const [pageSize, setPageSize] = useState(10);
@@ -319,31 +324,27 @@ export default function ModelOfficialPriceSettings(props) {
.length; .length;
}, [models, snapshot, liveStateOf, fillFilter]); }, [models, snapshot, liveStateOf, fillFilter]);
const filteredModels = useMemo(() => { const keyword = search.trim().toLowerCase();
let result = models; const matches = useCallback(
const kw = search.trim().toLowerCase(); (r) => {
if (kw) { const matchesKeyword =
result = result.filter((m) => { !keyword ||
const vendor = (vendorMap[m.vendor_id] || '').toLowerCase(); r.model_name.toLowerCase().includes(keyword) ||
return m.model_name.toLowerCase().includes(kw) || vendor.includes(kw); (vendorMap[r.vendor_id] || '').toLowerCase().includes(keyword);
}); const expected =
}
if (fillFilter !== 'all') {
const want =
fillFilter === 'filled' fillFilter === 'filled'
? OFFICIAL_FILL_FILLED ? OFFICIAL_FILL_FILLED
: fillFilter === 'partial' : fillFilter === 'partial'
? OFFICIAL_FILL_PARTIAL ? OFFICIAL_FILL_PARTIAL
: OFFICIAL_FILL_EMPTY; : OFFICIAL_FILL_EMPTY;
result = result.filter((m) => snapshot[m.model_name] === want); return (
} matchesKeyword &&
return result; (fillFilter === 'all' || snapshot[r.model_name] === expected)
}, [models, search, fillFilter, snapshot, vendorMap]); );
},
// 搜索/筛选变化后回到第一页,避免停留在越界空页 [keyword, fillFilter, snapshot, vendorMap],
useEffect(() => { );
setCurrentPage(1); const filteredModels = useFilteredTableRows(models, matches);
}, [search, fillFilter]);
// 列表里没有对应行的官方价条目:看不见、删不掉,但每次保存都会被原样写回。 // 列表里没有对应行的官方价条目:看不见、删不掉,但每次保存都会被原样写回。
// 注意 /api/pricing 只返回「当前有启用渠道」的模型,渠道被临时禁用(含自动禁用) // 注意 /api/pricing 只返回「当前有启用渠道」的模型,渠道被临时禁用(含自动禁用)
@@ -1114,16 +1115,17 @@ export default function ModelOfficialPriceSettings(props) {
<Input <Input
prefix={<IconSearch />} prefix={<IconSearch />}
placeholder={t('搜索模型名称或厂商')} placeholder={t('搜索模型名称或厂商')}
value={search} value={draft.search}
onChange={(v) => setSearch(v)} onChange={(search) => changeFilters({ search })}
onEnterPress={submitSearch}
showClear showClear
style={{ width: 220 }} style={{ width: 220 }}
/> />
<RadioGroup <RadioGroup
type='button' type='button'
value={fillFilter} value={draft.fillFilter}
onChange={(e) => { onChange={(e) => {
setFillFilter(e.target.value); changeFilters({ fillFilter: e.target.value });
setSnapshotTick((v) => v + 1); setSnapshotTick((v) => v + 1);
}} }}
> >
@@ -1200,6 +1202,7 @@ export default function ModelOfficialPriceSettings(props) {
loading={modelsLoading} loading={modelsLoading}
size='small' size='small'
pagination={{ pagination={{
preservePage: true,
currentPage, currentPage,
pageSize, pageSize,
showSizeChanger: true, showSizeChanger: true,
@@ -1,5 +1,7 @@
import { useLocalTableFilters } from '@/hooks/common/useLocalTableFilters';
import { useFilteredTableRows } from '@/hooks/common/useFilteredTableRows';
import { useEffectEvent } from '../../../hooks/common/useEffectEvent'; import { useEffectEvent } from '../../../hooks/common/useEffectEvent';
import React, { useEffect, useState } from 'react'; import React, { useCallback, useEffect, useState } from 'react';
import { import {
Table, Table,
Button, Button,
@@ -26,7 +28,10 @@ export default function ModelRatioNotSetEditor(props) {
const [visible, setVisible] = useState(false); const [visible, setVisible] = useState(false);
const [batchVisible, setBatchVisible] = useState(false); const [batchVisible, setBatchVisible] = useState(false);
const [currentModel, setCurrentModel] = useState(null); const [currentModel, setCurrentModel] = useState(null);
const [searchText, setSearchText] = useState(''); const { draft, applied, changeFilters, submitSearch } = useLocalTableFilters({
searchText: '',
});
const { searchText } = applied;
const [currentPage, setCurrentPage] = useState(1); const [currentPage, setCurrentPage] = useState(1);
const [pageSize, setPageSize] = useState(10); const [pageSize, setPageSize] = useState(10);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@@ -115,9 +120,11 @@ export default function ModelRatioNotSetEditor(props) {
}; };
// 在 return 语句之前,先处理过滤和分页逻辑 // 在 return 语句之前,先处理过滤和分页逻辑
const filteredModels = models.filter((model) => const matches = useCallback(
searchText ? model.name.includes(searchText) : true, (model) => !searchText || model.name.includes(searchText),
[searchText],
); );
const filteredModels = useFilteredTableRows(models, matches);
// 然后基于过滤后的数据计算分页数据 // 然后基于过滤后的数据计算分页数据
const pagedData = getPagedData(filteredModels, currentPage, pageSize); const pagedData = getPagedData(filteredModels, currentPage, pageSize);
@@ -398,11 +405,9 @@ export default function ModelRatioNotSetEditor(props) {
<Input <Input
prefix={<IconSearch />} prefix={<IconSearch />}
placeholder={t('搜索模型名称')} placeholder={t('搜索模型名称')}
value={searchText} value={draft.searchText}
onChange={(value) => { onChange={(searchText) => changeFilters({ searchText })}
setSearchText(value); onEnterPress={submitSearch}
setCurrentPage(1);
}}
style={{ width: 200 }} style={{ width: 200 }}
/> />
</Space> </Space>
@@ -417,6 +422,7 @@ export default function ModelRatioNotSetEditor(props) {
rowSelection={rowSelection} rowSelection={rowSelection}
rowKey='name' rowKey='name'
pagination={{ pagination={{
preservePage: true,
currentPage: currentPage, currentPage: currentPage,
pageSize: pageSize, pageSize: pageSize,
total: filteredModels.length, total: filteredModels.length,
@@ -1,5 +1,7 @@
import { useLocalTableFilters } from '@/hooks/common/useLocalTableFilters';
import { useFilteredTableRows } from '@/hooks/common/useFilteredTableRows';
import TableActionPopconfirm from '@/components/common/table/TableActionPopconfirm'; import TableActionPopconfirm from '@/components/common/table/TableActionPopconfirm';
import React, { useEffect, useState, useRef } from 'react'; import React, { useCallback, useEffect, useState, useRef } from 'react';
import { import {
Table, Table,
Button, Button,
@@ -22,12 +24,15 @@ export default function ModelSettingsVisualEditor(props) {
const [visible, setVisible] = useState(false); const [visible, setVisible] = useState(false);
const [isEditMode, setIsEditMode] = useState(false); const [isEditMode, setIsEditMode] = useState(false);
const [currentModel, setCurrentModel] = useState(null); const [currentModel, setCurrentModel] = useState(null);
const [searchText, setSearchText] = useState(''); const { draft, applied, changeFilters, submitSearch } = useLocalTableFilters({
searchText: '',
conflictOnly: false,
});
const { searchText, conflictOnly } = applied;
const [currentPage, setCurrentPage] = useState(1); const [currentPage, setCurrentPage] = useState(1);
const [, setLoading] = useState(false); const [, setLoading] = useState(false);
const [pricingMode, setPricingMode] = useState('per-token'); // 'per-token' or 'per-request' const [pricingMode, setPricingMode] = useState('per-token'); // 'per-token' or 'per-request'
const [pricingSubMode, setPricingSubMode] = useState('ratio'); // 'ratio' or 'token-price' const [pricingSubMode, setPricingSubMode] = useState('ratio'); // 'ratio' or 'token-price'
const [conflictOnly, setConflictOnly] = useState(false);
const formRef = useRef(null); const formRef = useRef(null);
const [pageSize, setPageSize] = useState(10); const [pageSize, setPageSize] = useState(10);
const _quotaPerUnit = getQuotaPerUnit(); const _quotaPerUnit = getQuotaPerUnit();
@@ -74,11 +79,15 @@ export default function ModelSettingsVisualEditor(props) {
}; };
// 在 return 语句之前,先处理过滤和分页逻辑 // 在 return 语句之前,先处理过滤和分页逻辑
const filteredModels = models.filter((model) => { const matches = useCallback(
const keywordMatch = searchText ? model.name.includes(searchText) : true; (model) => {
const conflictMatch = conflictOnly ? model.hasConflict : true; const keywordMatch = searchText ? model.name.includes(searchText) : true;
return keywordMatch && conflictMatch; const conflictMatch = conflictOnly ? model.hasConflict : true;
}); return keywordMatch && conflictMatch;
},
[searchText, conflictOnly],
);
const filteredModels = useFilteredTableRows(models, matches);
// 然后基于过滤后的数据计算分页数据 // 然后基于过滤后的数据计算分页数据
const pagedData = getPagedData(filteredModels, currentPage, pageSize); const pagedData = getPagedData(filteredModels, currentPage, pageSize);
@@ -449,20 +458,15 @@ export default function ModelSettingsVisualEditor(props) {
<Input <Input
prefix={<IconSearch />} prefix={<IconSearch />}
placeholder={t('搜索模型名称')} placeholder={t('搜索模型名称')}
value={searchText} value={draft.searchText}
onChange={(value) => { onChange={(searchText) => changeFilters({ searchText })}
setSearchText(value); onEnterPress={submitSearch}
setCurrentPage(1);
}}
style={{ width: 200 }} style={{ width: 200 }}
showClear showClear
/> />
<Checkbox <Checkbox
checked={conflictOnly} checked={draft.conflictOnly}
onChange={(e) => { onChange={(e) => changeFilters({ conflictOnly: e.target.checked })}
setConflictOnly(e.target.checked);
setCurrentPage(1);
}}
> >
{t('仅显示矛盾倍率')} {t('仅显示矛盾倍率')}
</Checkbox> </Checkbox>
@@ -472,6 +476,7 @@ export default function ModelSettingsVisualEditor(props) {
columns={columns} columns={columns}
dataSource={pagedData} dataSource={pagedData}
pagination={{ pagination={{
preservePage: true,
currentPage: currentPage, currentPage: currentPage,
pageSize: pageSize, pageSize: pageSize,
total: filteredModels.length, total: filteredModels.length,
+24 -30
View File
@@ -1,8 +1,10 @@
import { useLocalTableFilters } from '@/hooks/common/useLocalTableFilters';
import { useFilteredTableRows } from '@/hooks/common/useFilteredTableRows';
import { import {
RefreshCcw as ActionRefreshCcw, RefreshCcw as ActionRefreshCcw,
CheckSquare as ActionCheckSquare, CheckSquare as ActionCheckSquare,
} from '@/components/common/icons/ActionIcons'; } from '@/components/common/icons/ActionIcons';
import React, { useState, useCallback, useMemo, useEffect } from 'react'; import React, { useState, useCallback, useMemo } from 'react';
import { import {
Button, Button,
Table, Table,
@@ -87,10 +89,10 @@ export default function UpstreamRatioSync(props) {
const [pageSize, setPageSize] = useState(10); const [pageSize, setPageSize] = useState(10);
// 搜索相关状态 // 搜索相关状态
const [searchKeyword, setSearchKeyword] = useState(''); const { draft, applied, changeFilters, submitSearch } = useLocalTableFilters({
searchKeyword: '',
// 倍率类型过滤 ratioTypeFilter: '',
const [ratioTypeFilter, setRatioTypeFilter] = useState(''); });
// 冲突确认弹窗相关 // 冲突确认弹窗相关
const [confirmVisible, setConfirmVisible] = useState(false); const [confirmVisible, setConfirmVisible] = useState(false);
@@ -98,10 +100,6 @@ export default function UpstreamRatioSync(props) {
const channelSelectorRef = React.useRef(null); const channelSelectorRef = React.useRef(null);
useEffect(() => {
setCurrentPage(1);
}, [ratioTypeFilter, searchKeyword]);
const fetchAllChannels = async () => { const fetchAllChannels = async () => {
setLoading(true); setLoading(true);
try { try {
@@ -432,19 +430,21 @@ export default function UpstreamRatioSync(props) {
<Input <Input
prefix={<IconSearch size={14} />} prefix={<IconSearch size={14} />}
placeholder={t('搜索模型名称')} placeholder={t('搜索模型名称')}
value={searchKeyword} value={draft.searchKeyword}
onChange={setSearchKeyword} onChange={(searchKeyword) => changeFilters({ searchKeyword })}
onEnterPress={submitSearch}
className='w-full sm:w-64' className='w-full sm:w-64'
showClear showClear
/> />
<Select <Select
placeholder={t('按倍率类型筛选')} placeholder={t('按倍率类型筛选')}
value={ratioTypeFilter} value={draft.ratioTypeFilter}
onChange={setRatioTypeFilter} onChange={(value) =>
changeFilters({ ratioTypeFilter: value ?? '' })
}
className='w-full sm:w-48' className='w-full sm:w-48'
showClear showClear
onClear={() => setRatioTypeFilter('')}
> >
<Select.Option value='model_ratio'>{t('模型倍率')}</Select.Option> <Select.Option value='model_ratio'>{t('模型倍率')}</Select.Option>
<Select.Option value='completion_ratio'> <Select.Option value='completion_ratio'>
@@ -489,22 +489,15 @@ export default function UpstreamRatioSync(props) {
return tmp; return tmp;
}, [differences]); }, [differences]);
const filteredDataSource = useMemo(() => { const keyword = applied.searchKeyword.toLowerCase().trim();
if (!searchKeyword.trim() && !ratioTypeFilter) { const { ratioTypeFilter } = applied;
return dataSource; const matches = useCallback(
} (item) =>
(!keyword || item.model.toLowerCase().includes(keyword)) &&
return dataSource.filter((item) => { (!ratioTypeFilter || item.ratioType === ratioTypeFilter),
const matchesKeyword = [keyword, ratioTypeFilter],
!searchKeyword.trim() || );
item.model.toLowerCase().includes(searchKeyword.toLowerCase().trim()); const filteredDataSource = useFilteredTableRows(dataSource, matches);
const matchesRatioType =
!ratioTypeFilter || item.ratioType === ratioTypeFilter;
return matchesKeyword && matchesRatioType;
});
}, [dataSource, searchKeyword, ratioTypeFilter]);
const upstreamNames = useMemo(() => { const upstreamNames = useMemo(() => {
const set = new Set(); const set = new Set();
@@ -754,6 +747,7 @@ export default function UpstreamRatioSync(props) {
pagination={{ pagination={{
currentPage: currentPage, currentPage: currentPage,
pageSize: pageSize, pageSize: pageSize,
preservePage: true,
total: filteredDataSource.length, total: filteredDataSource.length,
showSizeChanger: true, showSizeChanger: true,
showQuickJumper: true, showQuickJumper: true,
+101 -88
View File
@@ -22,6 +22,8 @@ import { useIsMobile } from '../../hooks/common/useIsMobile';
import { createCardProPagination } from '../../helpers/utils'; import { createCardProPagination } from '../../helpers/utils';
import { Button as AntButton } from 'antd'; import { Button as AntButton } from 'antd';
import React, { useCallback, useEffect, useMemo, useState } from 'react'; import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { useFilterSearch } from '../../hooks/common/useFilterSearch';
import { useTableFilterQuery } from '../../hooks/common/useTableFilterQuery';
import { useEffectEvent } from '../../hooks/common/useEffectEvent'; import { useEffectEvent } from '../../hooks/common/useEffectEvent';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { formatCurrency } from '../../helpers/safeDisplay'; import { formatCurrency } from '../../helpers/safeDisplay';
@@ -133,6 +135,12 @@ const Subscription = () => {
const [tiers, setTiers] = useState([]); const [tiers, setTiers] = useState([]);
const [statuses, setStatuses] = useState([]); const [statuses, setStatuses] = useState([]);
const [endDateRange, setEndDateRange] = useState(null); const [endDateRange, setEndDateRange] = useState(null);
const [appliedFilters, setAppliedFilters] = useState({
planTypes: [],
tiers: [],
statuses: [],
endDateRange: null,
});
const [quickFilter, setQuickFilter] = useState(null); // expiring3 / expiring7 / overdue const [quickFilter, setQuickFilter] = useState(null); // expiring3 / expiring7 / overdue
// 操作弹窗 // 操作弹窗
@@ -167,75 +175,85 @@ const Subscription = () => {
} }
}, [t]); }, [t]);
const fetchList = useCallback(async () => { const fetchList = useCallback(
setLoading(true); async (signal) => {
try { const { planTypes, tiers, statuses, endDateRange } = appliedFilters;
const params = { page, page_size: pageSize }; setLoading(true);
if (appliedKeyword) params.keyword = appliedKeyword; try {
if (appliedUserId) params.user_id = appliedUserId; const params = { page, page_size: pageSize };
if (planTypes.length) params.plan_types = planTypes.join(','); if (appliedKeyword) params.keyword = appliedKeyword;
if (tiers.length) params.tiers = tiers.join(','); if (appliedUserId) params.user_id = appliedUserId;
if (statuses.length) params.statuses = statuses.join(','); if (planTypes.length) params.plan_types = planTypes.join(',');
if (endDateRange && endDateRange[0]) { if (tiers.length) params.tiers = tiers.join(',');
params.end_date_from = Math.floor(endDateRange[0].getTime() / 1000); if (statuses.length) params.statuses = statuses.join(',');
} if (endDateRange && endDateRange[0]) {
if (endDateRange && endDateRange[1]) { params.end_date_from = Math.floor(endDateRange[0].getTime() / 1000);
params.end_date_to = Math.floor(endDateRange[1].getTime() / 1000); }
} if (endDateRange && endDateRange[1]) {
// 快捷筛选 (优先级覆盖 endDateRange) params.end_date_to = Math.floor(endDateRange[1].getTime() / 1000);
const now = Math.floor(Date.now() / 1000); }
if (quickFilter === 'expiring3') { // 快捷筛选 (优先级覆盖 endDateRange)
params.end_date_from = now; const now = Math.floor(Date.now() / 1000);
params.end_date_to = now + 3 * 86400; if (quickFilter === 'expiring3') {
params.statuses = 'active'; params.end_date_from = now;
} else if (quickFilter === 'expiring7') { params.end_date_to = now + 3 * 86400;
params.end_date_from = now; params.statuses = 'active';
params.end_date_to = now + 7 * 86400; } else if (quickFilter === 'expiring7') {
params.statuses = 'active'; params.end_date_from = now;
} else if (quickFilter === 'overdue') { params.end_date_to = now + 7 * 86400;
params.end_date_to = now; params.statuses = 'active';
params.statuses = 'expired'; } else if (quickFilter === 'overdue') {
} params.end_date_to = now;
params.statuses = 'expired';
}
const res = await API.get('/api/user/membership/manage/subscriptions', { const res = await API.get('/api/user/membership/manage/subscriptions', {
params, params,
}); signal,
if (res.data.success) { });
setList(res.data.data?.list || []); if (signal?.aborted) return;
setTotal(res.data.data?.total || 0); if (res.data.success) {
} else { setList(res.data.data?.list || []);
showError(res.data.message || t('查询失败')); setTotal(res.data.data?.total || 0);
} else {
showError(res.data.message || t('查询失败'));
}
} catch (err) {
if (!signal?.aborted && !err.isAxiosError) showError(err.message);
} finally {
if (!signal?.aborted) setLoading(false);
} }
} catch (err) { },
showError(err.message); [
} finally { page,
setLoading(false); pageSize,
} appliedKeyword,
}, [ appliedUserId,
page, appliedFilters,
pageSize, quickFilter,
appliedKeyword, t,
appliedUserId, ],
planTypes, );
tiers,
statuses,
endDateRange,
quickFilter,
t,
]);
useEffect(() => { const { cancelQuery } = useTableFilterQuery(fetchList, refreshToken);
fetchList();
}, [fetchList, refreshToken]);
const handleSearch = () => { const { changeFilter, submitSearch, cancelPendingSearch } = useFilterSearch(
setPage(1); () => {
setAppliedKeyword(keyword); setAppliedKeyword(keyword);
setAppliedUserId(userId); setAppliedUserId(userId);
setQuickFilter(null); setAppliedFilters({ planTypes, tiers, statuses, endDateRange });
}; },
cancelQuery,
);
const handleReset = () => { const handleReset = () => {
cancelPendingSearch();
setAppliedFilters({
planTypes: [],
tiers: [],
statuses: [],
endDateRange: null,
});
setPage(1); setPage(1);
setKeyword(''); setKeyword('');
setAppliedKeyword(''); setAppliedKeyword('');
@@ -249,7 +267,6 @@ const Subscription = () => {
}; };
const applyQuickFilter = (key) => { const applyQuickFilter = (key) => {
setPage(1);
setQuickFilter((prev) => (prev === key ? null : key)); setQuickFilter((prev) => (prev === key ? null : key));
}; };
@@ -309,6 +326,12 @@ const Subscription = () => {
setTiers([]); setTiers([]);
setStatuses([]); setStatuses([]);
setEndDateRange(null); setEndDateRange(null);
setAppliedFilters({
planTypes: [],
tiers: [],
statuses: [],
endDateRange: null,
});
setQuickFilter(null); setQuickFilter(null);
setPage(1); setPage(1);
} }
@@ -325,7 +348,7 @@ const Subscription = () => {
); );
if (res.data.success) { if (res.data.success) {
showSuccess(t('补发成功')); showSuccess(t('补发成功'));
fetchList(); setRefreshToken((key) => key + 1);
} else { } else {
showError(res.data.message); showError(res.data.message);
} }
@@ -488,7 +511,7 @@ const Subscription = () => {
searchArea={ searchArea={
<ConsoleFilterGrid <ConsoleFilterGrid
onReset={handleReset} onReset={handleReset}
onSearch={handleSearch} onSearch={submitSearch}
loading={loading} loading={loading}
> >
<ConsoleFilterField <ConsoleFilterField
@@ -500,7 +523,7 @@ const Subscription = () => {
prefix={<Search size={14} />} prefix={<Search size={14} />}
placeholder={t('搜索用户名/昵称/订单号')} placeholder={t('搜索用户名/昵称/订单号')}
value={keyword} value={keyword}
onChange={setKeyword} onChange={changeFilter(setKeyword)}
/> />
</ConsoleFilterField> </ConsoleFilterField>
<ConsoleFilterField label={t('用户ID')} id='subscription-user-id'> <ConsoleFilterField label={t('用户ID')} id='subscription-user-id'>
@@ -508,7 +531,7 @@ const Subscription = () => {
id='subscription-user-id' id='subscription-user-id'
placeholder={t('用户ID')} placeholder={t('用户ID')}
value={userId} value={userId}
onChange={setUserId} onChange={changeFilter(setUserId)}
min={0} min={0}
hideButtons hideButtons
/> />
@@ -521,10 +544,7 @@ const Subscription = () => {
id='subscription-plan-type' id='subscription-plan-type'
placeholder={t('套餐类型')} placeholder={t('套餐类型')}
value={planTypes} value={planTypes}
onChange={(v) => { onChange={changeFilter((value) => setPlanTypes(value || []))}
setPage(1);
setPlanTypes(v || []);
}}
multiple multiple
maxTagCount={2} maxTagCount={2}
optionList={[ optionList={[
@@ -539,10 +559,7 @@ const Subscription = () => {
id='subscription-tier' id='subscription-tier'
placeholder={t('档位')} placeholder={t('档位')}
value={tiers} value={tiers}
onChange={(v) => { onChange={changeFilter((value) => setTiers(value || []))}
setPage(1);
setTiers(v || []);
}}
multiple multiple
maxTagCount={2} maxTagCount={2}
optionList={[ optionList={[
@@ -556,10 +573,7 @@ const Subscription = () => {
id='subscription-status' id='subscription-status'
placeholder={t('状态')} placeholder={t('状态')}
value={statuses} value={statuses}
onChange={(v) => { onChange={changeFilter((value) => setStatuses(value || []))}
setPage(1);
setStatuses(v || []);
}}
multiple multiple
maxTagCount={2} maxTagCount={2}
optionList={[ optionList={[
@@ -579,12 +593,10 @@ const Subscription = () => {
start: 'subscription-end-date', start: 'subscription-end-date',
end: 'subscription-end-date-end', end: 'subscription-end-date-end',
}} }}
tableFilter
type='dateRange' type='dateRange'
value={endDateRange} value={endDateRange}
onChange={(d) => { onChange={changeFilter(setEndDateRange)}
setPage(1);
setEndDateRange(d || null);
}}
placeholder={[t('到期开始'), t('到期结束')]} placeholder={[t('到期开始'), t('到期结束')]}
density='compact' density='compact'
/> />
@@ -633,6 +645,7 @@ const Subscription = () => {
</div> </div>
} }
paginationArea={createCardProPagination({ paginationArea={createCardProPagination({
preservePage: true,
currentPage: page, currentPage: page,
pageSize, pageSize,
total, total,
@@ -661,7 +674,7 @@ const Subscription = () => {
onCancel={() => setBanVisible(false)} onCancel={() => setBanVisible(false)}
onDone={() => { onDone={() => {
setBanVisible(false); setBanVisible(false);
fetchList(); setRefreshToken((key) => key + 1);
}} }}
t={t} t={t}
/> />
@@ -673,7 +686,7 @@ const Subscription = () => {
onCancel={() => setUnbanVisible(false)} onCancel={() => setUnbanVisible(false)}
onDone={() => { onDone={() => {
setUnbanVisible(false); setUnbanVisible(false);
fetchList(); setRefreshToken((key) => key + 1);
}} }}
t={t} t={t}
/> />
@@ -685,7 +698,7 @@ const Subscription = () => {
onCancel={() => setExtendVisible(false)} onCancel={() => setExtendVisible(false)}
onDone={() => { onDone={() => {
setExtendVisible(false); setExtendVisible(false);
fetchList(); setRefreshToken((key) => key + 1);
}} }}
t={t} t={t}
/> />
@@ -697,7 +710,7 @@ const Subscription = () => {
onCancel={() => setEditVisible(false)} onCancel={() => setEditVisible(false)}
onDone={() => { onDone={() => {
setEditVisible(false); setEditVisible(false);
fetchList(); setRefreshToken((key) => key + 1);
}} }}
t={t} t={t}
/> />
+4
View File
@@ -3,6 +3,7 @@ import test from 'node:test';
import React from 'react'; import React from 'react';
import * as Ant from 'antd'; import * as Ant from 'antd';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import * as consoleConstants from '../../src/constants/console.constants.js';
import * as pagination from '../../src/components/ui/pagination.js'; import * as pagination from '../../src/components/ui/pagination.js';
import * as overlayPolicy from '../../src/components/ui/overlayPolicy.js'; import * as overlayPolicy from '../../src/components/ui/overlayPolicy.js';
import { loadFrontendModule } from './frontend-module.js'; import { loadFrontendModule } from './frontend-module.js';
@@ -17,6 +18,9 @@ const controls = await loadFrontendModule(
react: { ...React, useId: () => 'generated-control-id' }, react: { ...React, useId: () => 'generated-control-id' },
antd: Ant, antd: Ant,
dayjs, dayjs,
'react-i18next': { useTranslation: () => ({ t: (key) => key }) },
'../../constants/console.constants': consoleConstants,
'../common/table/table-filter-range.css': {},
'../console/ConsoleContext': context, '../console/ConsoleContext': context,
}, },
); );
+41 -12
View File
@@ -11,8 +11,7 @@ async function fixture(kind) {
{ length: 24 }, { length: 24 },
(_, i) => 'aa-' + String(i + 1).padStart(2, '0'), (_, i) => 'aa-' + String(i + 1).padStart(2, '0'),
); );
const states = const states = kind === 'Missing' ? [5, false, models, 2] : [5, {}, 2];
kind === 'Missing' ? [5, false, models, 'AA', 2] : [5, {}, 2, 'AA'];
let cursor = 0; let cursor = 0;
const react = { const react = {
...React, ...React,
@@ -51,6 +50,22 @@ async function fixture(kind) {
react, react,
'react-i18next': { useTranslation: () => ({ t: (key) => key }) }, 'react-i18next': { useTranslation: () => ({ t: (key) => key }) },
'@/components/ui': ui, '@/components/ui': ui,
'@/hooks/common/useLocalTableFilters': {
useLocalTableFilters: () => ({
draft: { searchKeyword: 'AA' },
applied: { searchKeyword: 'AA' },
changeFilters: ({ searchKeyword }) =>
calls.push(['search', searchKeyword]),
submitSearch: () => {},
resetFilters: () => {},
}),
},
'@/hooks/common/useFilteredTableRows': {
useFilteredTableRows: (rows, matches) => rows.filter(matches),
},
'@/hooks/common/useEffectEvent': {
useEffectEvent: (callback) => callback,
},
'../../../../hooks/common/useEffectEvent': { '../../../../hooks/common/useEffectEvent': {
useEffectEvent: (callback) => callback, useEffectEvent: (callback) => callback,
}, },
@@ -105,11 +120,12 @@ for (const kind of ['Missing', 'Upstream']) {
assert.equal(table.pagination.total, 24); assert.equal(table.pagination.total, 24);
assert.equal(table.pagination.pageSize, 5); assert.equal(table.pagination.pageSize, 5);
assert.equal(table.pagination.currentPage, 2); assert.equal(table.pagination.currentPage, 2);
assert.equal(table.pagination.preservePage, true);
}, },
); );
test( test(
kind + kind +
': search and size changes reset the current page without network calls', ': search retains the page and size changes reset it without network calls',
async () => { async () => {
const { calls, table, input } = await fixture(kind); const { calls, table, input } = await fixture(kind);
table.pagination.onPageSizeChange(20); table.pagination.onPageSizeChange(20);
@@ -117,8 +133,7 @@ for (const kind of ['Missing', 'Upstream']) {
assert.ok(calls.some(([, value]) => value === 20)); assert.ok(calls.some(([, value]) => value === 20));
calls.length = 0; calls.length = 0;
input.onChange('aa-24'); input.onChange('aa-24');
assert.ok(calls.some(([, value]) => value === 'aa-24')); assert.deepEqual(calls, [['search', 'aa-24']]);
assert.ok(calls.some(([, value]) => value === 1));
}, },
); );
} }
@@ -135,6 +150,24 @@ async function modelTestFixture() {
react: { react: {
...React, ...React,
useState: () => [5, (value) => calls.push(['size', value])], useState: () => [5, (value) => calls.push(['size', value])],
useEffect: () => {},
useMemo: (fn) => fn(),
useCallback: (fn) => fn,
},
'@/hooks/common/useEffectEvent': {
useEffectEvent: (callback) => callback,
},
'@/hooks/common/useLocalTableFilters': {
useLocalTableFilters: () => ({
draft: { keyword: 'AA' },
applied: { keyword: 'AA' },
changeFilters: ({ keyword }) => calls.push(['search', keyword]),
submitSearch: () => {},
resetFilters: () => {},
}),
},
'@/hooks/common/useFilteredTableRows': {
useFilteredTableRows: (rows, matches) => rows.filter(matches),
}, },
antd: { antd: {
...Object.fromEntries( ...Object.fromEntries(
@@ -154,13 +187,11 @@ async function modelTestFixture() {
); );
const tree = Component({ const tree = Component({
currentTestChannel: { id: 7, name: 'channel', models: models.join(',') }, currentTestChannel: { id: 7, name: 'channel', models: models.join(',') },
modelSearchKeyword: 'AA',
modelTablePage: 2, modelTablePage: 2,
selectedModelKeys: [], selectedModelKeys: [],
modelTestResults: {}, modelTestResults: {},
testingModels: new Set(), testingModels: new Set(),
setModelTablePage: (value) => calls.push(['page', value]), setModelTablePage: (value) => calls.push(['page', value]),
setModelSearchKeyword: (value) => calls.push(['search', value]),
t: (key) => key, t: (key) => key,
}); });
const find = (type, node = tree) => const find = (type, node = tree) =>
@@ -187,6 +218,7 @@ test('Model test dialog passes the complete filtered list to local table paginat
models, models,
); );
assert.equal(table.pagination.total, undefined); assert.equal(table.pagination.total, undefined);
assert.equal(table.pagination.preservePage, true);
assert.equal(table.pagination.current, 2); assert.equal(table.pagination.current, 2);
assert.equal(table.pagination.pageSize, 5); assert.equal(table.pagination.pageSize, 5);
const html = renderToStaticMarkup(React.createElement(AntTable, table)); const html = renderToStaticMarkup(React.createElement(AntTable, table));
@@ -197,7 +229,7 @@ test('Model test dialog passes the complete filtered list to local table paginat
); );
}); });
test('Model test dialog preserves page changes and resets after search or size changes', async () => { test('Model test dialog retains the page after search and resets after size changes', async () => {
const { calls, table, input } = await modelTestFixture(); const { calls, table, input } = await modelTestFixture();
table.pagination.onChange(3, 5); table.pagination.onChange(3, 5);
assert.deepEqual(calls.splice(0), [ assert.deepEqual(calls.splice(0), [
@@ -210,8 +242,5 @@ test('Model test dialog preserves page changes and resets after search or size c
['size', 20], ['size', 20],
]); ]);
input.onChange({ target: { value: 'aa-24' } }); input.onChange({ target: { value: 'aa-24' } });
assert.deepEqual(calls, [ assert.deepEqual(calls, [['search', 'aa-24']]);
['search', 'aa-24'],
['page', 1],
]);
}); });
+20 -6
View File
@@ -73,10 +73,20 @@ async function exercise(
seqRef: { current: 0 }, seqRef: { current: 0 },
orgRef: { current: 77 }, orgRef: { current: 77 },
fetchSeqRef: { current: 0 }, fetchSeqRef: { current: 0 },
request: { current: 0 },
searchKeyword: 'pagination-fixture', searchKeyword: 'pagination-fixture',
appliedKeyword: 'pagination-fixture', appliedKeyword: 'pagination-fixture',
appliedOrderId: 42, appliedOrderId: 42,
appliedUserId: 7, appliedUserId: 7,
appliedStatus: '',
appliedPaymentMethod: '',
appliedDateRange: [],
appliedFilters: {
planTypes: [],
tiers: [],
statuses: [],
endDateRange: null,
},
statusFilter: '', statusFilter: '',
paymentMethodFilter: '', paymentMethodFilter: '',
dateRange: [], dateRange: [],
@@ -184,6 +194,7 @@ for (const cfg of [
file: 'src/pages/AdminInvoice/index.jsx', file: 'src/pages/AdminInvoice/index.jsx',
fn: 'fetchInvoices', fn: 'fetchInvoices',
expectedPath: '/api/invoice/list', expectedPath: '/api/invoice/list',
args: [new AbortController().signal],
}, },
{ {
file: 'src/pages/UserCenter/Invoice.jsx', file: 'src/pages/UserCenter/Invoice.jsx',
@@ -326,12 +337,11 @@ for (const cfg of [
{ {
file: 'src/pages/Organization/datasecurity/OrgDsHitLogs.jsx', file: 'src/pages/Organization/datasecurity/OrgDsHitLogs.jsx',
fn: 'fetchLogs', fn: 'fetchLogs',
args: [3, false], args: [new AbortController().signal],
expectedPath: '/api/org/data-security/logs', expectedPath: '/api/org/data-security/logs',
pageKey: 'page', pageKey: 'page',
values: { values: {
logsSeqRef: { current: 0 }, query: { page: 3, sensitiveOnly: false },
lastAttemptedPageRef: { current: 1 },
headers: {}, headers: {},
}, },
}, },
@@ -537,10 +547,13 @@ test('Multi-key read pagination preserves existing POST action and response fiel
channel: { id: 7 }, channel: { id: 7 },
currentPage: 3, currentPage: 3,
pageSize: 50, pageSize: 50,
statusFilter: 1, AbortController,
appliedStatus: { current: 1 },
activeRequest: { current: null },
cancelQuery: () => {},
API: { API: {
post: async (path, data) => { post: async (path, data, options) => {
calls.push({ path, data }); calls.push({ path, data, options });
return { return {
data: { data: {
success: true, success: true,
@@ -580,6 +593,7 @@ test('Multi-key read pagination preserves existing POST action and response fiel
assert.equal(calls[0].data.action, 'get_key_status'); assert.equal(calls[0].data.action, 'get_key_status');
assert.equal(calls[0].data.page, 3); assert.equal(calls[0].data.page, 3);
assert.equal(calls[0].data.page_size, 50); assert.equal(calls[0].data.page_size, 50);
assert.ok(calls[0].options.signal instanceof AbortSignal);
assert.equal(states.total, 156); assert.equal(states.total, 156);
assert.equal(states.rows[0], sentinel); assert.equal(states.rows[0], sentinel);
assert.equal(states.loading, false); assert.equal(states.loading, false);
+14 -3
View File
@@ -128,13 +128,17 @@ test('targets and run directories reject ambiguous or unsafe values', () => {
}); });
test('mobile retains UA, touch and DPR while using the requested CSS viewport', () => { test('mobile retains UA, touch and DPR while using the requested CSS viewport', () => {
assert.equal(projectViewports.length, 8); assert.equal(projectViewports.length, 9);
const mobile = contextOptions('mobile'); const mobile = contextOptions('mobile');
assert.deepEqual(mobile.viewport, { width: 360, height: 800 }); assert.deepEqual(mobile.viewport, { width: 360, height: 800 });
assert.equal(mobile.deviceScaleFactor, 2.75); assert.equal(mobile.deviceScaleFactor, 2.75);
assert.equal(mobile.hasTouch, true); assert.equal(mobile.hasTouch, true);
assert.equal(mobile.isMobile, true); assert.equal(mobile.isMobile, true);
assert.match(mobile.userAgent, /Mobile/); assert.match(mobile.userAgent, /Mobile/);
assert.deepEqual(contextOptions('mobile-393'), {
...mobile,
viewport: { width: 393, height: 851 },
});
assert.equal(contextOptions('tablet').hasTouch, false); assert.equal(contextOptions('tablet').hasTouch, false);
}); });
@@ -163,8 +167,15 @@ test('config isolates HTML, JUnit and traces and supports extended projects', ()
PW_WORKERS: '1', PW_WORKERS: '1',
PW_TARGET: 'local-dev', PW_TARGET: 'local-dev',
}); });
assert.equal(base.projects.length, 2); assert.deepEqual(
assert.equal(ci.projects.length, 8); base.projects.map(({ name }) => name),
['chrome-desktop', 'chrome-mobile', 'chrome-mobile-393'],
);
assert.deepEqual(
base.projects.find(({ name }) => name === 'chrome-mobile').use.viewport,
{ width: 360, height: 800 },
);
assert.equal(ci.projects.length, 9);
assert.equal(base.use.headless, false); assert.equal(base.use.headless, false);
assert.equal(ci.use.headless, true); assert.equal(ci.use.headless, true);
assert.ok( assert.ok(