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

This commit is contained in:
zhanjunhao
2026-11-24 20:14:10 +08:00
parent 437a0345e8
commit dd4da99f1d
83 changed files with 2094 additions and 1355 deletions
@@ -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);
};
+3 -4
View File
@@ -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(() => {});
}
}}
/>
+1
View File
@@ -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,12 +91,10 @@ const ModelTestModal = ({
const handleSelectSuccess = () => {
if (!currentTestChannel) return;
const successKeys = models
.filter((m) => m.toLowerCase().includes(modelSearchKeyword.toLowerCase()))
.filter((m) => {
const result = modelTestResults[`${currentTestChannel.id}-${m}`];
return result && result.success;
});
const successKeys = filteredModels.filter((m) => {
const result = modelTestResults[`${currentTestChannel.id}-${m}`];
return result && result.success;
});
if (successKeys.length === 0) {
showInfo(t('暂无成功模型'));
}
@@ -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,
+6 -12
View File
@@ -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);
refresh();
}
}}
>
+1
View File
@@ -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 (
+3
View File
@@ -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),
);
}, [dataSource, searchKeyword]);
const matches = useCallback(
(item) => (item.model_name || '').toLowerCase().includes(keyword),
[keyword],
);
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);
refresh();
}
};
@@ -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>
+1
View File
@@ -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);
refresh();
};
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,
+3 -4
View File
@@ -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 (
+1
View File
@@ -84,6 +84,7 @@ const UsersPage = () => {
}
tableActions={<UsersActions setShowAddUser={setShowAddUser} t={t} />}
paginationArea={createCardProPagination({
preservePage: true,
showRange: false,
currentPage: usersData.activePage,
pageSize: usersData.pageSize,
+65 -8
View File
@@ -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) => ({
label: p.label || p.text,
value: convert(p.value || (p.start && [p.start, p.end])),
}))}
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 : '')
}
+61 -30
View File
@@ -341,34 +341,60 @@ 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 });
const changePage = (page, size) => {
setLocalPage(size === pageSize ? page : 1);
if (size !== pageSize && managesSize) {
setLocalSize(size);
if (current !== 1) config.onPageChange?.(1);
} else {
events.onChange(page, size);
}
};
return (
<Component
{...props}
pagination={{
...centerPaginationOptions({ className: config.className }, isMobile),
current,
pageSize,
onChange: (page, size) => {
setLocalPage(size === pageSize ? page : 1);
if (size !== pageSize && managesSize) {
setLocalSize(size);
if (current !== 1) config.onPageChange?.(1);
} else {
events.onChange(page, size);
}
},
}}
/>
<>
<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;
const outsideResults = preservePage && page !== validPage;
if (!total && !outsideResults) return null;
const options = centerPaginationOptions(
{ className, showSizeChanger: hasPageSizeHandler(config) },
isMobile,
);
return (
<Ant.Pagination
{...centerPaginationOptions(
{ className, showSizeChanger: hasPageSizeHandler(config) },
isMobile,
)}
{...options}
{...centerPaginationEvents(config)}
current={resolvedPage}
current={outsideResults ? page : validPage}
pageSize={pageSize}
total={total}
total={outsideResults ? (page - 1) * pageSize + 1 : total}
showTotal={() => options.showTotal(total)}
/>
);
}
+3 -1
View File
@@ -1046,6 +1046,7 @@ export const formatPriceInfo = (priceData, t) => {
// CardPro 分页配置函数
// 用于创建 CardPro 的 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}
+11 -29
View File
@@ -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,
+82 -47
View File
@@ -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);
}
},
[refreshAll],
);
const handlePeriodChange = (newPeriod) => {
setPeriod(newPeriod);
if (newPeriod !== 'custom') {
const emptyRange = [null, null];
setDateRange(emptyRange);
scheduleSearch({ period: newPeriod, dateRange: emptyRange });
}
};
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,
};
};
+53 -40
View File
@@ -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,41 +303,51 @@ 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}` : '';
const res = await API.get(
`/api/channel/?p=${page}&page_size=${pageSize}&id_sort=${idSort}&tag_mode=${enableTagMode}${typeParam}${statusParam}`,
);
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) {
return;
}
const { success, message, data } = res.data;
if (success) {
const { items, total, type_counts } = data;
if (type_counts) {
const sumAll = Object.values(type_counts).reduce(
(acc, v) => acc + v,
0,
);
setTypeCounts({ ...type_counts, all: sumAll });
if (
res === undefined ||
signal?.aborted ||
reqId !== requestCounter.current
) {
return;
}
setChannelFormat(items, enableTagMode);
setChannelCount(total);
// 获取日消耗数据
fetchDailyQuotaInfo(items);
} else {
showError(message);
const { success, message, data } = res.data;
if (success) {
const { items, total, type_counts } = data;
if (type_counts) {
const sumAll = Object.values(type_counts).reduce(
(acc, v) => acc + v,
0,
);
setTypeCounts({ ...type_counts, all: sumAll });
}
setChannelFormat(items, enableTagMode);
setChannelCount(total);
// 获取日消耗数据
fetchDailyQuotaInfo(items);
} else {
showError(message);
}
} finally {
if (reqId === requestCounter.current) setLoading(false);
}
setLoading(false);
};
// Search channels
@@ -348,23 +358,28 @@ export const useChannelsData = () => {
page = 1,
pageSz = pageSize,
sortFlag = idSort,
signal,
) => {
const { searchKeyword, searchGroup, searchModel } = getFormValues();
if (searchKeyword === '' && searchGroup === '' && searchModel === '') {
await loadChannels(
page,
pageSz,
sortFlag,
enableTagMode,
typeKey,
statusF,
signal,
);
return;
}
const reqId = ++requestCounter.current;
setLoading(false);
setSearching(true);
try {
if (searchKeyword === '' && searchGroup === '' && searchModel === '') {
await loadChannels(
page,
pageSz,
sortFlag,
enableTagMode,
typeKey,
statusF,
);
return;
}
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,
+54 -7
View File
@@ -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?.();
},
};
}
+26
View File
@@ -0,0 +1,26 @@
import { useEffect, useMemo, useState } from 'react';
import { filterTableRows } from '../../components/common/table/filterTableRows';
export function useFilteredTableRows(items, matches) {
const [filtered, setFiltered] = useState([]);
const small = items.length <= 500;
useEffect(() => {
if (small) return;
const controller = new AbortController();
const { signal } = controller;
void filterTableRows(items, matches, signal)
.then((result) => {
if (!signal.aborted) setFiltered(result);
})
.catch((error) => {
if (!signal.aborted) throw error;
});
return () => controller.abort();
}, [items, matches, small]);
return useMemo(
() => (small ? items.filter(matches) : filtered),
[filtered, items, matches, small],
);
}
+27
View File
@@ -0,0 +1,27 @@
import { useState } from 'react';
import { useFilterSearch } from './useFilterSearch';
export function useLocalTableFilters(defaults) {
const [draft, setDraft] = useState(defaults);
const [applied, setApplied] = useState(defaults);
const { scheduleSearch, submitSearch, cancelPendingSearch } = useFilterSearch(
(filters) => setApplied(filters ?? draft),
);
const changeFilters = (fields) => {
setDraft((current) => ({ ...current, ...fields }));
scheduleSearch();
};
return {
draft,
applied,
changeFilters,
submitSearch,
resetFilters() {
cancelPendingSearch();
setDraft(defaults);
setApplied(defaults);
},
};
}
+21
View File
@@ -0,0 +1,21 @@
import { useCallback, useEffect, useRef } from 'react';
export function useTableFilterQuery(query, version) {
const activeRequest = useRef(null);
const cancelQuery = useCallback(() => activeRequest.current?.abort(), []);
const reloadQuery = useCallback(() => {
cancelQuery();
const controller = new AbortController();
activeRequest.current = controller;
return query(controller.signal);
}, [cancelQuery, query]);
useEffect(() => {
void reloadQuery();
return cancelQuery;
// The version changes when the caller refreshes with the same conditions.
}, [cancelQuery, reloadQuery, version]);
return { cancelQuery, reloadQuery };
}
+7 -6
View File
@@ -202,7 +202,7 @@ export const useMjLogsData = () => {
// Load logs function
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
+55 -56
View File
@@ -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);
}
}
setLoading(false);
};
// Refresh data
const loadModels = (
page = 1,
size = pageSize,
vendorKey = activeVendorKey,
signal,
) => {
const vendor = vendorKey && vendorKey !== 'all' ? vendorKey : undefined;
return fetchModels(
vendor ? '/api/models/search' : '/api/models/',
{
p: page,
page_size: size,
vendor,
},
page,
signal,
);
};
const refresh = async (page = activePage) => {
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}`,
);
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);
return fetchModels(
'/api/models/search',
{
keyword: searchKeyword,
vendor: searchVendor,
category: searchCategory,
p: page,
page_size: size,
},
page,
signal,
true,
);
};
// 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
+37 -13
View File
@@ -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) {
showError(err.message);
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) {
showError(err.message);
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) {
showError(err.message);
if (!signal?.aborted && id === request.current && !err.isAxiosError)
showError(err.message);
} finally {
setLoading(false);
if (id === request.current) setLoading(false);
}
},
[orgId],
+41 -23
View File
@@ -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,
+19 -12
View File
@@ -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);
}
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) => {
+12 -6
View File
@@ -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
+15 -8
View File
@@ -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}`);
const { success, message, data } = res.data;
if (success) {
syncPageData(data);
} else {
showError(message);
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);
}
setLoading(false);
};
// Refresh function
+29 -22
View File
@@ -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);
} catch (error) {
if (!signal?.aborted && !error.isAxiosError) showError(error);
} finally {
if (requestId === statRequest.current) setLoadingStat(false);
}
setShowStat(true);
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
+17 -7
View File
@@ -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);
}
};
+5
View File
@@ -55,6 +55,11 @@ async function createHarness() {
},
];
},
useRef(current) {
const index = cursor++;
if (mounting) states[index] = { current };
return states[index];
},
useEffect(effect) {
if (mounting) effects.push(effect);
},
+48 -39
View File
@@ -15,7 +15,9 @@ import ConsoleCollection from '../../components/console/ConsoleCollection';
import TableEmpty from '../../components/common/table/TableEmpty';
import { 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,47 +86,51 @@ const AdminInvoice = () => {
const [adminRemark, setAdminRemark] = useState('');
const [approveLoading, setApproveLoading] = useState(false);
const fetchInvoices = useCallback(async () => {
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 (res.data.success) {
setInvoices(res.data.data?.items || []);
setTotal(res.data.data?.total || 0);
} else {
showError(res.data.message || t('查询失败'));
const fetchInvoices = useCallback(
async (signal) => {
setLoading(true);
try {
const params = { p: page, page_size: pageSize };
if (searchKeyword) params.keyword = searchKeyword;
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);
} else {
showError(res.data.message || t('查询失败'));
}
} catch (err) {
if (!signal.aborted && !err.isAxiosError) showError(err.message);
} finally {
if (!signal.aborted) setLoading(false);
}
} catch (err) {
showError(err.message);
} finally {
setLoading(false);
}
}, [page, pageSize, searchKeyword, statusFilter, t]);
},
[page, pageSize, searchKeyword, appliedStatus, t],
);
useEffect(() => {
fetchInvoices();
}, [fetchInvoices]);
const handleSearch = () => {
setPage(1);
setSearchKeyword(keyword);
};
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,
+76 -80
View File
@@ -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,59 +87,64 @@ 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 () => {
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 (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 });
if (res.data.success) {
setOrders(res.data.data?.items || []);
setTotal(res.data.data?.total || 0);
} else {
showError(res.data.message || t('查询失败'));
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 (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, signal });
if (signal?.aborted) return;
if (res.data.success) {
setOrders(res.data.data?.items || []);
setTotal(res.data.data?.total || 0);
} else {
showError(res.data.message || t('查询失败'));
}
} catch (err) {
if (!signal?.aborted && !err.isAxiosError) showError(err.message);
} finally {
if (!signal?.aborted) setLoading(false);
}
} catch (err) {
showError(err.message);
} finally {
setLoading(false);
}
}, [
page,
pageSize,
searchKeyword,
appliedOrderId,
appliedUserId,
statusFilter,
paymentMethodFilter,
dateRange,
appliedMinMoney,
appliedMaxMoney,
t,
]);
},
[
page,
pageSize,
searchKeyword,
appliedOrderId,
appliedUserId,
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,
+84 -94
View File
@@ -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,49 +309,58 @@ const AdminOrganizations = () => {
// 筛选/排序可高频连续触发请求,用递增序号丢弃过期响应,防止慢网下旧结果覆盖新筛选
const fetchSeqRef = useRef(0);
const fetchOrgs = useCallback(async () => {
const seq = ++fetchSeqRef.current;
setLoading(true);
try {
const params = { p: page, page_size: pageSize };
if (searchKeyword) params.keyword = searchKeyword;
if (statusFilter != null) params.status = statusFilter;
if (levelFilter) params.level = levelFilter;
if (salesRepFilter) params.sales_rep = salesRepFilter;
if (userIdFilter) params.user_id = userIdFilter;
if (sortBy) {
params.sort_by = sortBy;
params.sort_order = sortOrder || 'desc';
const fetchOrgs = useCallback(
async (signal) => {
const { statusFilter, levelFilter, salesRepFilter } = appliedFilters;
const seq = ++fetchSeqRef.current;
setLoading(true);
try {
const params = { p: page, page_size: pageSize };
if (searchKeyword) params.keyword = searchKeyword;
if (statusFilter != null) params.status = statusFilter;
if (levelFilter) params.level = levelFilter;
if (salesRepFilter) params.sales_rep = salesRepFilter;
if (userIdFilter) params.user_id = userIdFilter;
if (sortBy) {
params.sort_by = sortBy;
params.sort_order = sortOrder || 'desc';
}
const res = await API.get('/api/admin/organizations/', {
params,
signal,
});
if (signal?.aborted || seq !== fetchSeqRef.current) return;
if (res.data.success) {
setOrgs(res.data.data?.items || []);
setTotal(res.data.data?.total || 0);
} else {
showError(res.data.message || t('查询失败'));
}
} catch (err) {
if (
!signal?.aborted &&
seq === fetchSeqRef.current &&
!err.isAxiosError
)
showError(err.message);
} finally {
if (seq === fetchSeqRef.current) setLoading(false);
}
const res = await API.get('/api/admin/organizations/', { params });
if (seq !== fetchSeqRef.current) return;
if (res.data.success) {
setOrgs(res.data.data?.items || []);
setTotal(res.data.data?.total || 0);
} else {
showError(res.data.message || t('查询失败'));
}
} catch (err) {
if (seq === fetchSeqRef.current) showError(err.message);
} finally {
if (seq === fetchSeqRef.current) setLoading(false);
}
}, [
page,
pageSize,
searchKeyword,
statusFilter,
levelFilter,
salesRepFilter,
userIdFilter,
sortBy,
sortOrder,
t,
]);
},
[
page,
pageSize,
searchKeyword,
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);
setSearchKeyword(keyword.trim());
setUserIdFilter(userIdInput);
setQueryVersion((version) => version + 1);
};
const { changeFilter, submitSearch, cancelPendingSearch } = useFilterSearch(
() => {
setSearchKeyword(keyword.trim());
setUserIdFilter(userIdInput);
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,
+23 -4
View File
@@ -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('每日统计明细')}
+53 -38
View File
@@ -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,39 +29,55 @@ export default function LatestTierPanel({
error: '',
});
const [exporting, setExporting] = useState(false);
const load = useCallback(async () => {
const current = ++generation.current;
setExporting(false);
setState((old) => ({ ...old, context, items: [], busy: true, error: '' }));
try {
const result = await fetchJSON(latestTierURL(query, query.page));
if (current !== generation.current || activeContext.current !== context)
return;
setState({
...result,
const [version, setVersion] = useState(0);
const load = useCallback(
async (signal) => {
const current = ++generation.current;
setExporting(false);
setState((old) => ({
...old,
context,
items: result.items.map((item) => ({ ...item, __asOf: result.as_of })),
busy: false,
items: [],
busy: true,
error: '',
});
} catch (error) {
if (current === generation.current && activeContext.current === context)
setState((old) => ({
...old,
items: [],
}));
try {
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,
})),
busy: false,
error: error.message,
}));
}
}, [fetchJSON, query, context]);
useEffect(() => {
load();
return () => {
// 卸载或重新加载时作废进行中的请求(原有逻辑)。
// eslint-disable-next-line react-hooks/exhaustive-deps
generation.current++;
};
}, [load]);
error: '',
});
} catch (error) {
if (
!signal.aborted &&
current === generation.current &&
activeContext.current === context
)
setState((old) => ({
...old,
items: [],
busy: false,
error: error.message,
}));
}
},
[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;
+30 -24
View File
@@ -1,4 +1,4 @@
import React, { useState } from 'react';
import React, { useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { 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,
},
section,
searchableText,
);
const query = () => {
setFilters(draft);
setPage(1);
server?.onChange({ ...draft, status, page: 1 });
};
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,
);
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);
+69 -37
View File
@@ -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,
+15 -14
View File
@@ -14,19 +14,20 @@ 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) =>
matchesStatus(row, filters.status, key) &&
(!filters.type ||
(key === 'partners'
? row.type
: 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)),
);
return (row) =>
matchesStatus(row, filters.status, key) &&
(!filters.type ||
(key === 'partners'
? row.type
: 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));
}
export function filterCommissionRows(rows, filters, key, searchableText) {
return rows.filter(createCommissionRowFilter(filters, key, searchableText));
}
+43 -43
View File
@@ -1,10 +1,12 @@
import { confirmTableAction } from '@/components/common/table/confirmTableAction';
import 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,38 +65,40 @@ export default function DemoReservations() {
setQuery(update);
};
useEffect(() => {
const controller = new AbortController();
const { signal } = controller;
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) {
setError(error.message || '预约信息加载失败,请重新查询');
setResult({ items: [], total: 0 });
}
})
.finally(() => {
if (!signal.aborted && !changedPage) setLoading(false);
});
return () => controller.abort();
}, [query]);
const load = useCallback(
(signal) => {
setLoading(true);
setError('');
fetchDemoReservations(query, { signal })
.then((data) => {
if (signal.aborted) return;
setResult(data);
})
.catch((error) => {
if (!signal.aborted) {
setError(error.message || '预约信息加载失败,请重新查询');
setResult({ items: [], total: 0 });
}
})
.finally(() => {
if (!signal.aborted) setLoading(false);
});
},
[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 }),
}}
+82 -84
View File
@@ -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,77 +120,83 @@ 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;
setLoading(true);
const errors = [];
const [summaryRes, trendRes, topUsersRes, recentRes] = await Promise.all([
API.get(
`/api/admin/playground/upload-audit/summary?range_hours=${rangeHours}`,
).catch((e) => {
errors.push(['summary', e]);
return null;
}),
API.get(
`/api/admin/playground/upload-audit/trend?range_hours=${rangeHours}&bucket=${rangeHours > 48 ? 'day' : 'hour'}`,
).catch((e) => {
errors.push(['trend', e]);
return null;
}),
API.get(
`/api/admin/playground/upload-audit/top-failing-users?range_hours=${rangeHours}&limit=10`,
).catch((e) => {
errors.push(['top-users', e]);
return null;
}),
API.get(
`/api/admin/playground/upload-audit/recent?range_hours=${rangeHours}&event=${encodeURIComponent(eventFilter)}&page=${page}&page_size=${pageSize}`,
).catch((e) => {
errors.push(['recent', e]);
return null;
}),
]);
// 过期响应直接丢弃:myId 落后于最新 id 说明用户已经发起新请求了
if (myId !== requestIdRef.current) {
return;
}
if (summaryRes?.data?.success) setSummary(summaryRes.data.data);
if (trendRes?.data?.success) setTrend(trendRes.data.data);
if (topUsersRes?.data?.success)
setTopUsers(topUsersRes.data.data?.items || []);
if (recentRes?.data?.success) {
setRecent({
items: recentRes.data.data?.items || [],
total: recentRes.data.data?.total || 0,
});
}
// 多块同时失败时,单独把每一块的错误都告诉用户;showError 内部会去重处理(如果 message 一致)
if (errors.length > 0) {
// 把 4 块名字翻成可读:summary/trend/top-users/recent → 数据看板加载(部分失败)
Toast.warning({
content: t('数据加载部分失败:{{names}}', {
names: errors.map((e) => e[0]).join(', '),
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;
}),
duration: 4,
});
// 同时把第一个 axios 错误细节也打到 Toast,方便定位(401/500 等)
showError(errors[0][1]);
}
setLoading(false);
}, [rangeHours, eventFilter, page, pageSize, t]);
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;
}),
]);
useEffect(() => {
loadAll();
}, [loadAll]);
if (signal.aborted) return;
if (summaryRes?.data?.success) setSummary(summaryRes.data.data);
if (trendRes?.data?.success) setTrend(trendRes.data.data);
if (topUsersRes?.data?.success)
setTopUsers(topUsersRes.data.data?.items || []);
if (recentRes?.data?.success) {
setRecent({
items: recentRes.data.data?.items || [],
total: recentRes.data.data?.total || 0,
});
}
// 多块同时失败时,单独把每一块的错误都告诉用户;showError 内部会去重处理(如果 message 一致)
if (errors.length > 0) {
// 把 4 块名字翻成可读:summary/trend/top-users/recent → 数据看板加载(部分失败)
Toast.warning({
content: t('数据加载部分失败:{{names}}', {
names: errors.map((e) => e[0]).join(', '),
}),
duration: 4,
});
// 同时把第一个 axios 错误细节也打到 Toast,方便定位(401/500 等)
showError(errors[0][1]);
}
setLoading(false);
},
[filters, page, pageSize, t],
);
const { cancelQuery, reloadQuery } = useTableFilterQuery(loadAll);
const { changeFilter, submitSearch } = useFilterSearch(() => {
if (
filters.rangeHours === rangeHours &&
filters.eventFilter === eventFilter
) {
return reloadQuery();
}
setFilters({ rangeHours, eventFilter });
}, cancelQuery);
// ----- 趋势图 spec -----
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,
+31 -18
View File
@@ -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)),
),
page,
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}
+26 -10
View File
@@ -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,
+26 -14
View File
@@ -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 filters = { dateRange, modelName: modelName.trim() };
setAppliedFilters(filters);
fetchLogs(1, filters);
};
const { changeFilter, submitSearch, cancelPendingSearch } = useFilterSearch(
(_, signal) => {
const filters = { dateRange, modelName: modelName.trim() };
setAppliedFilters(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,
+35 -19
View File
@@ -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,29 +330,39 @@ 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) {
fetchRanking(
{
userId: filters.userId,
startTimestamp: filters.startTimestamp,
endTimestamp: filters.endTimestamp,
modelName: filters.modelName,
},
forceRefresh,
requests.push(
fetchRanking(
{
userId: filters.userId,
startTimestamp: filters.startTimestamp,
endTimestamp: filters.endTimestamp,
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,
+25 -16
View File
@@ -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]);
+68 -53
View File
@@ -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,43 +45,57 @@ const FundLedgerSheet = ({ visible, account, fetchLedger, onClose }) => {
// 请求序号:快速改筛选或翻页时只采纳最后一次请求的结果。
const seqRef = useRef(0);
const load = useCallback(async () => {
if (!visible || !account?.id) return;
const [start, end] = range || [];
if (start && end && start > end) {
setRangeError(t('开始时间不能晚于结束时间'));
return;
}
setRangeError('');
const seq = ++seqRef.current;
setLoading(true);
setError('');
try {
const res = await fetchLedger(account.id, {
start_timestamp: start ? Math.floor(start.getTime() / 1000) : undefined,
end_timestamp: end ? Math.floor(end.getTime() / 1000) : undefined,
type: types.length ? types.join(',') : undefined,
p: page,
page_size: pageSize,
});
if (seq !== seqRef.current) return;
if (res?.data?.success) {
setItems(res.data.data?.items || []);
setTotal(res.data.data?.total || 0);
} else {
setError(res?.data?.message || t('加载失败,请重试'));
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;
}
} catch {
// 保留旧数据并标识刷新失败,不把旧数据冒充为最新
if (seq === seqRef.current) setError(t('数据刷新失败,请重试'));
} finally {
if (seq === seqRef.current) setLoading(false);
}
}, [visible, account?.id, range, types, page, pageSize, fetchLedger, t]);
setRangeError('');
const seq = ++seqRef.current;
setLoading(true);
setError('');
try {
const res = await fetchLedger(
account.id,
{
start_timestamp: start
? Math.floor(start.getTime() / 1000)
: undefined,
end_timestamp: end ? Math.floor(end.getTime() / 1000) : undefined,
type: types.length ? types.join(',') : undefined,
p: page,
page_size: pageSize,
},
signal,
);
if (signal?.aborted || seq !== seqRef.current) return;
if (res?.data?.success) {
setItems(res.data.data?.items || []);
setTotal(res.data.data?.total || 0);
} else {
setError(res?.data?.message || t('加载失败,请重试'));
}
} catch {
// 保留旧数据并标识刷新失败,不把旧数据冒充为最新
if (!signal?.aborted && seq === seqRef.current)
setError(t('数据刷新失败,请重试'));
} finally {
if (seq === seqRef.current) setLoading(false);
}
},
[visible, account?.id, applied, page, pageSize, fetchLedger, t],
);
useEffect(() => {
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) => {
+1 -1
View File
@@ -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;
+4 -4
View File
@@ -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(
+54 -37
View File
@@ -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,40 +31,54 @@ 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) => {
setLoading(true);
try {
const base = userIsAdmin ? '/api/user/topup' : '/api/user/topup/self';
const qs =
`p=${currentPage}&page_size=${currentPageSize}` +
(keyword ? `&keyword=${encodeURIComponent(keyword)}` : '');
const endpoint = `${base}?${qs}`;
const res = await API.get(endpoint);
const { success, message, data } = res.data;
if (success) {
setTopups(data.items || []);
setTotal(data.total || 0);
} else {
Toast.error({ content: message || t('加载失败') });
const query = useCallback(
async (signal) => {
setLoading(true);
try {
const base = userIsAdmin ? '/api/user/topup' : '/api/user/topup/self';
const qs =
`p=${page}&page_size=${pageSize}` +
(appliedKeyword
? `&keyword=${encodeURIComponent(appliedKeyword)}`
: '');
const endpoint = `${base}?${qs}`;
const res = await API.get(endpoint, { signal });
if (signal?.aborted) return;
const { success, message, data } = res.data;
if (success) {
setTopups(data.items || []);
setTotal(data.total || 0);
} else {
Toast.error({ content: message || t('加载失败') });
}
} catch (error) {
if (!signal?.aborted && !error.isAxiosError)
Toast.error({ content: t('加载账单失败') });
} finally {
if (!signal?.aborted) setLoading(false);
}
} catch (error) {
console.error('Load topups error:', error);
Toast.error({ content: t('加载账单失败') });
} finally {
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}
+15 -9
View File
@@ -1,6 +1,8 @@
import { useLocalTableFilters } from '@/hooks/common/useLocalTableFilters';
import { useFilteredTableRows } from '@/hooks/common/useFilteredTableRows';
import TableActionPopconfirm from '@/components/common/table/TableActionPopconfirm';
import { 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>
) : (
+33 -43
View File
@@ -1,3 +1,5 @@
import { useLocalTableFilters } from '@/hooks/common/useLocalTableFilters';
import { useFilteredTableRows } from '@/hooks/common/useFilteredTableRows';
import { confirmTableAction } from '@/components/common/table/confirmTableAction';
import { 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 keywordMatch = searchText ? model.name.includes(searchText) : true;
const conflictMatch = conflictOnly ? model.hasConflict : true;
return keywordMatch && conflictMatch;
});
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,
+24 -30
View File
@@ -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,
+101 -88
View File
@@ -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,75 +175,85 @@ const Subscription = () => {
}
}, [t]);
const fetchList = useCallback(async () => {
setLoading(true);
try {
const params = { page, page_size: pageSize };
if (appliedKeyword) params.keyword = appliedKeyword;
if (appliedUserId) params.user_id = appliedUserId;
if (planTypes.length) params.plan_types = planTypes.join(',');
if (tiers.length) params.tiers = tiers.join(',');
if (statuses.length) params.statuses = statuses.join(',');
if (endDateRange && endDateRange[0]) {
params.end_date_from = Math.floor(endDateRange[0].getTime() / 1000);
}
if (endDateRange && endDateRange[1]) {
params.end_date_to = Math.floor(endDateRange[1].getTime() / 1000);
}
// 快捷筛选 (优先级覆盖 endDateRange)
const now = Math.floor(Date.now() / 1000);
if (quickFilter === 'expiring3') {
params.end_date_from = now;
params.end_date_to = now + 3 * 86400;
params.statuses = 'active';
} else if (quickFilter === 'expiring7') {
params.end_date_from = now;
params.end_date_to = now + 7 * 86400;
params.statuses = 'active';
} else if (quickFilter === 'overdue') {
params.end_date_to = now;
params.statuses = 'expired';
}
const fetchList = useCallback(
async (signal) => {
const { planTypes, tiers, statuses, endDateRange } = appliedFilters;
setLoading(true);
try {
const params = { page, page_size: pageSize };
if (appliedKeyword) params.keyword = appliedKeyword;
if (appliedUserId) params.user_id = appliedUserId;
if (planTypes.length) params.plan_types = planTypes.join(',');
if (tiers.length) params.tiers = tiers.join(',');
if (statuses.length) params.statuses = statuses.join(',');
if (endDateRange && endDateRange[0]) {
params.end_date_from = Math.floor(endDateRange[0].getTime() / 1000);
}
if (endDateRange && endDateRange[1]) {
params.end_date_to = Math.floor(endDateRange[1].getTime() / 1000);
}
// 快捷筛选 (优先级覆盖 endDateRange)
const now = Math.floor(Date.now() / 1000);
if (quickFilter === 'expiring3') {
params.end_date_from = now;
params.end_date_to = now + 3 * 86400;
params.statuses = 'active';
} else if (quickFilter === 'expiring7') {
params.end_date_from = now;
params.end_date_to = now + 7 * 86400;
params.statuses = 'active';
} else if (quickFilter === 'overdue') {
params.end_date_to = now;
params.statuses = 'expired';
}
const res = await API.get('/api/user/membership/manage/subscriptions', {
params,
});
if (res.data.success) {
setList(res.data.data?.list || []);
setTotal(res.data.data?.total || 0);
} else {
showError(res.data.message || t('查询失败'));
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);
} else {
showError(res.data.message || t('查询失败'));
}
} catch (err) {
if (!signal?.aborted && !err.isAxiosError) showError(err.message);
} finally {
if (!signal?.aborted) setLoading(false);
}
} catch (err) {
showError(err.message);
} finally {
setLoading(false);
}
}, [
page,
pageSize,
appliedKeyword,
appliedUserId,
planTypes,
tiers,
statuses,
endDateRange,
quickFilter,
t,
]);
},
[
page,
pageSize,
appliedKeyword,
appliedUserId,
appliedFilters,
quickFilter,
t,
],
);
useEffect(() => {
fetchList();
}, [fetchList, refreshToken]);
const { cancelQuery } = useTableFilterQuery(fetchList, refreshToken);
const handleSearch = () => {
setPage(1);
setAppliedKeyword(keyword);
setAppliedUserId(userId);
setQuickFilter(null);
};
const { changeFilter, submitSearch, cancelPendingSearch } = useFilterSearch(
() => {
setAppliedKeyword(keyword);
setAppliedUserId(userId);
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}
/>