refactor(shared): 提取公共状态逻辑并修复用户列表分页
统一存储解析、通知已读状态、表格偏好和企业日志筛选参数。修复切换每页条数时沿用旧页码、丢失筛选条件和重复触发分页回调的问题。 同步调整项目检查脚本、格式配置和开发文档。
This commit is contained in:
@@ -110,6 +110,8 @@ const UsersPage = () => {
|
||||
total: usersData.userCount,
|
||||
onPageChange: usersData.handlePageChange,
|
||||
onPageSizeChange: usersData.handlePageSizeChange,
|
||||
// The size handler resets to page 1; skip Semi's automatic page callback.
|
||||
preventPageChangeOnPageSizeChange: true,
|
||||
isMobile: isMobile,
|
||||
t: usersData.t,
|
||||
})}
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
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 { parseStoredObject } from './storageJson.js';
|
||||
|
||||
// Resolve raw localStorage JSON without mutating defaults or performing I/O.
|
||||
export const resolveColumnVisibility = (
|
||||
defaults,
|
||||
savedColumns,
|
||||
hiddenKeys = [],
|
||||
) => {
|
||||
const resolved = { ...defaults };
|
||||
const preferences = parseStoredObject(savedColumns);
|
||||
|
||||
for (const key of Object.keys(defaults)) {
|
||||
if (
|
||||
Object.prototype.hasOwnProperty.call(preferences, key) &&
|
||||
typeof preferences[key] === 'boolean'
|
||||
) {
|
||||
resolved[key] = preferences[key];
|
||||
}
|
||||
}
|
||||
|
||||
// Role restrictions take precedence over saved preferences.
|
||||
for (const key of hiddenKeys) {
|
||||
resolved[key] = false;
|
||||
}
|
||||
|
||||
return resolved;
|
||||
};
|
||||
@@ -0,0 +1,149 @@
|
||||
/*
|
||||
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 test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { resolveColumnVisibility } from './columnVisibility.js';
|
||||
|
||||
const defaults = Object.freeze({ time: true, model: true, channel: false });
|
||||
|
||||
test('missing or malformed saved JSON falls back to a fresh copy of defaults', () => {
|
||||
for (const saved of [
|
||||
undefined,
|
||||
null,
|
||||
'',
|
||||
'{',
|
||||
'not-json',
|
||||
'{"time":false,}',
|
||||
]) {
|
||||
const resolved = resolveColumnVisibility(defaults, saved);
|
||||
assert.deepEqual(resolved, defaults);
|
||||
assert.notStrictEqual(resolved, defaults);
|
||||
}
|
||||
});
|
||||
|
||||
test('null, arrays, and primitive JSON values are not preference maps', () => {
|
||||
for (const saved of [
|
||||
'null',
|
||||
'[]',
|
||||
'[false]',
|
||||
'"text"',
|
||||
'0',
|
||||
'true',
|
||||
'false',
|
||||
]) {
|
||||
assert.deepEqual(resolveColumnVisibility(defaults, saved), defaults);
|
||||
}
|
||||
});
|
||||
|
||||
test('non-string saved data is ignored without coercion or mutation', () => {
|
||||
const saved = Object.freeze({ time: false });
|
||||
for (const value of [saved, [false], 1, true]) {
|
||||
assert.deepEqual(resolveColumnVisibility(defaults, value), defaults);
|
||||
}
|
||||
assert.deepEqual(saved, { time: false });
|
||||
});
|
||||
|
||||
test('saved false and true values override defaults while new columns keep defaults', () => {
|
||||
assert.deepEqual(
|
||||
resolveColumnVisibility(defaults, '{"time":false,"channel":true}'),
|
||||
{ time: false, model: true, channel: true },
|
||||
);
|
||||
assert.deepEqual(resolveColumnVisibility(defaults, '{}'), defaults);
|
||||
});
|
||||
|
||||
test('invalid individual preferences keep defaults without discarding valid booleans', () => {
|
||||
for (const value of [null, 0, 1, '', 'false', [], {}]) {
|
||||
assert.deepEqual(
|
||||
resolveColumnVisibility(
|
||||
defaults,
|
||||
JSON.stringify({ time: value, channel: value, model: false }),
|
||||
),
|
||||
{ time: true, model: false, channel: false },
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('unknown and prototype-related saved keys do not enter the result', () => {
|
||||
const resolved = resolveColumnVisibility(
|
||||
defaults,
|
||||
'{"time":false,"removedColumn":true,"__proto__":{"polluted":true},"constructor":false,"toString":false}',
|
||||
);
|
||||
assert.deepEqual(resolved, { time: false, model: true, channel: false });
|
||||
assert.equal(Object.getPrototypeOf(resolved), Object.prototype);
|
||||
assert.equal(Object.hasOwn(resolved, '__proto__'), false);
|
||||
});
|
||||
|
||||
for (const [table, restrictedKeys] of [
|
||||
['usage logs', ['channel', 'username', 'retry']],
|
||||
['task logs', ['channel']],
|
||||
]) {
|
||||
for (const isAdmin of [true, false]) {
|
||||
test(`${table}: ${isAdmin ? 'admin' : 'non-admin'} preferences respect role restrictions`, () => {
|
||||
const roleDefaults = {
|
||||
model: true,
|
||||
...Object.fromEntries(restrictedKeys.map((key) => [key, isAdmin])),
|
||||
};
|
||||
const hiddenKeys = isAdmin ? [] : restrictedKeys;
|
||||
for (const checked of [true, false]) {
|
||||
const preferences = {
|
||||
model: false,
|
||||
...Object.fromEntries(restrictedKeys.map((key) => [key, checked])),
|
||||
};
|
||||
const resolved = resolveColumnVisibility(
|
||||
roleDefaults,
|
||||
JSON.stringify(preferences),
|
||||
hiddenKeys,
|
||||
);
|
||||
assert.equal(resolved.model, false);
|
||||
for (const key of restrictedKeys) {
|
||||
assert.equal(resolved[key], isAdmin && checked);
|
||||
}
|
||||
}
|
||||
assert.deepEqual(
|
||||
resolveColumnVisibility(roleDefaults, null, hiddenKeys),
|
||||
roleDefaults,
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
test('forced-hidden keys apply even when saved preferences are missing or invalid', () => {
|
||||
for (const saved of [null, '{', 'null', '[]', '{}', '{"time":true}']) {
|
||||
assert.deepEqual(resolveColumnVisibility(defaults, saved, ['time']), {
|
||||
time: false,
|
||||
model: true,
|
||||
channel: false,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test('resolution never mutates defaults or hidden keys and returns independent results', () => {
|
||||
const hiddenKeys = Object.freeze(['channel']);
|
||||
const saved = '{"time":false,"channel":true}';
|
||||
const first = resolveColumnVisibility(defaults, saved, hiddenKeys);
|
||||
const second = resolveColumnVisibility(defaults, saved, hiddenKeys);
|
||||
|
||||
assert.notStrictEqual(first, second);
|
||||
first.model = false;
|
||||
assert.deepEqual(second, { time: false, model: true, channel: false });
|
||||
assert.deepEqual(defaults, { time: true, model: true, channel: false });
|
||||
assert.deepEqual(hiddenKeys, ['channel']);
|
||||
assert.equal(saved, '{"time":false,"channel":true}');
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
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 { parseStoredArray, readStorageValue } from './storageJson.js';
|
||||
|
||||
export const NOTICE_READ_KEYS_KEY = 'notice_read_keys';
|
||||
|
||||
export const getAnnouncementKey = (announcement) =>
|
||||
`${announcement?.publishDate || ''}-${(announcement?.content || '').slice(0, 30)}`;
|
||||
|
||||
export function getUnreadAnnouncementKeys(announcements, readKeys) {
|
||||
const readSet = new Set(readKeys);
|
||||
return announcements
|
||||
.map(getAnnouncementKey)
|
||||
.filter((key) => !readSet.has(key));
|
||||
}
|
||||
|
||||
export function mergeAnnouncementReadKeys(announcements, readKeys) {
|
||||
return Array.from(
|
||||
new Set([...readKeys, ...announcements.map(getAnnouncementKey)]),
|
||||
);
|
||||
}
|
||||
|
||||
export function readNoticeReadKeys() {
|
||||
return parseStoredArray(readStorageValue(NOTICE_READ_KEYS_KEY));
|
||||
}
|
||||
|
||||
export function markAnnouncementsRead(announcements) {
|
||||
const mergedKeys = mergeAnnouncementReadKeys(
|
||||
announcements,
|
||||
readNoticeReadKeys(),
|
||||
);
|
||||
// Let write failures propagate so callers do not report unread items as saved.
|
||||
localStorage.setItem(NOTICE_READ_KEYS_KEY, JSON.stringify(mergedKeys));
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
/** Map the shared consumption filters without adding endpoint-specific options. */
|
||||
export function buildOrgLogFilters({
|
||||
userId,
|
||||
startTimestamp,
|
||||
endTimestamp,
|
||||
modelName,
|
||||
} = {}) {
|
||||
const params = {};
|
||||
// Preserve the API callers' existing omission of empty values (including zero).
|
||||
if (userId) params.user_id = userId;
|
||||
if (startTimestamp) params.start_timestamp = startTimestamp;
|
||||
if (endTimestamp) params.end_timestamp = endTimestamp;
|
||||
if (modelName) params.model_name = modelName;
|
||||
return params;
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
/*
|
||||
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 test from 'node:test';
|
||||
import { buildOrgLogFilters } from './orgLogFilters.js';
|
||||
|
||||
test('consumption filters map to the existing API field names', () => {
|
||||
const filters = Object.freeze({
|
||||
userId: 42,
|
||||
startTimestamp: 1700000000,
|
||||
endTimestamp: 1700003600,
|
||||
modelName: 'example/model + preview',
|
||||
});
|
||||
assert.deepEqual(buildOrgLogFilters(filters), {
|
||||
user_id: 42,
|
||||
start_timestamp: 1700000000,
|
||||
end_timestamp: 1700003600,
|
||||
model_name: 'example/model + preview',
|
||||
});
|
||||
});
|
||||
|
||||
test('empty filters and existing falsy values are omitted', () => {
|
||||
assert.deepEqual(buildOrgLogFilters(), {});
|
||||
for (const value of [undefined, null, '', 0, false, NaN]) {
|
||||
assert.deepEqual(
|
||||
buildOrgLogFilters({
|
||||
userId: value,
|
||||
startTimestamp: value,
|
||||
endTimestamp: value,
|
||||
modelName: value,
|
||||
}),
|
||||
{},
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('partial filters preserve values without coercion', () => {
|
||||
assert.deepEqual(buildOrgLogFilters({ userId: '0', modelName: 'a&b' }), {
|
||||
user_id: '0',
|
||||
model_name: 'a&b',
|
||||
});
|
||||
});
|
||||
|
||||
test('endpoint-specific parameters cannot leak into shared filters', () => {
|
||||
const filters = Object.freeze({
|
||||
userId: 42,
|
||||
limit: 10,
|
||||
nocache: 1,
|
||||
p: 5,
|
||||
page_size: 20,
|
||||
memberId: 7,
|
||||
});
|
||||
const params = buildOrgLogFilters(filters);
|
||||
assert.deepEqual(params, { user_id: 42 });
|
||||
params.limit = 15;
|
||||
assert.deepEqual(buildOrgLogFilters(filters), { user_id: 42 });
|
||||
assert.equal(filters.limit, 10);
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
function parseStoredJson(json, isValid, fallback) {
|
||||
if (typeof json !== 'string') return fallback;
|
||||
try {
|
||||
const value = JSON.parse(json);
|
||||
return isValid(value) ? value : fallback;
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
export function parseStoredArray(json) {
|
||||
return parseStoredJson(json, Array.isArray, []);
|
||||
}
|
||||
|
||||
export function parseStoredObject(json) {
|
||||
return parseStoredJson(
|
||||
json,
|
||||
(value) =>
|
||||
value !== null && typeof value === 'object' && !Array.isArray(value),
|
||||
{},
|
||||
);
|
||||
}
|
||||
|
||||
export function readStorageValue(key) {
|
||||
try {
|
||||
return localStorage.getItem(key);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
/*
|
||||
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 test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
parseStoredArray,
|
||||
parseStoredObject,
|
||||
readStorageValue,
|
||||
} from './storageJson.js';
|
||||
|
||||
import {
|
||||
getAnnouncementKey,
|
||||
getUnreadAnnouncementKeys,
|
||||
markAnnouncementsRead,
|
||||
mergeAnnouncementReadKeys,
|
||||
NOTICE_READ_KEYS_KEY,
|
||||
readNoticeReadKeys,
|
||||
} from './notificationReadState.js';
|
||||
import {
|
||||
getTableCompactMode,
|
||||
parseTableCompactMode,
|
||||
setTableCompactMode,
|
||||
} from './tableCompactMode.js';
|
||||
import { TABLE_COMPACT_MODES_KEY } from '../constants/common.constant.js';
|
||||
|
||||
function mockStorage(t, storage) {
|
||||
const descriptor = Object.getOwnPropertyDescriptor(
|
||||
globalThis,
|
||||
'localStorage',
|
||||
);
|
||||
Object.defineProperty(globalThis, 'localStorage', {
|
||||
configurable: true,
|
||||
value: storage,
|
||||
});
|
||||
t.after(() => {
|
||||
if (descriptor) {
|
||||
Object.defineProperty(globalThis, 'localStorage', descriptor);
|
||||
} else {
|
||||
delete globalThis.localStorage;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const invalidJson = [
|
||||
null,
|
||||
undefined,
|
||||
'',
|
||||
'{broken',
|
||||
'null',
|
||||
'true',
|
||||
'42',
|
||||
'"text"',
|
||||
];
|
||||
|
||||
test('stored arrays reject malformed JSON and non-array values', () => {
|
||||
for (const json of [...invalidJson, '{}', '{"0":"notice"}']) {
|
||||
assert.deepEqual(parseStoredArray(json), [], String(json));
|
||||
}
|
||||
});
|
||||
|
||||
test('stored objects reject malformed JSON and non-object values', () => {
|
||||
for (const json of [...invalidJson, '[]', '[true]']) {
|
||||
assert.deepEqual(parseStoredObject(json), {}, String(json));
|
||||
}
|
||||
});
|
||||
|
||||
test('valid stored containers keep their values without coercion or filtering', () => {
|
||||
const array = ['notice', 'notice', null, 1];
|
||||
const object = { global: true, tokens: false, other: 'yes' };
|
||||
assert.deepEqual(parseStoredArray(JSON.stringify(array)), array);
|
||||
assert.deepEqual(parseStoredObject(JSON.stringify(object)), object);
|
||||
});
|
||||
|
||||
test('fallback containers are fresh for each parse', () => {
|
||||
const array = parseStoredArray(null);
|
||||
const object = parseStoredObject(null);
|
||||
array.push('notice');
|
||||
object.global = true;
|
||||
assert.deepEqual(parseStoredArray(null), []);
|
||||
assert.deepEqual(parseStoredObject(null), {});
|
||||
});
|
||||
|
||||
test('storage reads return the original stored value', (t) => {
|
||||
mockStorage(t, {
|
||||
getItem(key) {
|
||||
assert.equal(key, 'preference');
|
||||
return 'stored';
|
||||
},
|
||||
});
|
||||
assert.equal(readStorageValue('preference'), 'stored');
|
||||
});
|
||||
|
||||
test('storage read failures fall back to null', (t) => {
|
||||
mockStorage(t, {
|
||||
getItem() {
|
||||
throw new Error('Storage blocked');
|
||||
},
|
||||
});
|
||||
assert.equal(readStorageValue('preference'), null);
|
||||
assert.deepEqual(readNoticeReadKeys(), []);
|
||||
assert.equal(getTableCompactMode(), false);
|
||||
});
|
||||
|
||||
test('announcement identity keeps the date and first 30 content characters', () => {
|
||||
assert.equal(
|
||||
getAnnouncementKey({ publishDate: '2025-01-01', content: 'a'.repeat(40) }),
|
||||
`2025-01-01-${'a'.repeat(30)}`,
|
||||
);
|
||||
assert.equal(getAnnouncementKey({}), '-');
|
||||
assert.equal(getAnnouncementKey(null), '-');
|
||||
});
|
||||
|
||||
const first = { publishDate: '2025-01-01', content: 'First' };
|
||||
const second = { publishDate: '2025-01-02', content: 'Second' };
|
||||
|
||||
test('unread keys preserve announcement order and duplicate counts', () => {
|
||||
const notices = [first, second, second];
|
||||
const readKeys = [getAnnouncementKey(first)];
|
||||
assert.deepEqual(getUnreadAnnouncementKeys(notices, readKeys), [
|
||||
getAnnouncementKey(second),
|
||||
getAnnouncementKey(second),
|
||||
]);
|
||||
assert.deepEqual(
|
||||
getUnreadAnnouncementKeys(notices, []),
|
||||
notices.map(getAnnouncementKey),
|
||||
);
|
||||
assert.deepEqual(
|
||||
getUnreadAnnouncementKeys(notices, notices.map(getAnnouncementKey)),
|
||||
[],
|
||||
);
|
||||
assert.deepEqual(getUnreadAnnouncementKeys([], readKeys), []);
|
||||
});
|
||||
|
||||
test('merging read keys retains history, deduplicates, and does not mutate inputs', () => {
|
||||
const notices = [first, second, first];
|
||||
const readKeys = ['old', getAnnouncementKey(first), 'old'];
|
||||
assert.deepEqual(mergeAnnouncementReadKeys(notices, readKeys), [
|
||||
'old',
|
||||
getAnnouncementKey(first),
|
||||
getAnnouncementKey(second),
|
||||
]);
|
||||
assert.deepEqual(readKeys, ['old', getAnnouncementKey(first), 'old']);
|
||||
assert.deepEqual(notices, [first, second, first]);
|
||||
});
|
||||
|
||||
test('notification persistence uses the existing key and merges the latest stored history', (t) => {
|
||||
let stored = '["old"]';
|
||||
mockStorage(t, {
|
||||
getItem(key) {
|
||||
assert.equal(key, 'notice_read_keys');
|
||||
return stored;
|
||||
},
|
||||
setItem(key, value) {
|
||||
assert.equal(key, NOTICE_READ_KEYS_KEY);
|
||||
stored = value;
|
||||
},
|
||||
});
|
||||
markAnnouncementsRead([first, first]);
|
||||
assert.deepEqual(JSON.parse(stored), ['old', getAnnouncementKey(first)]);
|
||||
stored = JSON.stringify([...JSON.parse(stored), 'another-tab']);
|
||||
markAnnouncementsRead([second]);
|
||||
assert.deepEqual(JSON.parse(stored), [
|
||||
'old',
|
||||
getAnnouncementKey(first),
|
||||
'another-tab',
|
||||
getAnnouncementKey(second),
|
||||
]);
|
||||
});
|
||||
|
||||
test('invalid notice storage is treated as unread and can be repaired on write', (t) => {
|
||||
let stored;
|
||||
mockStorage(t, {
|
||||
getItem: () => stored,
|
||||
setItem: (_key, value) => {
|
||||
stored = value;
|
||||
},
|
||||
});
|
||||
for (const json of [...invalidJson, '{}']) {
|
||||
stored = json;
|
||||
assert.deepEqual(readNoticeReadKeys(), []);
|
||||
assert.deepEqual(getUnreadAnnouncementKeys([first], readNoticeReadKeys()), [
|
||||
getAnnouncementKey(first),
|
||||
]);
|
||||
markAnnouncementsRead([first]);
|
||||
assert.deepEqual(JSON.parse(stored), [getAnnouncementKey(first)]);
|
||||
}
|
||||
});
|
||||
|
||||
test('notification write failures propagate instead of reporting a saved read state', (t) => {
|
||||
const failure = new Error('Quota exceeded');
|
||||
mockStorage(t, {
|
||||
getItem: () => '[]',
|
||||
setItem() {
|
||||
throw failure;
|
||||
},
|
||||
});
|
||||
assert.throws(
|
||||
() => markAnnouncementsRead([first]),
|
||||
(error) => error === failure,
|
||||
);
|
||||
});
|
||||
|
||||
test('compact parsing preserves global defaults, per-table selection and truthiness', () => {
|
||||
const json = '{"global":true,"tokens":false,"channels":"enabled","logs":0}';
|
||||
assert.equal(parseTableCompactMode(json), true);
|
||||
assert.equal(parseTableCompactMode(json, 'tokens'), false);
|
||||
assert.equal(parseTableCompactMode(json, 'channels'), true);
|
||||
assert.equal(parseTableCompactMode(json, 'logs'), false);
|
||||
assert.equal(parseTableCompactMode(json, 'missing'), false);
|
||||
});
|
||||
|
||||
test('compact storage-event payloads use the same fallback as initial reads', (t) => {
|
||||
let stored;
|
||||
mockStorage(t, { getItem: () => stored });
|
||||
for (const json of [...invalidJson, '[]', '[true]', '{"global":true}']) {
|
||||
stored = json;
|
||||
assert.equal(parseTableCompactMode(json), getTableCompactMode());
|
||||
}
|
||||
assert.equal(parseTableCompactMode(null), false);
|
||||
});
|
||||
|
||||
test('compact writes preserve other table preferences and the storage key', (t) => {
|
||||
let stored = '{"channels":true,"tokens":false}';
|
||||
mockStorage(t, {
|
||||
getItem(key) {
|
||||
assert.equal(key, 'table_compact_modes');
|
||||
return stored;
|
||||
},
|
||||
setItem(key, value) {
|
||||
assert.equal(key, TABLE_COMPACT_MODES_KEY);
|
||||
stored = value;
|
||||
},
|
||||
});
|
||||
assert.equal(setTableCompactMode(true), undefined);
|
||||
setTableCompactMode(true, 'tokens');
|
||||
assert.deepEqual(JSON.parse(stored), {
|
||||
channels: true,
|
||||
tokens: true,
|
||||
global: true,
|
||||
});
|
||||
setTableCompactMode(false, 'channels');
|
||||
assert.equal(getTableCompactMode('channels'), false);
|
||||
});
|
||||
|
||||
test('invalid compact preferences can be replaced by a valid object on write', (t) => {
|
||||
let stored;
|
||||
mockStorage(t, {
|
||||
getItem: () => stored,
|
||||
setItem: (_key, value) => {
|
||||
stored = value;
|
||||
},
|
||||
});
|
||||
for (const json of [...invalidJson, '[]', '[true]']) {
|
||||
stored = json;
|
||||
assert.equal(getTableCompactMode(), false);
|
||||
setTableCompactMode(true);
|
||||
assert.deepEqual(JSON.parse(stored), { global: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('compact write failures remain non-fatal', (t) => {
|
||||
mockStorage(t, {
|
||||
getItem: () => '{}',
|
||||
setItem() {
|
||||
throw new Error('Quota exceeded');
|
||||
},
|
||||
});
|
||||
assert.doesNotThrow(() => setTableCompactMode(true));
|
||||
});
|
||||
|
||||
test('blocked storage access is guarded for reads and compact writes but not notice writes', (t) => {
|
||||
mockStorage(t, undefined);
|
||||
Object.defineProperty(globalThis, 'localStorage', {
|
||||
configurable: true,
|
||||
get() {
|
||||
throw new Error('Storage blocked');
|
||||
},
|
||||
});
|
||||
assert.deepEqual(readNoticeReadKeys(), []);
|
||||
assert.equal(getTableCompactMode(), false);
|
||||
assert.doesNotThrow(() => setTableCompactMode(true));
|
||||
assert.throws(() => markAnnouncementsRead([first]), /Storage blocked/);
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
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 { TABLE_COMPACT_MODES_KEY } from '../constants/common.constant.js';
|
||||
import { parseStoredObject, readStorageValue } from './storageJson.js';
|
||||
|
||||
export function parseTableCompactMode(json, tableKey = 'global') {
|
||||
const modes = parseStoredObject(json);
|
||||
return !!modes[tableKey];
|
||||
}
|
||||
|
||||
export function getTableCompactMode(tableKey = 'global') {
|
||||
return parseTableCompactMode(
|
||||
readStorageValue(TABLE_COMPACT_MODES_KEY),
|
||||
tableKey,
|
||||
);
|
||||
}
|
||||
|
||||
export function setTableCompactMode(compact, tableKey = 'global') {
|
||||
const modes = parseStoredObject(readStorageValue(TABLE_COMPACT_MODES_KEY));
|
||||
modes[tableKey] = compact;
|
||||
try {
|
||||
localStorage.setItem(TABLE_COMPACT_MODES_KEY, JSON.stringify(modes));
|
||||
} catch {
|
||||
// Compact mode remains usable in memory when preferences cannot be saved.
|
||||
}
|
||||
}
|
||||
+6
-28
@@ -26,7 +26,6 @@ import {
|
||||
THINK_TAG_REGEX,
|
||||
MESSAGE_ROLES,
|
||||
} from '../constants/playground.constants';
|
||||
import { TABLE_COMPACT_MODES_KEY } from '../constants';
|
||||
import { MOBILE_BREAKPOINT } from '../hooks/common/useIsMobile';
|
||||
// 官方价折扣计算(纯函数):管理端与市场页共用
|
||||
import { buildOfficialComparison, formatDiscountLabel } from './officialPrice';
|
||||
@@ -735,33 +734,10 @@ export const formatDateTimeString = (date) => {
|
||||
return `${year}-${month}-${day} ${hours}:${minutes}`;
|
||||
};
|
||||
|
||||
function readTableCompactModes() {
|
||||
try {
|
||||
const json = localStorage.getItem(TABLE_COMPACT_MODES_KEY);
|
||||
return json ? JSON.parse(json) : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function writeTableCompactModes(modes) {
|
||||
try {
|
||||
localStorage.setItem(TABLE_COMPACT_MODES_KEY, JSON.stringify(modes));
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
export function getTableCompactMode(tableKey = 'global') {
|
||||
const modes = readTableCompactModes();
|
||||
return !!modes[tableKey];
|
||||
}
|
||||
|
||||
export function setTableCompactMode(compact, tableKey = 'global') {
|
||||
const modes = readTableCompactModes();
|
||||
modes[tableKey] = compact;
|
||||
writeTableCompactModes(modes);
|
||||
}
|
||||
export {
|
||||
getTableCompactMode,
|
||||
setTableCompactMode,
|
||||
} from './tableCompactMode.js';
|
||||
|
||||
// -------------------------------
|
||||
// Select 组件统一过滤逻辑
|
||||
@@ -1111,6 +1087,7 @@ export const createCardProPagination = ({
|
||||
isMobile = false,
|
||||
pageSizeOpts = [10, 20, 50, 100],
|
||||
showSizeChanger = true,
|
||||
preventPageChangeOnPageSizeChange = false,
|
||||
t = (key) => key,
|
||||
}) => {
|
||||
if (!total || total <= 0) return null;
|
||||
@@ -1140,6 +1117,7 @@ export const createCardProPagination = ({
|
||||
showSizeChanger={showSizeChanger}
|
||||
onPageSizeChange={onPageSizeChange}
|
||||
onPageChange={onPageChange}
|
||||
preventPageChangeOnPageSizeChange={preventPageChangeOnPageSizeChange}
|
||||
size={isMobile ? 'small' : 'default'}
|
||||
showQuickJumper={isMobile}
|
||||
showTotal
|
||||
|
||||
@@ -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);
|
||||
};
|
||||
|
||||
@@ -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
@@ -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;
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user