阶段七:完成React feature依赖门禁与旧入口瘦身

This commit is contained in:
Christ committed 2026-08-15 02:31:07 +08:00
1 parent 448713735f
commit 22656c20f1
30 files changed
+1485 -1511

No files matched your search

+1 -1
View File
@@ -11,7 +11,7 @@ import Notifications from './components/Notifications';
import Chat from './components/Chat';
import { readSidebarCollapsed, writeSidebarCollapsed } from './components/sidebarState';
import { YdisksBrandIcon } from './components/YdisksLogo';
import { initializeAdmin, login, logout, verifySession } from './services/api';
import { initializeAdmin, login, logout, verifySession } from './app/features/session/api';
import { ShieldCheck, ArrowRight, Loader2, User, Lock } from 'lucide-react';
interface DeliveryRuleTarget {
@@ -1,7 +1,8 @@
import { describe, expect, test } from 'vitest';
import type { AccountDetail } from '../types';
import { mergeAccountRuntimeStatuses } from './accountRuntimeState';
import type { AccountDetail } from '../../../types';
import { mergeAccountRuntimeStatuses } from './runtime';
// account 创建运行状态测试使用的最小账号对象。
const account = (overrides: Partial<AccountDetail> = {}): AccountDetail => ({
id: 'account-1',
cookie: 'cookie',
@@ -10,15 +11,14 @@ const account = (overrides: Partial<AccountDetail> = {}): AccountDetail => ({
...overrides,
});
describe('mergeAccountRuntimeStatuses', () => {
test('用最新在线状态替换风控恢复中的旧提示', () => {
const result = mergeAccountRuntimeStatuses([
account({
runtime_state: 'connecting',
runtime_message: 'token 风控验证已处理,正在重新获取登录凭证',
runtime_updated_at: '2026-07-13T13:16:00+08:00',
}),
], {
describe('Accounts runtime state', () => {
test('最新在线状态替换风控恢复中的旧提示', () => {
// result 是合并当前运行状态后的账号列表。
const result = mergeAccountRuntimeStatuses([account({
runtime_state: 'connecting',
runtime_message: 'token 风控验证已处理,正在重新获取登录凭证',
runtime_updated_at: '2026-07-13T13:16:00+08:00',
})], {
'account-1': {
state: 'online',
message: '消息服务连接正常',
@@ -28,15 +28,11 @@ describe('mergeAccountRuntimeStatuses', () => {
},
});
expect(result[0]).toMatchObject({
runtime_state: 'online',
runtime_message: '消息服务连接正常',
runtime_connected: true,
runtime_updated_at: '2026-07-13T13:16:02+08:00',
});
expect(result[0]).toMatchObject({ runtime_state: 'online', runtime_message: '消息服务连接正常', runtime_connected: true });
});
test('忽略晚到达的旧状态响应', () => {
test('晚到达的旧状态响应不会覆盖当前账号状态', () => {
// current 是当前页面已经展示的较新账号状态。
const current = account({
runtime_state: 'online',
runtime_message: '消息服务连接正常',
@@ -55,7 +51,8 @@ describe('mergeAccountRuntimeStatuses', () => {
expect(result[0]).toBe(current);
});
test('缺少对应运行时状态时保留账号对象', () => {
test('缺少对应运行状态时保留原账号对象', () => {
// current 是没有新运行状态可合并的账号对象。
const current = account();
expect(mergeAccountRuntimeStatuses([current], {})[0]).toBe(current);
});
@@ -80,3 +80,62 @@ test('密码登录风控和失败状态统一转换且不暴露验证链接',
qrCodeUrl: '',
});
});
test('登录字段更新不会用空白密码覆盖已有凭证',
// 账号或浏览器开关变化时只提交真正变化的非敏感字段。
() => {
expect(buildAccountLoginInfoUpdate(account({ username: 'old-user', show_browser: true }), {
username: 'new-user',
login_password: '',
show_browser: false,
})).toEqual({ username: 'new-user', show_browser: false });
});
test('登录字段更新只在用户输入新密码时提交密码',
// 用户输入新密码后才允许将密码字段写入设置补丁。
() => {
expect(buildAccountLoginInfoUpdate(account(), {
username: 'old-user',
login_password: 'new-secret',
show_browser: false,
})).toEqual({ username: 'old-user', login_password: 'new-secret', show_browser: false });
});
test('登录字段没有变化时不生成更新补丁',
// 没有任何登录字段变化时避免发起无意义的设置请求。
() => {
expect(buildAccountLoginInfoUpdate(account(), {
username: 'old-user',
login_password: '',
show_browser: false,
})).toBeNull();
});
test('登录字段支持明确清空密码',
// 清空密码必须由用户显式勾选,不能由空白输入隐式触发。
() => {
expect(buildAccountLoginInfoUpdate(account(), {
username: 'old-user',
login_password: '',
show_browser: false,
clear_password: true,
})).toEqual({ username: 'old-user', show_browser: false, clear_password: true });
});
test('明确清空密码优先于同时输入的新密码',
// 同时存在清空和输入时遵循显式清空意图,避免写入新密码。
() => {
expect(buildAccountLoginInfoUpdate(account(), {
username: 'old-user',
login_password: 'new-secret',
show_browser: false,
clear_password: true,
})).toEqual({ username: 'old-user', show_browser: false, clear_password: true });
});
test('暂停时长相同不会重新启动账号暂停',
// 暂停时长没有变化时保持当前状态,避免重复写入暂停记录。
() => {
expect(shouldUpdateAccountPause(60, { pause_duration: 60, paused: false })).toBe(false);
expect(shouldUpdateAccountPause(60, { pause_duration: 60, paused: true })).toBe(false);
});
@@ -32,3 +32,9 @@ test('追加目标切换后拒绝旧请求响应和旧代次响应',
expect(isCurrentCardRequest(2, 3, '2', '2')).toBe(false);
expect(isCurrentCardRequest(3, 3, '2', '3')).toBe(false);
});
test('卡密筛选忽略名称周围空白并支持大小写无关匹配',
// 用户输入的名称关键字会先裁剪空白,再进行不区分大小写的匹配。
() => {
expect(filterCards(cards, '', ' ppt ')).toEqual([cards[0], cards[2]]);
});
@@ -0,0 +1,50 @@
import { expect, test } from 'vitest';
import type { AutomationRunIssue } from './api';
import { canResolveAutomationIssue, filterAutomationIssues, loadAutomationPageData } from './issueState';
// issue 创建规则异常测试使用的最小异常对象。
const issue = (cookieID: string, allowed: AutomationRunIssue['allowed_resolutions']): AutomationRunIssue => ({
id: cookieID === 'a' ? 1 : 2,
cookie_id: cookieID,
order_id: 'o',
trigger_type: 'buyer_reviewed',
error_message: 'error',
issue_kind: 'invalid_snapshot',
allowed_resolutions: allowed,
action_cursor: 0,
sent_count: 0,
updated_at: '',
});
test('规则异常处理动作遵循后端允许列表',
// 只有后端明确允许的人工动作才能被页面提交。
() => {
const invalid = issue('a', ['cancel']);
expect(canResolveAutomationIssue(invalid, 'cancel')).toBe(true);
expect(canResolveAutomationIssue(invalid, 'continue')).toBe(false);
expect(canResolveAutomationIssue(invalid, 'retry')).toBe(false);
});
test('规则异常按账号筛选后再决定是否展示面板',
// 异常面板只展示当前账号的运行异常和延迟任务。
() => {
const visible = filterAutomationIssues({ runs: [issue('a', ['cancel']), issue('b', ['retry', 'cancel'])], pending_tasks: [] }, 'missing');
expect(visible.runs).toEqual([]);
expect(visible.pending_tasks).toEqual([]);
});
test('规则列表不因异常接口失败而停止加载', async () => {
// receivedRules 保存主规则列表加载器收到的结果。
const receivedRules: string[][] = [];
// errors 保存异常接口失败后的错误回调。
const errors: unknown[] = [];
await loadAutomationPageData({
loadRules: async () => ['rule'],
loadIssues: async () => { throw new Error('issues unavailable'); },
onRules: rules => receivedRules.push(rules),
onIssues: () => { throw new Error('must not receive issues'); },
onIssuesError: error => errors.push(error),
});
expect(receivedRules).toEqual([['rule']]);
expect(errors).toHaveLength(1);
});
+2
View File
@@ -0,0 +1,2 @@
// Session feature 只通过本适配层访问会话相关网络接口。
export { initializeAdmin, login, logout, verifySession } from '../../../services/api';
+3
View File
@@ -0,0 +1,3 @@
// System feature 只通过本适配层访问服务健康检查接口。
export { getHealth } from '../../../services/api';
export type { BuildInfo } from './types';
+7
View File
@@ -0,0 +1,7 @@
// BuildInfo 描述健康检查接口返回的构建版本信息。
export interface BuildInfo {
// version 是当前服务构建版本。
version: string;
// commit 是当前服务对应的提交标识。
commit: string;
}
+5 -7
View File
@@ -4,7 +4,10 @@ import {
GitCommitHorizontal, LogOut, MessageCircleMore, Settings, ShoppingBag, Users, Zap,
} from 'lucide-react';
import { YdisksBrandIcon } from './YdisksLogo';
import { getHealth } from '../app/features/system/api';
import type { BuildInfo } from '../app/features/system/types';
// SidebarProps 描述侧边栏所需的导航和会话回调。
interface SidebarProps {
activeTab: string;
isAdmin?: boolean;
@@ -14,20 +17,15 @@ interface SidebarProps {
onLogout: () => void;
}
interface BuildInfo {
version: string;
commit: string;
}
const Sidebar: React.FC<SidebarProps> = ({
activeTab, isAdmin = false, collapsed, onToggleCollapsed, onNavigate, onLogout,
}) => {
const [buildInfo, setBuildInfo] = useState<BuildInfo>({ version: 'dev', commit: 'unknown' });
useEffect(() => {
// controller 控制健康检查请求的取消。
const controller = new AbortController();
fetch('/health', { signal: controller.signal })
.then(response => response.ok ? response.json() : Promise.reject(new Error('health request failed')))
getHealth({ signal: controller.signal })
.then(data => setBuildInfo({
version: String(data.version || 'dev'),
commit: String(data.commit || 'unknown'),
-62
View File
@@ -1,62 +0,0 @@
import { expect, test } from 'vitest';
import { buildAccountLoginInfoUpdate } from './accountEdit';
test('buildAccountLoginInfoUpdate omits blank password while updating other login fields', () => {
const payload = buildAccountLoginInfoUpdate(
{ id: 'acc1', enabled: true, auto_confirm: true, username: 'old-user', show_browser: true },
{ username: 'new-user', login_password: '', show_browser: false },
);
expect(payload).toEqual({
username: 'new-user',
show_browser: false,
});
});
test('buildAccountLoginInfoUpdate includes password only when user entered one', () => {
const payload = buildAccountLoginInfoUpdate(
{ id: 'acc1', enabled: true, auto_confirm: true, username: 'old-user', show_browser: false },
{ username: 'old-user', login_password: 'new-secret', show_browser: false },
);
expect(payload).toEqual({
username: 'old-user',
login_password: 'new-secret',
show_browser: false,
});
});
test('buildAccountLoginInfoUpdate skips unchanged login info', () => {
const payload = buildAccountLoginInfoUpdate(
{ id: 'acc1', enabled: true, auto_confirm: true, username: 'old-user', show_browser: false },
{ username: 'old-user', login_password: '', show_browser: false },
);
expect(payload).toBeNull();
});
test('buildAccountLoginInfoUpdate sends explicit clear password flag', () => {
const payload = buildAccountLoginInfoUpdate(
{ id: 'acc1', enabled: true, auto_confirm: true, username: 'old-user', show_browser: false },
{ username: 'old-user', login_password: '', show_browser: false, clear_password: true },
);
expect(payload).toEqual({
username: 'old-user',
show_browser: false,
clear_password: true,
});
});
test('buildAccountLoginInfoUpdate prefers clear password over typed password', () => {
const payload = buildAccountLoginInfoUpdate(
{ id: 'acc1', enabled: true, auto_confirm: true, username: 'old-user', show_browser: false },
{ username: 'old-user', login_password: 'new-secret', show_browser: false, clear_password: true },
);
expect(payload).toEqual({
username: 'old-user',
show_browser: false,
clear_password: true,
});
});
-8
View File
@@ -1,8 +0,0 @@
// 旧目录保留兼容入口,实际登录字段构造逻辑已归入 accounts feature。
export {
buildAccountLoginInfoUpdate,
} from '../app/features/accounts/state';
export type {
AccountLoginEditFields as AccountLoginEditForm,
AccountLoginInfoPayload,
} from '../app/features/accounts/state';
-17
View File
@@ -1,17 +0,0 @@
import { describe, expect, it } from 'vitest';
import { shouldUpdateAccountPause } from './accountPause';
describe('shouldUpdateAccountPause', () => {
it('does not silently reapply the same duration after a pause has expired', () => {
expect(shouldUpdateAccountPause(60, { pause_duration: 60, paused: false })).toBe(false);
});
it('does not restart an active unchanged pause', () => {
expect(shouldUpdateAccountPause(60, { pause_duration: 60, paused: true })).toBe(false);
});
it('sends changed values including explicit resume', () => {
expect(shouldUpdateAccountPause(30, { pause_duration: 60, paused: true })).toBe(true);
expect(shouldUpdateAccountPause(0, { pause_duration: 60, paused: true })).toBe(true);
});
});
-2
View File
@@ -1,2 +0,0 @@
// 旧目录保留兼容入口,实际暂停时长门禁已归入 accounts feature。
export { shouldUpdateAccountPause } from '../app/features/accounts/state';
@@ -1,2 +0,0 @@
// 旧目录保留兼容入口,实际运行状态合并逻辑已归入 accounts feature。
export { mergeAccountRuntimeStatuses } from '../app/features/accounts/runtime';
@@ -1,43 +0,0 @@
import { expect, test } from 'vitest';
import type { AutomationRunIssue } from '../services/api';
import { canResolveAutomationIssue, filterAutomationIssues, loadAutomationPageData } from './automationIssueState';
const issue = (cookieID: string, allowed: AutomationRunIssue['allowed_resolutions']): AutomationRunIssue => ({
id: cookieID === 'a' ? 1 : 2,
cookie_id: cookieID,
order_id: 'o',
trigger_type: 'buyer_reviewed',
error_message: 'error',
issue_kind: 'invalid_snapshot',
allowed_resolutions: allowed,
action_cursor: 0,
sent_count: 0,
updated_at: '',
});
test('automation issue actions follow the backend policy', () => {
const invalid = issue('a', ['cancel']);
expect(canResolveAutomationIssue(invalid, 'cancel')).toBe(true);
expect(canResolveAutomationIssue(invalid, 'continue')).toBe(false);
expect(canResolveAutomationIssue(invalid, 'retry')).toBe(false);
});
test('automation issues are filtered before deciding whether to show the panel', () => {
const visible = filterAutomationIssues({ runs: [issue('a', ['cancel']), issue('b', ['retry', 'cancel'])], pending_tasks: [] }, 'missing');
expect(visible.runs).toEqual([]);
expect(visible.pending_tasks).toEqual([]);
});
test('automation rules still load when the diagnostic issue request fails', async () => {
const receivedRules: string[][] = [];
const errors: unknown[] = [];
await loadAutomationPageData({
loadRules: async () => ['rule'],
loadIssues: async () => { throw new Error('issues unavailable'); },
onRules: rules => receivedRules.push(rules),
onIssues: () => { throw new Error('must not receive issues'); },
onIssuesError: error => errors.push(error),
});
expect(receivedRules).toEqual([['rule']]);
expect(errors).toHaveLength(1);
});
@@ -1,8 +0,0 @@
// 旧目录保留兼容入口,实际实现统一归属 Rules feature。
export {
automationIssueKindLabel,
canResolveAutomationIssue,
filterAutomationIssues,
loadAutomationPageData,
} from '../app/features/rules/issueState';
export type { AutomationResolution } from '../app/features/rules/issueState';
-19
View File
@@ -1,19 +0,0 @@
import { describe, expect, test } from 'vitest';
import type { Card } from '../types';
import { filterCards } from './cardListState';
const cards = [
{ id: 1, name: '年终总结 PPT', type: 'text' },
{ id: 2, name: '年终总结兑换码', type: 'data' },
{ id: 3, name: '产品介绍 PPT', type: 'text' },
] as Card[];
describe('filterCards', () => {
test('combines type and name filters with AND semantics', () => {
expect(filterCards(cards, 'text', '年终')).toEqual([cards[0]]);
});
test('matches names case-insensitively and ignores surrounding whitespace', () => {
expect(filterCards(cards, '', ' ppt ')).toEqual([cards[0], cards[2]]);
});
});
-7
View File
@@ -1,7 +0,0 @@
// 旧目录保留兼容入口,实际卡密筛选和批量状态逻辑已归入 cards feature。
export {
canSubmitAppend,
filterCards,
isCurrentCardRequest,
previewAppendContent,
} from '../app/features/cards/batchState';
@@ -1,10 +0,0 @@
import { expect, test } from 'vitest';
import { selectActivePublishBatch } from './itemPublishBatchState';
test('completed history does not replace the new batch upload flow', () => {
expect(selectActivePublishBatch([{ id: 'done', status: 'completed' }])).toBeUndefined();
expect(selectActivePublishBatch([
{ id: 'done', status: 'completed' },
{ id: 'active', status: 'running' },
])?.id).toBe('active');
});
@@ -1,3 +0,0 @@
// 旧目录保留兼容入口,实际批量状态模型统一归属 ItemList feature。
export { selectActivePublishBatch } from '../app/features/items/batchState';
export type { PublishBatchSummary } from '../app/features/items/batchState';
-8
View File
@@ -1,8 +0,0 @@
export {
failedOrderImportRows,
normalizeOrderImportResult,
} from '../app/features/orders/state';
export type {
OrderImportResult,
OrderImportRowResult,
} from '../app/features/orders/types';
+79
View File
@@ -0,0 +1,79 @@
import { readdirSync, readFileSync } from 'node:fs';
import { resolve, relative } from 'node:path';
import { describe, expect, test } from 'vitest';
// sourceRoot 是前端源码根目录,所有架构规则都基于生产源码扫描。
const sourceRoot = resolve(__dirname);
// collectSourceFiles 递归收集指定目录下的 TypeScript/TSX 源文件。
const collectSourceFiles = (directory: string): string[] => readdirSync(directory, { withFileTypes: true }).flatMap(entry => {
// entry 是当前目录中的文件或子目录条目。
// filePath 是当前目录项的绝对路径。
const filePath = resolve(directory, entry.name);
if (entry.isDirectory()) {
if (['node_modules', 'dist', 'coverage'].includes(entry.name)) return [];
return collectSourceFiles(filePath);
}
return /\.(ts|tsx)$/.test(entry.name) ? [filePath] : [];
});
// productionSources 返回排除测试文件后的生产源码及其相对路径。
const productionSources = (): Array<{ relativePath: string; source: string }> => collectSourceFiles(sourceRoot)
.filter(filePath => !filePath.endsWith('.test.ts') && !filePath.endsWith('.test.tsx'))
.map(filePath => ({
relativePath: relative(sourceRoot, filePath).split('/').join('/'),
source: readFileSync(filePath, 'utf8'),
}));
describe('React feature dependency boundaries', () => {
test('network clients are only imported by feature API adapters', () => {
// violations 保存页面、组件或非 API feature 文件中的共享网络客户端依赖。
const violations = productionSources()
.filter(file => file.source.includes("from './services/api'") || file.source.includes("from '../services/api'") || file.source.includes("from '../../../services/api'"))
.filter(file => file.relativePath !== 'services/api.ts' && !file.relativePath.endsWith('/api.ts'))
.map(file => file.relativePath);
expect(violations).toEqual([]);
});
test('production React code does not call fetch or axios outside the request boundary', () => {
// violations 保存页面或组件中直接发起网络请求的源码路径。
const violations = productionSources()
.filter(file => file.relativePath !== 'request.ts' && /\bfetch\s*\(|\baxios\b/.test(file.source))
.map(file => file.relativePath);
expect(violations).toEqual([]);
});
test('feature API adapters are the only feature files allowed to depend on shared API', () => {
// violations 保存 feature 内部绕过 API 适配层的共享服务依赖。
const violations = productionSources()
.filter(file => file.relativePath.startsWith('app/features/') && file.source.includes("from '../../../services/api'"))
.filter(file => !file.relativePath.endsWith('/api.ts'))
.map(file => file.relativePath);
expect(violations).toEqual([]);
});
test('legacy component state compatibility entrypoints have been removed', () => {
// legacyEntrypoints 是不应重新引入页面层状态转发文件的旧路径。
const legacyEntrypoints = [
'components/accountEdit.ts',
'components/accountPause.ts',
'components/accountRuntimeState.ts',
'components/cardListState.ts',
'components/itemPublishBatchState.ts',
'components/orderImportState.ts',
'components/automationIssueState.ts',
];
expect(legacyEntrypoints.filter(entry => {
try {
readFileSync(resolve(sourceRoot, entry));
return true;
} catch {
return false;
}
})).toEqual([]);
});
});
+11 -1
View File
@@ -16,7 +16,7 @@ import {
getReplyRules, getDefaultReplies, getDefaultReply, updateDefaultReply, deleteDefaultReply, clearDefaultReplyRecords,
getShippingRules,
getShippingRulesPage,
getSystemSettings, getCards, createCard, updateCard, deleteCard, getCardDetails, batchCreateCards, appendCardData,
getSystemSettings, getHealth, getCards, createCard, updateCard, deleteCard, getCardDetails, batchCreateCards, appendCardData,
getValidOrders,
publishItem, recommendPublishCategory, previewItemPublishBatch,
logout,
@@ -56,6 +56,16 @@ test('updateSystemSettings uses one atomic bulk request', async () => {
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({ theme_color: 'blue', renewal_log_retention_days: 15 });
});
test('health API exposes build metadata through the request boundary', async () => {
// fetchMock 是健康检查 API 的请求替身。
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ version: '1.2.3', commit: 'abc123' }));
vi.stubGlobal('fetch', fetchMock);
const controller = new AbortController();
await expect(getHealth({ signal: controller.signal })).resolves.toEqual({ version: '1.2.3', commit: 'abc123' });
expect(fetchMock).toHaveBeenCalledWith('/health', expect.objectContaining({ method: 'GET', signal: expect.any(AbortSignal) }));
});
test('chat APIs preserve account and conversation scope', async () => {
const fetchMock = vi.fn()
.mockResolvedValueOnce(jsonResponse({ sessions: [{ account_id: 'a1', chat_id: 'c1' }] }))
+5
View File
@@ -30,6 +30,11 @@ export const verifySession = async (options?: RequestControlOptions): Promise<{
return get('/api/v1/session', undefined, options);
};
// getHealth 读取服务健康检查和构建版本信息。
export const getHealth = async (options?: RequestControlOptions): Promise<{ version?: string; commit?: string }> => {
return get('/health', undefined, options);
};
export const logout = async (): Promise<ApiResponse> => {
return post('/api/v1/session/logout', {});
};