refactor(shared): 提取公共状态逻辑并修复用户列表分页

统一存储解析、通知已读状态、表格偏好和企业日志筛选参数。修复切换每页条数时沿用旧页码、丢失筛选条件和重复触发分页回调的问题。
同步调整项目检查脚本、格式配置和开发文档。
This commit is contained in:
zhanjunhao
2026-10-21 18:47:21 +08:00
parent ae190663f0
commit 67d08b69c2
30 changed files with 1484 additions and 466 deletions
+16 -43
View File
@@ -17,49 +17,31 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useEffect } from 'react';
import { useState, useEffect, useCallback } from 'react';
import {
getUnreadAnnouncementKeys,
markAnnouncementsRead,
readNoticeReadKeys,
} from '../../helpers/notificationReadState.js';
const EMPTY_ANNOUNCEMENTS = [];
export const useNotifications = (statusState) => {
const [noticeVisible, setNoticeVisible] = useState(false);
const [unreadCount, setUnreadCount] = useState(0);
const announcements = statusState?.status?.announcements || [];
const announcements =
statusState?.status?.announcements || EMPTY_ANNOUNCEMENTS;
// Helper functions
const getAnnouncementKey = (a) =>
`${a?.publishDate || ''}-${(a?.content || '').slice(0, 30)}`;
const calculateUnreadCount = () => {
if (!announcements.length) return 0;
let readKeys = [];
try {
readKeys = JSON.parse(localStorage.getItem('notice_read_keys')) || [];
} catch (_) {
readKeys = [];
}
const readSet = new Set(readKeys);
return announcements.filter((a) => !readSet.has(getAnnouncementKey(a)))
.length;
};
const getUnreadKeys = () => {
const getUnreadKeys = useCallback(() => {
if (!announcements.length) return [];
let readKeys = [];
try {
readKeys = JSON.parse(localStorage.getItem('notice_read_keys')) || [];
} catch (_) {
readKeys = [];
}
const readSet = new Set(readKeys);
return announcements
.filter((a) => !readSet.has(getAnnouncementKey(a)))
.map(getAnnouncementKey);
};
return getUnreadAnnouncementKeys(announcements, readNoticeReadKeys());
}, [announcements]);
// Effects
useEffect(() => {
setUnreadCount(calculateUnreadCount());
}, [announcements]);
setUnreadCount(getUnreadKeys().length);
}, [getUnreadKeys]);
// Actions
const handleNoticeOpen = () => {
@@ -69,16 +51,7 @@ export const useNotifications = (statusState) => {
const handleNoticeClose = () => {
setNoticeVisible(false);
if (announcements.length) {
let readKeys = [];
try {
readKeys = JSON.parse(localStorage.getItem('notice_read_keys')) || [];
} catch (_) {
readKeys = [];
}
const mergedKeys = Array.from(
new Set([...readKeys, ...announcements.map(getAnnouncementKey)]),
);
localStorage.setItem('notice_read_keys', JSON.stringify(mergedKeys));
markAnnouncementsRead(announcements);
}
setUnreadCount(0);
};
+7 -8
View File
@@ -18,8 +18,12 @@ For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useEffect, useCallback } from 'react';
import { getTableCompactMode, setTableCompactMode } from '../../helpers';
import { TABLE_COMPACT_MODES_KEY } from '../../constants';
import {
getTableCompactMode,
parseTableCompactMode,
setTableCompactMode,
} from '../../helpers/tableCompactMode.js';
import { TABLE_COMPACT_MODES_KEY } from '../../constants/common.constant.js';
/**
* 自定义 Hook:管理表格紧凑/自适应模式
@@ -42,12 +46,7 @@ export function useTableCompactMode(tableKey = 'global') {
useEffect(() => {
const handleStorage = (e) => {
if (e.key === TABLE_COMPACT_MODES_KEY) {
try {
const modes = JSON.parse(e.newValue || '{}');
setCompactModeState(!!modes[tableKey]);
} catch {
// ignore parse error
}
setCompactModeState(parseTableCompactMode(e.newValue, tableKey));
}
};
window.addEventListener('storage', handleStorage);
+11 -28
View File
@@ -19,6 +19,7 @@ For commercial licensing, please contact support@quantumnous.com
import { useState, useCallback, useEffect, useRef } from 'react';
import { API } from '../../helpers/api';
import { showError } from '../../helpers';
import { buildOrgLogFilters } from '../../helpers/orgLogFilters.js';
// 获取企业X-Org-Id header
const getOrgHeaders = (orgId) => ({
@@ -239,19 +240,15 @@ export function useOrgMemberLogs(orgId) {
const [loading, setLoading] = useState(false);
const fetch = useCallback(
async (
page = 1,
pageSize = 20,
{ userId, startTimestamp, endTimestamp, modelName } = {},
) => {
async (page = 1, pageSize = 20, filters = {}) => {
if (!orgId) return;
setLoading(true);
try {
const params = { p: page, page_size: pageSize };
if (userId) params.user_id = userId;
if (startTimestamp) params.start_timestamp = startTimestamp;
if (endTimestamp) params.end_timestamp = endTimestamp;
if (modelName) params.model_name = modelName;
const params = {
p: page,
page_size: pageSize,
...buildOrgLogFilters(filters),
};
const res = await API.get('/api/org/logs', {
headers: getOrgHeaders(orgId),
@@ -292,18 +289,11 @@ export function useOrgLogsStat(orgId) {
const [loading, setLoading] = useState(false);
const fetch = useCallback(
async (
{ userId, startTimestamp, endTimestamp, modelName } = {},
noCache = false,
) => {
async (filters = {}, noCache = false) => {
if (!orgId) return;
setLoading(true);
try {
const params = {};
if (userId) params.user_id = userId;
if (startTimestamp) params.start_timestamp = startTimestamp;
if (endTimestamp) params.end_timestamp = endTimestamp;
if (modelName) params.model_name = modelName;
const params = buildOrgLogFilters(filters);
if (noCache) params.nocache = 1;
const res = await API.get('/api/org/logs/stat', {
@@ -346,18 +336,11 @@ export function useOrgMemberRanking(orgId) {
const [loading, setLoading] = useState(false);
const fetch = useCallback(
async (
{ userId, startTimestamp, endTimestamp, modelName, limit } = {},
noCache = false,
) => {
async ({ limit, ...filters } = {}, noCache = false) => {
if (!orgId) return;
setLoading(true);
try {
const params = {};
if (userId) params.user_id = userId;
if (startTimestamp) params.start_timestamp = startTimestamp;
if (endTimestamp) params.end_timestamp = endTimestamp;
if (modelName) params.model_name = modelName;
const params = buildOrgLogFilters(filters);
if (limit) params.limit = limit;
if (noCache) params.nocache = 1;
+8 -18
View File
@@ -29,6 +29,7 @@ import {
timestamp2string,
} from '../../helpers';
import { EVENTS, emit } from '../../helpers/eventBus';
import { resolveColumnVisibility } from '../../helpers/columnVisibility';
import { ITEMS_PER_PAGE } from '../../constants';
import { useTableCompactMode } from '../common/useTableCompactMode';
@@ -136,24 +137,13 @@ export const useTaskLogsData = () => {
// Load saved column preferences from localStorage
useEffect(() => {
const savedColumns = localStorage.getItem(STORAGE_KEY);
if (savedColumns) {
try {
const parsed = JSON.parse(savedColumns);
const defaults = getDefaultColumnVisibility();
const merged = { ...defaults, ...parsed };
// For non-admin users, force-hide admin-only columns (does not touch admin settings)
if (!isAdminUser) {
merged[COLUMN_KEYS.CHANNEL] = false;
}
setVisibleColumns(merged);
} catch (e) {
console.error('Failed to parse saved column preferences', e);
initDefaultColumns();
}
} else {
initDefaultColumns();
}
setVisibleColumns(
resolveColumnVisibility(
getDefaultColumnVisibility(),
savedColumns,
isAdminUser ? [] : [COLUMN_KEYS.CHANNEL],
),
);
}, []);
// Get default column visibility based on user role
+10 -20
View File
@@ -34,6 +34,7 @@ import {
import { ITEMS_PER_PAGE } from '../../constants';
import { useTableCompactMode } from '../common/useTableCompactMode';
import { EVENTS, subscribe } from '../../helpers/eventBus';
import { resolveColumnVisibility } from '../../helpers/columnVisibility';
export const useLogsData = () => {
const { t } = useTranslation();
@@ -191,26 +192,15 @@ export const useLogsData = () => {
// Load saved column preferences from localStorage
useEffect(() => {
const savedColumns = localStorage.getItem(STORAGE_KEY);
if (savedColumns) {
try {
const parsed = JSON.parse(savedColumns);
const defaults = getDefaultColumnVisibility();
const merged = { ...defaults, ...parsed };
// For non-admin users, force-hide admin-only columns (does not touch admin settings)
if (!isAdminUser) {
merged[COLUMN_KEYS.CHANNEL] = false;
merged[COLUMN_KEYS.USERNAME] = false;
merged[COLUMN_KEYS.RETRY] = false;
}
setVisibleColumns(merged);
} catch (e) {
console.error('Failed to parse saved column preferences', e);
initDefaultColumns();
}
} else {
initDefaultColumns();
}
setVisibleColumns(
resolveColumnVisibility(
getDefaultColumnVisibility(),
savedColumns,
isAdminUser
? []
: [COLUMN_KEYS.CHANNEL, COLUMN_KEYS.USERNAME, COLUMN_KEYS.RETRY],
),
);
}, []);
// Get default column visibility based on user role
+44 -41
View File
@@ -72,17 +72,22 @@ export const useUsersData = () => {
// Load users data
const loadUsers = async (startIdx, pageSize) => {
setLoading(true);
const res = await API.get(`/api/user/?p=${startIdx}&page_size=${pageSize}`);
const { success, message, data } = res.data;
if (success) {
const newPageData = data.items;
setActivePage(data.page);
setUserCount(data.total);
setUserFormat(newPageData);
} else {
showError(message);
try {
const res = await API.get(
`/api/user/?p=${startIdx}&page_size=${pageSize}`,
);
const { success, message, data } = res.data;
if (success) {
const newPageData = data.items;
setActivePage(data.page);
setUserCount(data.total);
setUserFormat(newPageData);
} else {
showError(message);
}
} finally {
setLoading(false);
}
setLoading(false);
};
// Search users with keyword and group
@@ -100,24 +105,32 @@ export const useUsersData = () => {
}
if (searchKeyword === '' && searchGroup === '') {
// If keyword is blank, load files instead
// If both filters are blank, load users instead
await loadUsers(startIdx, pageSize);
return;
}
setSearching(true);
const res = await API.get(
`/api/user/search?keyword=${searchKeyword}&group=${searchGroup}&p=${startIdx}&page_size=${pageSize}`,
);
const { success, message, data } = res.data;
if (success) {
const newPageData = data.items;
setActivePage(data.page);
setUserCount(data.total);
setUserFormat(newPageData);
} else {
showError(message);
try {
const res = await API.get('/api/user/search', {
params: {
keyword: searchKeyword,
group: searchGroup,
p: startIdx,
page_size: pageSize,
},
});
const { success, message, data } = res.data;
if (success) {
const newPageData = data.items;
setActivePage(data.page);
setUserCount(data.total);
setUserFormat(newPageData);
} else {
showError(message);
}
} finally {
setSearching(false);
}
setSearching(false);
};
// Manage user operations (promote, demote, enable, disable, delete)
@@ -191,12 +204,9 @@ export const useUsersData = () => {
// Handle page change
const handlePageChange = (page) => {
setActivePage(page);
const { searchKeyword, searchGroup } = getFormValues();
if (searchKeyword === '' && searchGroup === '') {
loadUsers(page, pageSize).then();
} else {
searchUsers(page, pageSize, searchKeyword, searchGroup).then();
}
refresh(page).catch((reason) => {
showError(reason);
});
};
// Handle page size change
@@ -204,11 +214,9 @@ export const useUsersData = () => {
localStorage.setItem('page-size', size + '');
setPageSize(size);
setActivePage(1);
loadUsers(activePage, size)
.then()
.catch((reason) => {
showError(reason);
});
await refresh(1, size).catch((reason) => {
showError(reason);
});
};
// Handle table row styling for disabled/deleted users
@@ -225,13 +233,8 @@ export const useUsersData = () => {
};
// Refresh data
const refresh = async (page = activePage) => {
const { searchKeyword, searchGroup } = getFormValues();
if (searchKeyword === '' && searchGroup === '') {
await loadUsers(page, pageSize);
} else {
await searchUsers(page, pageSize, searchKeyword, searchGroup);
}
const refresh = async (page = activePage, size = pageSize) => {
await searchUsers(page, size);
};
// Fetch groups data
+256
View File
@@ -0,0 +1,256 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import test from 'node:test';
import { setImmediate } from 'node:timers/promises';
import { runInNewContext } from 'node:vm';
import axios from 'axios';
import { transformWithEsbuild } from 'vite';
const filename = new URL('./useUsersData.jsx', import.meta.url);
const { code } = await transformWithEsbuild(
await readFile(filename, 'utf8'),
filename.pathname,
{ loader: 'jsx', format: 'cjs', target: 'node22' },
);
const defaultPageSize = 10;
// Execute the real exported hook with state snapshots and mount effects only.
// This controller harness does not model React scheduling, StrictMode, DOM, or HTTP.
async function createHarness() {
const states = [];
const effects = [];
const requests = [];
const errors = [];
const storage = new Map();
let cursor = 0;
let mounting = true;
let respond = (request) => {
if (request.path === '/api/group/') {
return { data: { data: ['default'] } };
}
return {
data: {
success: true,
data: {
page: Number(request.params.p),
total: 1,
items: [{ id: 42, username: 'test-user' }],
},
},
};
};
const modules = {
react: {
useState(initialValue) {
const index = cursor++;
if (mounting) {
states[index] =
typeof initialValue === 'function' ? initialValue() : initialValue;
}
return [
states[index],
(value) => {
states[index] =
typeof value === 'function' ? value(states[index]) : value;
},
];
},
useEffect(effect) {
if (mounting) effects.push(effect);
},
},
'react-i18next': { useTranslation: () => ({ t: (value) => value }) },
'../../helpers': {
API: {
async get(url, config) {
// Use Axios's actual serializer, but never send a network request.
const parsed = new URL(
axios.getUri({ ...config, url }),
'https://example.test',
);
const request = {
path: parsed.pathname,
params: Object.fromEntries(parsed.searchParams),
};
requests.push(request);
return respond(request);
},
},
showError: (error) => errors.push(error),
showSuccess: () => {},
},
'../../constants': { ITEMS_PER_PAGE: defaultPageSize },
'../common/useTableCompactMode': {
useTableCompactMode: () => [false, () => {}],
},
};
const module = { exports: {} };
runInNewContext(code, {
module,
exports: module.exports,
require(name) {
assert.ok(Object.hasOwn(modules, name), `Unexpected import: ${name}`);
return modules[name];
},
localStorage: { setItem: (key, value) => storage.set(key, value) },
});
const render = () => {
cursor = 0;
return module.exports.useUsersData();
};
render();
mounting = false;
effects.forEach((effect) => effect());
await setImmediate();
return {
render,
requests,
errors,
storage,
setResponder(next) {
respond = next;
},
};
}
function assertRequest(request, page, size, filters = {}) {
const keyword = filters.searchKeyword || '';
const group = filters.searchGroup || '';
assert.deepEqual(request, {
path: keyword || group ? '/api/user/search' : '/api/user/',
params: {
...(keyword || group ? { keyword, group } : {}),
p: String(page),
page_size: String(size),
},
});
}
test('mount keeps the initial page-zero fetch and formats returned users', async () => {
const harness = await createHarness();
assertRequest(harness.requests[0], 0, defaultPageSize);
assert.equal(harness.requests[1].path, '/api/group/');
const data = harness.render();
assert.equal(data.loading, false);
assert.equal(data.searching, false);
assert.equal(data.activePage, 0);
assert.equal(data.userCount, 1);
assert.equal(data.users[0].key, 42);
});
for (const [name, filters] of Object.entries({
unfiltered: { searchKeyword: '', searchGroup: '' },
keyword: { searchKeyword: 'alice', searchGroup: '' },
group: { searchKeyword: '', searchGroup: 'staff' },
'both filters with reserved characters': {
searchKeyword: 'alice & bob+#?=user',
searchGroup: 'staff&group=other +#',
},
})) {
test(`page-size change from a later page uses page 1, new size, and live form values: ${name}`, async () => {
const harness = await createHarness();
let values = { searchKeyword: '', searchGroup: '' };
harness.render().setFormApi({ getValues: () => values });
harness.render().handlePageChange(4);
await setImmediate();
assert.equal(harness.render().activePage, 4);
values = filters;
harness.requests.length = 0;
const pending = harness.render().handlePageSizeChange(25);
assert.equal(harness.render().activePage, 1);
assert.equal(harness.render().pageSize, 25);
await pending;
assert.equal(harness.requests.length, 1);
assertRequest(harness.requests[0], 1, 25, filters);
assert.equal(harness.storage.get('page-size'), '25');
assert.equal(harness.render().activePage, 1);
assert.equal(harness.render().loading, false);
assert.equal(harness.render().searching, false);
harness.render().handlePageChange(3);
await setImmediate();
assertRequest(harness.requests[1], 3, 25, filters);
await harness.render().refresh();
assertRequest(harness.requests[2], 3, 25, filters);
});
}
test('form search still reads current filters and supports explicit filters and blank fallback', async () => {
const harness = await createHarness();
let values = { searchKeyword: 'form keyword', searchGroup: 'form group' };
harness.render().setFormApi({ getValues: () => values });
harness.requests.length = 0;
await harness.render().searchUsers(1, 20);
assertRequest(harness.requests[0], 1, 20, values);
await harness.render().searchUsers(2, 20, 'explicit', 'override');
assertRequest(harness.requests[1], 2, 20, {
searchKeyword: 'explicit',
searchGroup: 'override',
});
values = {};
await harness.render().searchUsers(1, 20);
assertRequest(harness.requests[2], 1, 20);
});
for (const action of ['loadUsers', 'searchUsers', 'blank search fallback']) {
test(`${action} clears its pending flag and propagates request rejection`, async () => {
const harness = await createHarness();
const failure = new Error('request rejected');
let rejectRequest;
harness.setResponder(
() => new Promise((resolve, reject) => (rejectRequest = reject)),
);
const data = harness.render();
const pending =
action === 'loadUsers'
? data.loadUsers(2, 10)
: data.searchUsers(2, 10, action === 'searchUsers' ? 'alice' : '', '');
const flag = action === 'searchUsers' ? 'searching' : 'loading';
assert.equal(harness.render()[flag], true);
const rejected = assert.rejects(pending, (error) => error === failure);
rejectRequest(failure);
await rejected;
assert.equal(harness.render().loading, false);
assert.equal(harness.render().searching, false);
});
}
for (const handler of ['handlePageSizeChange', 'handlePageChange']) {
for (const filtered of [false, true]) {
test(`${handler} reports rejected ${filtered ? 'filtered' : 'unfiltered'} requests and clears flags`, async () => {
const harness = await createHarness();
harness.render().setFormApi({
getValues: () => ({ searchKeyword: filtered ? 'alice' : '' }),
});
const failure = new Error('pagination request rejected');
harness.setResponder(() => Promise.reject(failure));
await harness.render()[handler](25);
await setImmediate();
assert.deepEqual(harness.errors, [failure]);
assert.equal(harness.render().loading, false);
assert.equal(harness.render().searching, false);
});
}
}