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