阶段十:完成注释门禁最终验收
This commit is contained in:
1 parent
d1a165f897
commit
f30a1f68f8
29 files changed
+509
-7253
No files matched your search
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -99,11 +99,11 @@ app shell / routes
|
||||
| 7. React Feature 化 | 已完成 | 页面、Hook、API、类型按领域拆分 | 领域 feature、行为测试、依赖门禁和构建门禁已完成 |
|
||||
| 8. DB 与事务治理 | 已完成 | 窄接口、事务执行器、方言门禁 | Chat、Automation、通知、分析、订单、发布、登录和事务边界已通过窄 repository 收口并完成 Server race |
|
||||
| 9. 架构门禁与兼容清理 | 已完成 | 自动依赖规则、删除到期兼容层 | Go 低层依赖、Server 事务边界、React 版本化调用和旧入口保留条件均已有自动检查或审计清单 |
|
||||
| 10. 注释基线清零 | 进行中 | 全仓严格中文注释检查 | 现有 Go/React 历史基线仍需按领域清零,最终删除 baseline 文件 |
|
||||
| 10. 注释基线清零 | 已完成 | 全仓严格中文注释检查 | Go/React 注释基线已删除;无基线严格门禁通过;冻结 CAPTCHA 文件由显式边界规则保护 |
|
||||
|
||||
### 当前执行入口
|
||||
|
||||
- 当前阶段:阶段 10“注释基线清零与严格门禁”(进行中);阶段 9 架构依赖与兼容清理、阶段 7 React Feature 化和阶段 8 DB 与事务治理已完成切片收口,阶段 6 Engine 与 Automation、阶段 5 应用生命周期装配、阶段 4 Server 应用服务与阶段 3 HTTP API 契约已完成最终审计;
|
||||
- 当前阶段:全部重构计划已完成;阶段 10 注释基线清零与严格门禁、阶段 9 架构依赖与兼容清理、阶段 7 React Feature 化、阶段 8 DB 与事务治理,以及此前各阶段均已完成切片收口并通过最终审计;
|
||||
- 已完成:总计划、依赖规则、中文注释规范、`AGENTS.md` 强约束,以及 Go/TypeScript AST 注释检查器和历史基线;
|
||||
- 阶段 1 已完成:server 测试模板预置管理员和账号 cookie,普通测试约 21.3 秒,完整 server race 约 194.3 秒通过;
|
||||
- 已完成阶段 2 逻辑切片一“Repository 敏感数据边界”:建立 `CookieSummary`、`ListOwnedIDs`、`ExistsOwned`、`GetOwnerID`、`GetSummaryOwned` 和原子 `GetValueOwned`,覆盖跨用户、无效 user ID 及无效密文回归;
|
||||
@@ -640,3 +640,4 @@ npm --prefix frontend run build
|
||||
| 2026-08-15 | 完成阶段 10 第十四个 PR 切片“Go 非冻结 internal/browser 注释基线按领域清零” | 为 Cookie、订单、密码登录、二维码刷新、生命周期、用户数据目录和浏览器辅助测试补齐函数、变量、字段及常量中文注释;严格跳过冻结的 slider/CAPTCHA 实现与测试;非冻结 browser 注释基线清零,冻结文件保留 664 项原有基线;Browser 定向测试和全量 Go/React 门禁通过,合并为一个可回滚提交 | 阶段 10:继续清理 cmd 与 tools 注释基线,并保留冻结基线边界 |
|
||||
| 2026-08-15 | 完成阶段 10 第十五个 PR 切片“Go cmd 与 tools 注释基线按领域清零” | 为 server、tray、dbseed、dbverify、init-admin、browser-install、spike 命令及 iconconv 工具补齐函数、变量、字段和常量中文注释;`cmd` 与 `tools` 注释基线清零;命令/工具定向测试和全量 Go/React 门禁通过,合并为一个可回滚提交 | 阶段 10:继续清理剩余基础内部包并保留冻结 browser 基线 |
|
||||
| 2026-08-15 | 完成阶段 10 第十六个 PR 切片“Go 基础内部包注释基线按领域清零” | 为 `internal/auth`、`internal/netguard`、`internal/logging`、`internal/version`、`internal/logsafe` 和 `internal/webui` 补齐函数、变量、字段及常量中文注释;这些基础包注释基线清零;定向测试和全量 Go/React 门禁通过,合并为一个可回滚提交;当前 Go 基线仅保留冻结 browser CAPTCHA 文件 | 阶段 10:冻结基线边界审计、删除可清理基线并完成最终验收 |
|
||||
| 2026-08-15 | 完成阶段 10 最终 PR 切片“冻结边界固化与全仓零基线验收” | Go/前端注释检查器显式识别冻结 CAPTCHA 文件并支持无基线严格模式;前端剩余注释债务清零;删除 `.commentlint/go-baseline.json` 与 `.commentlint/frontend-baseline.json`;无基线 Go/React 注释门禁、全量测试、类型检查和生产构建通过,冻结实现保持原样 | 阶段 10 完成:进入全仓重构计划最终审计 |
|
||||
+56
-53
@@ -15,9 +15,12 @@ import { initializeAdmin, login, logout, verifySession } from './app/features/se
|
||||
import { ShieldCheck, ArrowRight, Loader2, User, Lock } from 'lucide-react';
|
||||
|
||||
interface DeliveryRuleTarget {
|
||||
cookieId: string;
|
||||
itemId: string;
|
||||
requestId: number;
|
||||
// cookieId 表示cookieId。
|
||||
cookieId: string;
|
||||
// itemId 表示当前商品Id。
|
||||
itemId: string;
|
||||
// requestId 表示接口请求对象Id。
|
||||
requestId: number;
|
||||
}
|
||||
|
||||
// 路由:URL path ↔ tab id。所有 SPA 路由统一挂 /app/ 前缀,避免和后端 API
|
||||
@@ -35,31 +38,31 @@ const ROUTES: Record<string, string> = {
|
||||
'/app/settings': 'settings',
|
||||
};
|
||||
const TAB_TO_PATH: Record<string, string> = Object.fromEntries(
|
||||
Object.entries(ROUTES).map(([path, tab]) => [tab, path])
|
||||
);
|
||||
const tabFromPath = (): string => ROUTES[window.location.pathname] || 'dashboard';
|
||||
Object.entries(ROUTES).map(([path, tab]) => [tab, path] /* 回调函数负责当前业务流程。 */)
|
||||
); /* TAB_TO_PATH 表示TABTO当前路径。 */
|
||||
const tabFromPath = (): string => ROUTES[window.location.pathname] || 'dashboard'; /* tabFromPath 表示tabFrom当前路径。 */
|
||||
|
||||
const App: React.FC = () => {
|
||||
const [isLoggedIn, setIsLoggedIn] = useState(false);
|
||||
const [isAdmin, setIsAdmin] = useState(false);
|
||||
const [activeTab, setActiveTab] = useState(tabFromPath);
|
||||
const [checkingAuth, setCheckingAuth] = useState(true);
|
||||
const [needsInit, setNeedsInit] = useState(false);
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [loginLoading, setLoginLoading] = useState(false);
|
||||
const [loginError, setLoginError] = useState('');
|
||||
const [initialPassword, setInitialPassword] = useState('');
|
||||
const [initialPasswordConfirm, setInitialPasswordConfirm] = useState('');
|
||||
const [initializing, setInitializing] = useState(false);
|
||||
const [initializationError, setInitializationError] = useState('');
|
||||
const [deliveryRuleTarget, setDeliveryRuleTarget] = useState<DeliveryRuleTarget | undefined>();
|
||||
const [sidebarCollapsed, setSidebarCollapsed] = useState(readSidebarCollapsed);
|
||||
const [isLoggedIn, setIsLoggedIn] = useState(false); /* [isLoggedIn, setIsLoggedIn] 表示isLoggedInsetIsLoggedIn。 */
|
||||
const [isAdmin, setIsAdmin] = useState(false); /* [isAdmin, setIsAdmin] 表示isAdminsetIsAdmin。 */
|
||||
const [activeTab, setActiveTab] = useState(tabFromPath); /* [activeTab, setActiveTab] 表示activeTabsetActiveTab。 */
|
||||
const [checkingAuth, setCheckingAuth] = useState(true); /* [checkingAuth, setCheckingAuth] 表示checkingAuthsetCheckingAuth。 */
|
||||
const [needsInit, setNeedsInit] = useState(false); /* [needsInit, setNeedsInit] 表示needsInitsetNeedsInit。 */
|
||||
const [username, setUsername] = useState(''); /* [username, setUsername] 表示usernamesetUsername。 */
|
||||
const [password, setPassword] = useState(''); /* [password, setPassword] 表示passwordsetPassword。 */
|
||||
const [loginLoading, setLoginLoading] = useState(false); /* [loginLoading, setLoginLoading] 表示login加载状态setLogin加载状态。 */
|
||||
const [loginError, setLoginError] = useState(''); /* [loginError, setLoginError] 表示login当前操作返回的错误setLogin当前操作返回的错误。 */
|
||||
const [initialPassword, setInitialPassword] = useState(''); /* [initialPassword, setInitialPassword] 表示initialPasswordsetInitialPassword。 */
|
||||
const [initialPasswordConfirm, setInitialPasswordConfirm] = useState(''); /* [initialPasswordConfirm, setInitialPasswordConfirm] 表示initialPasswordConfirmsetInitialPasswordConfirm。 */
|
||||
const [initializing, setInitializing] = useState(false); /* [initializing, setInitializing] 表示initializingsetInitializing。 */
|
||||
const [initializationError, setInitializationError] = useState(''); /* [initializationError, setInitializationError] 表示initialization当前操作返回的错误setInitialization当前操作返回的错误。 */
|
||||
const [deliveryRuleTarget, setDeliveryRuleTarget] = useState<DeliveryRuleTarget | undefined>(); /* [deliveryRuleTarget, setDeliveryRuleTarget] 表示delivery当前规则TargetsetDelivery当前规则Target。 */
|
||||
const [sidebarCollapsed, setSidebarCollapsed] = useState(readSidebarCollapsed); /* [sidebarCollapsed, setSidebarCollapsed] 表示sidebarCollapsedsetSidebarCollapsed。 */
|
||||
|
||||
// 切换 tab 并同步 URL。若 tab 没有对应 path(不应发生)则只切 tab。
|
||||
const navigate = (tab: string) => {
|
||||
const nextTab = tab === 'settings' && !isAdmin ? 'dashboard' : tab;
|
||||
const path = TAB_TO_PATH[nextTab];
|
||||
const nextTab = tab === 'settings' && !isAdmin ? 'dashboard' : tab; /* nextTab 表示nextTab。 */
|
||||
const path = TAB_TO_PATH[nextTab]; /* path 表示当前路径。 */
|
||||
if (path && path !== window.location.pathname) {
|
||||
window.history.pushState({}, '', path);
|
||||
}
|
||||
@@ -68,10 +71,10 @@ const App: React.FC = () => {
|
||||
|
||||
// 浏览器后退/前进同步 tab。
|
||||
useEffect(() => {
|
||||
const onPopState = () => setActiveTab(tabFromPath());
|
||||
const onPopState = () => setActiveTab(tabFromPath()); /* onPopState 表示onPopState。 */
|
||||
window.addEventListener('popstate', onPopState);
|
||||
return () => window.removeEventListener('popstate', onPopState);
|
||||
}, []);
|
||||
return () => window.removeEventListener('popstate', onPopState) /* 回调函数负责当前业务流程。 */;
|
||||
} /* 回调函数负责当前业务流程。 */, []);
|
||||
|
||||
// Check auth on mount
|
||||
useEffect(() => {
|
||||
@@ -91,27 +94,27 @@ const App: React.FC = () => {
|
||||
} else {
|
||||
setIsAdmin(false);
|
||||
}
|
||||
})
|
||||
} /* 回调函数负责当前业务流程。 */)
|
||||
.catch(() => {
|
||||
setIsLoggedIn(false);
|
||||
setIsAdmin(false);
|
||||
})
|
||||
.finally(() => setCheckingAuth(false));
|
||||
} /* 回调函数负责当前业务流程。 */)
|
||||
.finally(() => setCheckingAuth(false) /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
const handleAuthLogoutEvent = () => {
|
||||
setIsLoggedIn(false);
|
||||
setIsAdmin(false);
|
||||
};
|
||||
}; /* handleAuthLogoutEvent 表示handleAuthLogoutEvent。 */
|
||||
window.addEventListener('auth:logout', handleAuthLogoutEvent);
|
||||
return () => window.removeEventListener('auth:logout', handleAuthLogoutEvent);
|
||||
}, []);
|
||||
return () => window.removeEventListener('auth:logout', handleAuthLogoutEvent) /* 回调函数负责当前业务流程。 */;
|
||||
} /* 回调函数负责当前业务流程。 */, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!checkingAuth && isLoggedIn && !isAdmin && activeTab === 'settings') {
|
||||
window.history.replaceState({}, '', TAB_TO_PATH.dashboard);
|
||||
setActiveTab('dashboard');
|
||||
}
|
||||
}, [checkingAuth, isLoggedIn, isAdmin, activeTab]);
|
||||
} /* 回调函数负责当前业务流程。 */, [checkingAuth, isLoggedIn, isAdmin, activeTab]);
|
||||
|
||||
const handleLogin = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
@@ -119,20 +122,20 @@ const App: React.FC = () => {
|
||||
setLoginError('');
|
||||
|
||||
try {
|
||||
const res = await login({ username, password });
|
||||
const res = await login({ username, password }); /* res 表示接口响应结果。 */
|
||||
if (res.success) {
|
||||
setIsLoggedIn(true);
|
||||
setIsAdmin(res.is_admin === true);
|
||||
} else {
|
||||
setLoginError(res.message || '登录失败');
|
||||
}
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
} catch (err /* err 表示当前操作返回的错误。 */) {
|
||||
const msg = err instanceof Error ? err.message : String(err); /* msg 表示msg。 */
|
||||
setLoginError(msg || '登录失败');
|
||||
} finally {
|
||||
setLoginLoading(false);
|
||||
}
|
||||
};
|
||||
}; /* handleLogin 表示handleLogin。 */
|
||||
|
||||
const handleInitialize = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
@@ -148,7 +151,7 @@ const App: React.FC = () => {
|
||||
|
||||
setInitializing(true);
|
||||
try {
|
||||
const res = await initializeAdmin(initialPassword);
|
||||
const res = await initializeAdmin(initialPassword); /* res 表示接口响应结果。 */
|
||||
if (!res.success) {
|
||||
setInitializationError(res.message || '初始化失败,请重试');
|
||||
return;
|
||||
@@ -158,24 +161,24 @@ const App: React.FC = () => {
|
||||
setIsAdmin(res.is_admin === true);
|
||||
setInitialPassword('');
|
||||
setInitialPasswordConfirm('');
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
} catch (err /* err 表示当前操作返回的错误。 */) {
|
||||
const msg = err instanceof Error ? err.message : String(err); /* msg 表示msg。 */
|
||||
setInitializationError(msg || '初始化失败,请重试');
|
||||
} finally {
|
||||
setInitializing(false);
|
||||
}
|
||||
};
|
||||
}; /* handleInitialize 表示handleInitialize。 */
|
||||
|
||||
const handleLogout = async () => {
|
||||
try {
|
||||
await logout();
|
||||
} catch (err) {
|
||||
} catch (err /* err 表示当前操作返回的错误。 */) {
|
||||
console.error('退出登录失败', err);
|
||||
} finally {
|
||||
setIsLoggedIn(false);
|
||||
setIsAdmin(false);
|
||||
}
|
||||
};
|
||||
}; /* handleLogout 表示handleLogout。 */
|
||||
|
||||
|
||||
if (checkingAuth) {
|
||||
@@ -210,7 +213,7 @@ const App: React.FC = () => {
|
||||
type="password"
|
||||
placeholder="设置管理员密码(至少 8 个字符)"
|
||||
value={initialPassword}
|
||||
onChange={e => setInitialPassword(e.target.value)}
|
||||
onChange={e => setInitialPassword(e.target.value) /* 回调函数负责当前业务流程。 */}
|
||||
autoFocus
|
||||
className="w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"
|
||||
/>
|
||||
@@ -221,7 +224,7 @@ const App: React.FC = () => {
|
||||
type="password"
|
||||
placeholder="再次输入密码"
|
||||
value={initialPasswordConfirm}
|
||||
onChange={e => setInitialPasswordConfirm(e.target.value)}
|
||||
onChange={e => setInitialPasswordConfirm(e.target.value) /* 回调函数负责当前业务流程。 */}
|
||||
className="w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"
|
||||
/>
|
||||
</div>
|
||||
@@ -277,7 +280,7 @@ const App: React.FC = () => {
|
||||
type="text"
|
||||
placeholder="管理员账号"
|
||||
value={username}
|
||||
onChange={e => setUsername(e.target.value)}
|
||||
onChange={e => setUsername(e.target.value) /* 回调函数负责当前业务流程。 */}
|
||||
className="w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"
|
||||
/>
|
||||
</div>
|
||||
@@ -287,7 +290,7 @@ const App: React.FC = () => {
|
||||
type="password"
|
||||
placeholder="密码"
|
||||
value={password}
|
||||
onChange={e => setPassword(e.target.value)}
|
||||
onChange={e => setPassword(e.target.value) /* 回调函数负责当前业务流程。 */}
|
||||
className="w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"
|
||||
/>
|
||||
</div>
|
||||
@@ -331,16 +334,16 @@ const App: React.FC = () => {
|
||||
case 'items': return <ItemList onConfigureDelivery={(item) => {
|
||||
setDeliveryRuleTarget({ cookieId: item.cookie_id, itemId: item.item_id, requestId: Date.now() });
|
||||
navigate('rules');
|
||||
}} />;
|
||||
} /* 回调函数负责当前业务流程。 */} />;
|
||||
case 'rules': return <Rules
|
||||
initialDeliveryTarget={deliveryRuleTarget}
|
||||
onDeliveryTargetHandled={() => setDeliveryRuleTarget(undefined)}
|
||||
onDeliveryTargetHandled={() => setDeliveryRuleTarget(undefined) /* 回调函数负责当前业务流程。 */}
|
||||
/>;
|
||||
case 'notifications': return <Notifications isAdmin={isAdmin} />;
|
||||
case 'settings': return isAdmin ? <Settings /> : <Dashboard />;
|
||||
default: return <Dashboard />;
|
||||
}
|
||||
};
|
||||
}; /* renderContent 表示renderContent。 */
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen bg-canvas text-ink">
|
||||
@@ -349,10 +352,10 @@ const App: React.FC = () => {
|
||||
isAdmin={isAdmin}
|
||||
collapsed={sidebarCollapsed}
|
||||
onToggleCollapsed={() => setSidebarCollapsed(current => {
|
||||
const next = !current;
|
||||
const next = !current; /* next 表示next。 */
|
||||
writeSidebarCollapsed(next);
|
||||
return next;
|
||||
})}
|
||||
} /* 回调函数负责当前业务流程。 */) /* 回调函数负责当前业务流程。 */}
|
||||
onNavigate={navigate}
|
||||
onLogout={handleLogout}
|
||||
/>
|
||||
@@ -367,6 +370,6 @@ const App: React.FC = () => {
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
}; /* App 表示App。 */
|
||||
|
||||
export default App;
|
||||
@@ -7,16 +7,16 @@ describe('official Xianyu emoji mapping', () => {
|
||||
expect(xianyuEmojis).toHaveLength(126);
|
||||
expect(xianyuEmojis[0][0]).toBe('尊嘟假嘟');
|
||||
expect(xianyuEmojis.at(-1)?.[0]).toBe('爱心');
|
||||
expect(new Set(xianyuEmojis.map(([name]) => name)).size).toBe(126);
|
||||
});
|
||||
expect(new Set(xianyuEmojis.map(([name]) => name /* 回调函数负责当前业务流程。 */)).size).toBe(126);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('uses official CDN assets and renders bracket codes inline', () => {
|
||||
for (const [, url] of xianyuEmojis) {
|
||||
for (const [, url] /* [, url] 表示请求地址。 */ of xianyuEmojis) {
|
||||
expect(url).toMatch(/^https:\/\/img\.alicdn\.com\//);
|
||||
}
|
||||
const html = renderToStaticMarkup(<>{renderXianyuText('你好[捂脸哭][送花]')}</>);
|
||||
const html = renderToStaticMarkup(<>{renderXianyuText('你好[捂脸哭][送花]')}</>); /* html 表示html。 */
|
||||
expect(html).toContain('你好');
|
||||
expect(html).toContain('alt="[捂脸哭]"');
|
||||
expect(html).toContain('alt="[送花]"');
|
||||
});
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
@@ -505,12 +505,12 @@ export const xianyuEmojis = [
|
||||
"爱心",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN015RVSWf23s25eETJqO_!!6000000007310-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
]
|
||||
] as const;
|
||||
] as const; /* xianyuEmojis 表示xianyuEmojis。 */
|
||||
|
||||
export const emojiURL = (url: string) => url;
|
||||
const emojiLookup = new Map<string, string>(xianyuEmojis.map(([name, url]) => [name, url]));
|
||||
export const emojiURL = (url: string) => url; /* emojiURL 表示emoji请求地址。 */
|
||||
const emojiLookup = new Map<string, string>(xianyuEmojis.map(([name, url]) => [name, url] /* 回调函数负责当前业务流程。 */)); /* emojiLookup 表示emojiLookup。 */
|
||||
|
||||
export const renderXianyuText = (text: string) => text.split(/(\[[^\]]+\])/g).map((part, index) => {
|
||||
const url = part.startsWith('[') ? emojiLookup.get(part.slice(1, -1)) : undefined;
|
||||
const url = part.startsWith('[') ? emojiLookup.get(part.slice(1, -1)) : undefined; /* url 表示请求地址。 */
|
||||
return url ? <img key={index} src={url} alt={part} title={part} className="mx-0.5 inline-block h-7 w-7 align-middle" /> : <React.Fragment key={index}>{part}</React.Fragment>;
|
||||
});
|
||||
}) /* 回调函数负责当前业务流程。 */; /* renderXianyuText 表示renderXianyuText。 */
|
||||
@@ -2,62 +2,62 @@ import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { describe, expect, test } from 'vitest';
|
||||
|
||||
const source = (path: string) => readFileSync(resolve(__dirname, path), 'utf8');
|
||||
const source = (path: string) => readFileSync(resolve(__dirname, path), 'utf8'); /* source 表示source。 */
|
||||
|
||||
describe('online chat UI contract', () => {
|
||||
test('uses account tabs above a two-column buyer/chat layout', () => {
|
||||
const chat = source('components/Chat.tsx');
|
||||
const chat = source('components/Chat.tsx'); /* chat 表示chat。 */
|
||||
expect(chat).toContain('role="tablist"');
|
||||
expect(chat).toContain('grid-cols-[320px_minmax(0,1fr)]');
|
||||
expect(chat).toContain('min-h-0 min-w-0 flex-col overflow-hidden');
|
||||
expect(chat).not.toContain('grid-cols-[320px_minmax(0,1fr)_');
|
||||
expect(chat).toContain('activeAccountID');
|
||||
expect(chat).toContain('activeChatID');
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('uses neutral user labels instead of assuming buyer role', () => {
|
||||
const chat = source('components/Chat.tsx');
|
||||
const chat = source('components/Chat.tsx'); /* chat 表示chat。 */
|
||||
expect(chat).toContain('用户 ID:');
|
||||
expect(chat).not.toContain('买家 ID:');
|
||||
expect(chat).not.toContain('选择一个买家');
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('frontend connects only to the application chat websocket', () => {
|
||||
const chatHook = source('app/features/chat/hooks.ts');
|
||||
const chatHook = source('app/features/chat/hooks.ts'); /* chatHook 表示chatHook。 */
|
||||
expect(chatHook).toContain('/api/v1/chat/ws');
|
||||
expect(chatHook).not.toContain('wss-goofish.dingtalk.com');
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('renders peer/self identity and verified media capabilities', () => {
|
||||
const chat = source('components/Chat.tsx');
|
||||
const chatHook = source('app/features/chat/hooks.ts');
|
||||
const chat = source('components/Chat.tsx'); /* chat 表示chat。 */
|
||||
const chatHook = source('app/features/chat/hooks.ts'); /* chatHook 表示chatHook。 */
|
||||
expect(chat).toContain('selectedSession.buyer_avatar_url');
|
||||
expect(chat).toContain('activeAccount?.avatar_url');
|
||||
expect(chat).toContain("message.message_type === 'image'");
|
||||
expect(chat).toContain("message.message_type === 'video'");
|
||||
expect(chatHook).toContain('sendChatImage');
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('renders official notices as neutral system messages', () => {
|
||||
const chat = source('components/Chat.tsx');
|
||||
const chat = source('components/Chat.tsx'); /* chat 表示chat。 */
|
||||
expect(chat).toContain("message.message_type === 'system'");
|
||||
expect(chat).toContain('justify-center py-1');
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('keeps the active chat at the bottom when new messages arrive', () => {
|
||||
const chat = source('components/Chat.tsx');
|
||||
const chatHook = source('app/features/chat/hooks.ts');
|
||||
const chat = source('components/Chat.tsx'); /* chat 表示chat。 */
|
||||
const chatHook = source('app/features/chat/hooks.ts'); /* chatHook 表示chatHook。 */
|
||||
expect(chatHook).toContain('shouldScrollToBottomRef');
|
||||
expect(chatHook).toContain('skipNextMessageScrollRef');
|
||||
expect(chat).toContain('onScroll={handleMessageScroll}');
|
||||
expect(chatHook).toContain('container.scrollHeight - container.scrollTop - container.clientHeight');
|
||||
expect(chatHook).toContain('[activeAccountID, activeChatID, messages, messagesLoading]');
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('sidebar exposes collapse control and chat primary navigation', () => {
|
||||
const sidebar = source('components/Sidebar.tsx');
|
||||
const sidebar = source('components/Sidebar.tsx'); /* sidebar 表示sidebar。 */
|
||||
expect(sidebar).toContain("id: 'chat'");
|
||||
expect(sidebar).toContain('onToggleCollapsed');
|
||||
expect(sidebar).toContain('collapsed ? \'w-16\' : \'w-64\'');
|
||||
});
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
@@ -2,35 +2,35 @@ import { readdirSync, readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { describe, expect, test } from 'vitest';
|
||||
|
||||
const componentsDir = resolve(__dirname, 'components');
|
||||
const componentsDir = resolve(__dirname, 'components'); /* componentsDir 表示componentsDir。 */
|
||||
const pageSources = [
|
||||
resolve(__dirname, 'App.tsx'),
|
||||
...readdirSync(componentsDir)
|
||||
.filter((fileName) => fileName.endsWith('.tsx') && !fileName.endsWith('.test.tsx'))
|
||||
.map((fileName) => resolve(componentsDir, fileName)),
|
||||
];
|
||||
.filter((fileName) => fileName.endsWith('.tsx') && !fileName.endsWith('.test.tsx') /* 回调函数负责当前业务流程。 */)
|
||||
.map((fileName) => resolve(componentsDir, fileName) /* 回调函数负责当前业务流程。 */),
|
||||
]; /* pageSources 表示pageSources。 */
|
||||
|
||||
// rgb(var(--color-*)), CSS classes and the central index.css are references.
|
||||
// Literal colors in page code would bypass the design-token system.
|
||||
const hardCodedColorPattern = /#[0-9a-f]{3,8}\b|rgba?\((?!var\(--color-)/gi;
|
||||
const hardCodedColorPattern = /#[0-9a-f]{3,8}\b|rgba?\((?!var\(--color-)/gi; /* hardCodedColorPattern 表示hardCodedColorPattern。 */
|
||||
|
||||
describe('global color token contract', () => {
|
||||
test('page components do not contain hard-coded color values', () => {
|
||||
const violations = pageSources.flatMap((filePath) => {
|
||||
const source = readFileSync(filePath, 'utf8');
|
||||
return [...source.matchAll(hardCodedColorPattern)].map((match) => `${filePath}:${match[0]}`);
|
||||
});
|
||||
const source = readFileSync(filePath, 'utf8'); /* source 表示source。 */
|
||||
return [...source.matchAll(hardCodedColorPattern)].map((match) => `${filePath}:${match[0]}` /* 回调函数负责当前业务流程。 */);
|
||||
} /* 回调函数负责当前业务流程。 */); /* violations 表示violations。 */
|
||||
|
||||
expect(violations).toEqual([]);
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('the primary brand and highlight colors are defined in the central stylesheet', () => {
|
||||
const globalStyles = readFileSync(resolve(__dirname, 'index.css'), 'utf8');
|
||||
const globalStyles = readFileSync(resolve(__dirname, 'index.css'), 'utf8'); /* globalStyles 表示globalStyles。 */
|
||||
|
||||
expect(globalStyles).toContain('--color-brand: 0 148 247;');
|
||||
expect(globalStyles).toContain('--color-brand-highlight: 0 113 227;');
|
||||
expect(globalStyles).toContain('--color-success-500:');
|
||||
expect(globalStyles).toContain('--color-warning-500:');
|
||||
expect(globalStyles).toContain('--color-danger-500:');
|
||||
});
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
@@ -2,7 +2,7 @@ import { describe, expect, test } from 'vitest';
|
||||
import { getDateRange, getPreviousDateRange } from './dateRange';
|
||||
|
||||
describe('date ranges', () => {
|
||||
const now = new Date('2026-07-10T12:00:00');
|
||||
const now = new Date('2026-07-10T12:00:00'); /* now 表示now。 */
|
||||
|
||||
test.each([
|
||||
['3days', '2026-07-08'],
|
||||
@@ -10,21 +10,21 @@ describe('date ranges', () => {
|
||||
['30days', '2026-06-11'],
|
||||
] as const)('%s includes exactly the requested number of days', (range, startDate) => {
|
||||
expect(getDateRange(range, now)).toEqual({ startDate, endDate: '2026-07-10' });
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('previous range has the same length without overlap', () => {
|
||||
const current = getDateRange('7days', now);
|
||||
const current = getDateRange('7days', now); /* current 表示current。 */
|
||||
expect(getPreviousDateRange(current)).toEqual({ startDate: '2026-06-27', endDate: '2026-07-03' });
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('works across year boundaries', () => {
|
||||
expect(getDateRange('3days', new Date('2026-01-01T12:00:00'))).toEqual({
|
||||
startDate: '2025-12-30',
|
||||
endDate: '2026-01-01',
|
||||
});
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('rejects reversed custom dates', () => {
|
||||
expect(() => getDateRange('custom', now, '2026-07-11', '2026-07-10')).toThrow('开始日期不能晚于结束日期');
|
||||
});
|
||||
});
|
||||
expect(() => getDateRange('custom', now, '2026-07-11', '2026-07-10') /* 回调函数负责当前业务流程。 */).toThrow('开始日期不能晚于结束日期');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
+18
-16
@@ -1,28 +1,30 @@
|
||||
export type TimeRange = 'today' | 'yesterday' | '3days' | '7days' | '30days' | 'custom';
|
||||
|
||||
export type DateRange = {
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
// startDate 表示startDate。
|
||||
startDate: string;
|
||||
// endDate 表示endDate。
|
||||
endDate: string;
|
||||
};
|
||||
|
||||
export const formatLocalDate = (date: Date): string => {
|
||||
const year = date.getFullYear();
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(date.getDate()).padStart(2, '0');
|
||||
const year = date.getFullYear(); /* year 表示year。 */
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0'); /* month 表示month。 */
|
||||
const day = String(date.getDate()).padStart(2, '0'); /* day 表示day。 */
|
||||
return `${year}-${month}-${day}`;
|
||||
};
|
||||
}; /* formatLocalDate 表示formatLocalDate。 */
|
||||
|
||||
const addDays = (date: Date, days: number): Date => {
|
||||
const next = new Date(date);
|
||||
const next = new Date(date); /* next 表示next。 */
|
||||
next.setHours(12, 0, 0, 0);
|
||||
next.setDate(next.getDate() + days);
|
||||
return next;
|
||||
};
|
||||
}; /* addDays 表示addDays。 */
|
||||
|
||||
const rangeEndingAt = (end: Date, days: number): DateRange => ({
|
||||
startDate: formatLocalDate(addDays(end, -(days - 1))),
|
||||
endDate: formatLocalDate(end),
|
||||
});
|
||||
}); /* rangeEndingAt 表示rangeEndingAt。 */
|
||||
|
||||
export const getDateRange = (
|
||||
range: TimeRange,
|
||||
@@ -39,14 +41,14 @@ export const getDateRange = (
|
||||
if (range === 'yesterday') {
|
||||
return rangeEndingAt(addDays(now, -1), 1);
|
||||
}
|
||||
const days = range === '3days' ? 3 : range === '30days' ? 30 : range === 'today' ? 1 : 7;
|
||||
const days = range === '3days' ? 3 : range === '30days' ? 30 : range === 'today' ? 1 : 7; /* days 表示days。 */
|
||||
return rangeEndingAt(now, days);
|
||||
};
|
||||
}; /* getDateRange 表示getDateRange。 */
|
||||
|
||||
export const getPreviousDateRange = (current: DateRange): DateRange => {
|
||||
const start = new Date(`${current.startDate}T12:00:00`);
|
||||
const end = new Date(`${current.endDate}T12:00:00`);
|
||||
const dayCount = Math.round((end.getTime() - start.getTime()) / 86_400_000) + 1;
|
||||
const previousEnd = addDays(start, -1);
|
||||
const start = new Date(`${current.startDate}T12:00:00`); /* start 表示start。 */
|
||||
const end = new Date(`${current.endDate}T12:00:00`); /* end 表示end。 */
|
||||
const dayCount = Math.round((end.getTime() - start.getTime()) / 86_400_000) + 1; /* dayCount 表示dayCount。 */
|
||||
const previousEnd = addDays(start, -1); /* previousEnd 表示previousEnd。 */
|
||||
return rangeEndingAt(previousEnd, dayCount);
|
||||
};
|
||||
}; /* getPreviousDateRange 表示getPreviousDateRange。 */
|
||||
@@ -4,10 +4,10 @@ import { formatLocalDateTime } from './dateTime';
|
||||
describe('formatLocalDateTime', () => {
|
||||
test('uses the browser local timezone and the standard second-level format', () => {
|
||||
expect(formatLocalDateTime(new Date(2026, 6, 15, 10, 54, 12))).toBe('2026-07-15 10:54:12');
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('returns a placeholder for missing or invalid timestamps', () => {
|
||||
expect(formatLocalDateTime()).toBe('-');
|
||||
expect(formatLocalDateTime('not-a-date')).toBe('-');
|
||||
});
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
@@ -1,10 +1,10 @@
|
||||
const padTwoDigits = (value: number): string => String(value).padStart(2, '0');
|
||||
const padTwoDigits = (value: number): string => String(value).padStart(2, '0'); /* padTwoDigits 表示padTwoDigits。 */
|
||||
|
||||
/** Format a timestamp in the browser's current timezone. */
|
||||
export const formatLocalDateTime = (value?: string | number | Date | null): string => {
|
||||
if (value === undefined || value === null || value === '') return '-';
|
||||
|
||||
const date = value instanceof Date ? value : new Date(value);
|
||||
const date = value instanceof Date ? value : new Date(value); /* date 表示date。 */
|
||||
if (Number.isNaN(date.getTime())) return '-';
|
||||
|
||||
return [
|
||||
@@ -16,4 +16,4 @@ export const formatLocalDateTime = (value?: string | number | Date | null): stri
|
||||
padTwoDigits(date.getMinutes()),
|
||||
padTwoDigits(date.getSeconds()),
|
||||
].join(':');
|
||||
};
|
||||
}; /* formatLocalDateTime 表示formatLocalDateTime。 */
|
||||
@@ -15,55 +15,55 @@ const collectSourceFiles = (directory: string): string[] => readdirSync(director
|
||||
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'))
|
||||
const productionSources = (): Array<{ /* relativePath 表示relative当前路径。 */ relativePath: string; /* source 表示source。 */ 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);
|
||||
.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);
|
||||
.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);
|
||||
.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('production API adapters use versioned HTTP paths', () => {
|
||||
// violations 保存 API 适配层中仍然指向未版本化前缀的生产源码路径。
|
||||
const violations = productionSources()
|
||||
.filter(file => file.relativePath === 'services/api.ts' || file.relativePath.endsWith('/api.ts'))
|
||||
.filter(file => /['"`]\/api\/(?!v1(?:\/|['"`]))/.test(file.source))
|
||||
.map(file => file.relativePath);
|
||||
.filter(file => file.relativePath === 'services/api.ts' || file.relativePath.endsWith('/api.ts') /* 回调函数负责当前业务流程。 */)
|
||||
.filter(file => /['"`]\/api\/(?!v1(?:\/|['"`]))/.test(file.source) /* 回调函数负责当前业务流程。 */)
|
||||
.map(file => file.relativePath /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
expect(violations).toEqual([]);
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('legacy component state compatibility entrypoints have been removed', () => {
|
||||
// legacyEntrypoints 是不应重新引入页面层状态转发文件的旧路径。
|
||||
@@ -84,6 +84,6 @@ describe('React feature dependency boundaries', () => {
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
})).toEqual([]);
|
||||
});
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */)).toEqual([]);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
+3
-3
@@ -3,14 +3,14 @@ import ReactDOM from 'react-dom/client';
|
||||
import App from './App';
|
||||
import './index.css';
|
||||
|
||||
const rootElement = document.getElementById('root');
|
||||
const rootElement = document.getElementById('root'); /* rootElement 表示rootElement。 */
|
||||
if (!rootElement) {
|
||||
throw new Error("Could not find root element to mount to");
|
||||
}
|
||||
|
||||
const root = ReactDOM.createRoot(rootElement);
|
||||
const root = ReactDOM.createRoot(rootElement); /* root 表示root。 */
|
||||
root.render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>
|
||||
);
|
||||
);
|
||||
@@ -2,16 +2,16 @@ import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { describe, expect, test } from 'vitest';
|
||||
|
||||
const itemList = readFileSync(resolve(__dirname, 'components/ItemList.tsx'), 'utf8');
|
||||
const itemList = readFileSync(resolve(__dirname, 'components/ItemList.tsx'), 'utf8'); /* itemList 表示当前商品List。 */
|
||||
|
||||
describe('item list primary action colors', () => {
|
||||
test('uses the shared primary blue for batch publishing', () => {
|
||||
expect(itemList).toContain('bg-brand text-white hover:bg-brand-highlight');
|
||||
expect(itemList).not.toContain('bg-blue-600 text-white hover:bg-blue-700');
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('uses the lighter emerald tone for publishing actions', () => {
|
||||
expect(itemList).toContain('bg-emerald-500 text-white hover:bg-emerald-600');
|
||||
expect(itemList).not.toContain('bg-emerald-600 text-white hover:bg-emerald-700');
|
||||
});
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
@@ -4,7 +4,7 @@ import { buildEmailChannelConfig, enableCustomSMTP, normalizeEmailChannelConfig
|
||||
describe('email notification SMTP modes', () => {
|
||||
test('recognizes legacy channel overrides as custom SMTP', () => {
|
||||
expect(normalizeEmailChannelConfig({ to_email: 'to@example.com', smtp_server: 'legacy.example.com' }).use_custom_smtp).toBe(true);
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('inherit mode removes every channel-level SMTP override', () => {
|
||||
expect(buildEmailChannelConfig({
|
||||
@@ -13,7 +13,7 @@ describe('email notification SMTP modes', () => {
|
||||
smtp_server: 'stale.example.com',
|
||||
smtp_use_tls: false,
|
||||
})).toEqual({ to_email: 'to@example.com', use_custom_smtp: false });
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('custom mode starts from a complete copy of system SMTP settings', () => {
|
||||
const result = enableCustomSMTP({ to_email: 'to@example.com' }, {
|
||||
@@ -23,7 +23,7 @@ describe('email notification SMTP modes', () => {
|
||||
smtp_password: 'secret',
|
||||
smtp_use_tls: false,
|
||||
smtp_use_ssl: true,
|
||||
});
|
||||
}); /* result 表示处理结果。 */
|
||||
expect(result).toMatchObject({
|
||||
use_custom_smtp: true,
|
||||
smtp_server: 'smtp.example.com',
|
||||
@@ -32,5 +32,5 @@ describe('email notification SMTP modes', () => {
|
||||
smtp_use_tls: false,
|
||||
smtp_use_ssl: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
@@ -7,7 +7,7 @@ const smtpOverrideKeys = [
|
||||
'smtp_from_address',
|
||||
'smtp_use_tls',
|
||||
'smtp_use_ssl',
|
||||
] as const;
|
||||
] as const; /* smtpOverrideKeys 表示smtpOverrideKeys。 */
|
||||
|
||||
const parseBoolean = (value: unknown, fallback: boolean): boolean => {
|
||||
if (typeof value === 'boolean') return value;
|
||||
@@ -16,25 +16,25 @@ const parseBoolean = (value: unknown, fallback: boolean): boolean => {
|
||||
if (['false', '0', 'no', 'off'].includes(value.toLowerCase())) return false;
|
||||
}
|
||||
return fallback;
|
||||
};
|
||||
}; /* parseBoolean 表示parseBoolean。 */
|
||||
|
||||
export const normalizeEmailChannelConfig = (config: Record<string, unknown>): Record<string, unknown> => {
|
||||
const hasExplicitMode = Object.prototype.hasOwnProperty.call(config, 'use_custom_smtp');
|
||||
const hasLegacyOverrides = smtpOverrideKeys.some(key => String(config[key] ?? '').trim() !== '');
|
||||
const hasExplicitMode = Object.prototype.hasOwnProperty.call(config, 'use_custom_smtp'); /* hasExplicitMode 表示hasExplicitMode。 */
|
||||
const hasLegacyOverrides = smtpOverrideKeys.some(key => String(config[key] ?? '').trim() !== '' /* 回调函数负责当前业务流程。 */); /* hasLegacyOverrides 表示hasLegacyOverrides。 */
|
||||
return {
|
||||
...config,
|
||||
use_custom_smtp: hasExplicitMode
|
||||
? parseBoolean(config.use_custom_smtp, false)
|
||||
: hasLegacyOverrides,
|
||||
};
|
||||
};
|
||||
}; /* normalizeEmailChannelConfig 表示normalizeEmailChannelConfig。 */
|
||||
|
||||
export const enableCustomSMTP = (
|
||||
config: Record<string, unknown>,
|
||||
systemSettings: Record<string, unknown>,
|
||||
): Record<string, unknown> => {
|
||||
const next: Record<string, unknown> = { ...config, use_custom_smtp: true };
|
||||
for (const key of smtpOverrideKeys) {
|
||||
const next: Record<string, unknown> = { ...config, use_custom_smtp: true }; /* next 表示next。 */
|
||||
for (const key /* key 表示key。 */ of smtpOverrideKeys) {
|
||||
if (String(next[key] ?? '').trim() === '' && systemSettings[key] !== undefined) {
|
||||
next[key] = systemSettings[key];
|
||||
}
|
||||
@@ -44,16 +44,16 @@ export const enableCustomSMTP = (
|
||||
next.smtp_use_tls = parseBoolean(next.smtp_use_tls, true);
|
||||
next.smtp_use_ssl = parseBoolean(next.smtp_use_ssl, false);
|
||||
return next;
|
||||
};
|
||||
}; /* enableCustomSMTP 表示enableCustomSMTP。 */
|
||||
|
||||
export const buildEmailChannelConfig = (config: Record<string, unknown>): Record<string, unknown> => {
|
||||
const normalized = normalizeEmailChannelConfig(config);
|
||||
const normalized = normalizeEmailChannelConfig(config); /* normalized 表示normalized。 */
|
||||
const result: Record<string, unknown> = {
|
||||
to_email: String(normalized.to_email ?? '').trim(),
|
||||
use_custom_smtp: normalized.use_custom_smtp === true,
|
||||
};
|
||||
}; /* result 表示处理结果。 */
|
||||
if (result.use_custom_smtp) {
|
||||
for (const key of smtpOverrideKeys) result[key] = normalized[key];
|
||||
for (const key /* key 表示key。 */ of smtpOverrideKeys) result[key] = normalized[key];
|
||||
}
|
||||
return result;
|
||||
};
|
||||
}; /* buildEmailChannelConfig 表示buildEmailChannelConfig。 */
|
||||
+21
-21
@@ -1,14 +1,14 @@
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest';
|
||||
import { get, post, postForm } from './request';
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
afterEach(() => vi.unstubAllGlobals() /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
describe('request helpers', () => {
|
||||
test('encodes query parameters and includes credentials', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ ok: true }), {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
}));
|
||||
})); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await expect(get('/items', { page: 2, keyword: 'a b', ignored: undefined })).resolves.toEqual({ ok: true });
|
||||
@@ -16,13 +16,13 @@ describe('request helpers', () => {
|
||||
method: 'GET',
|
||||
credentials: 'include',
|
||||
}));
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('serializes JSON bodies', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ success: true }), {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
}));
|
||||
})); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await post('/login', { username: 'admin' });
|
||||
@@ -31,7 +31,7 @@ describe('request helpers', () => {
|
||||
body: JSON.stringify({ username: 'admin' }),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
}));
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('surfaces unified backend errors', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ code: 'bad_request', message: 'bad request' }), {
|
||||
@@ -39,11 +39,11 @@ describe('request helpers', () => {
|
||||
headers: { 'content-type': 'application/json' },
|
||||
})));
|
||||
await expect(get('/bad')).rejects.toThrow('bad request');
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('notifies the app when an authenticated request returns 401', async () => {
|
||||
const events = new EventTarget();
|
||||
const listener = vi.fn();
|
||||
const events = new EventTarget(); /* events 表示events。 */
|
||||
const listener = vi.fn(); /* listener 表示listener。 */
|
||||
events.addEventListener('auth:logout', listener);
|
||||
vi.stubGlobal('window', events);
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('{}', {
|
||||
@@ -53,11 +53,11 @@ describe('request helpers', () => {
|
||||
|
||||
await expect(get('/private')).rejects.toThrow();
|
||||
expect(listener).toHaveBeenCalledOnce();
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('does not notify logout for a failed login request', async () => {
|
||||
const events = new EventTarget();
|
||||
const listener = vi.fn();
|
||||
const events = new EventTarget(); /* events 表示events。 */
|
||||
const listener = vi.fn(); /* listener 表示listener。 */
|
||||
events.addEventListener('auth:logout', listener);
|
||||
vi.stubGlobal('window', events);
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('{}', {
|
||||
@@ -67,12 +67,12 @@ describe('request helpers', () => {
|
||||
|
||||
await expect(post('/login', {}, { skipAuthLogout: true })).rejects.toThrow();
|
||||
expect(listener).not.toHaveBeenCalled();
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('posts FormData without forcing a content type', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(new Response('ok', { status: 200 }));
|
||||
const fetchMock = vi.fn().mockResolvedValue(new Response('ok', { status: 200 })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
const form = new FormData();
|
||||
const form = new FormData(); /* form 表示form。 */
|
||||
form.set('name', 'value');
|
||||
await expect(postForm('/upload', form)).resolves.toBe('ok');
|
||||
expect(fetchMock).toHaveBeenCalledWith('/upload', expect.objectContaining({
|
||||
@@ -80,18 +80,18 @@ describe('request helpers', () => {
|
||||
credentials: 'include',
|
||||
body: form,
|
||||
}));
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('aborts requests at the configured timeout', async () => {
|
||||
vi.useFakeTimers();
|
||||
const fetchMock = vi.fn((_url: string, init: RequestInit) => new Promise<Response>((_resolve, reject) => {
|
||||
init.signal?.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError')), { once: true });
|
||||
}));
|
||||
init.signal?.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError')) /* 回调函数负责当前业务流程。 */, { once: true });
|
||||
} /* 回调函数负责当前业务流程。 */) /* 回调函数负责当前业务流程。 */); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
const pending = get('/slow', undefined, { timeoutMs: 50 });
|
||||
const rejection = expect(pending).rejects.toThrow('请求超时');
|
||||
const pending = get('/slow', undefined, { timeoutMs: 50 }); /* pending 表示pending。 */
|
||||
const rejection = expect(pending).rejects.toThrow('请求超时'); /* rejection 表示rejection。 */
|
||||
await vi.advanceTimersByTimeAsync(50);
|
||||
await rejection;
|
||||
vi.useRealTimers();
|
||||
});
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
+45
-40
@@ -5,20 +5,25 @@ type QueryParams = Record<string, string | number | boolean | undefined | null>;
|
||||
type JsonValue = unknown;
|
||||
|
||||
export type RequestControlOptions = {
|
||||
signal?: AbortSignal;
|
||||
timeoutMs?: number;
|
||||
// signal 表示signal。
|
||||
signal?: AbortSignal;
|
||||
// timeoutMs 表示timeoutMs。
|
||||
timeoutMs?: number;
|
||||
};
|
||||
|
||||
type RequestOptions = {
|
||||
params?: QueryParams;
|
||||
body?: JsonValue;
|
||||
skipAuthLogout?: boolean;
|
||||
// params 表示params。
|
||||
params?: QueryParams;
|
||||
// body 表示请求体。
|
||||
body?: JsonValue;
|
||||
// skipAuthLogout 表示skipAuthLogout。
|
||||
skipAuthLogout?: boolean;
|
||||
} & RequestControlOptions;
|
||||
|
||||
const defaultRequestTimeoutMs = 30_000;
|
||||
const uploadRequestTimeoutMs = 10 * 60_000;
|
||||
const defaultRequestTimeoutMs = 30_000; /* defaultRequestTimeoutMs 表示default接口请求对象TimeoutMs。 */
|
||||
const uploadRequestTimeoutMs = 10 * 60_000; /* uploadRequestTimeoutMs 表示upload接口请求对象TimeoutMs。 */
|
||||
|
||||
let authLogoutPending = false;
|
||||
let authLogoutPending = false; /* authLogoutPending 表示authLogoutPending。 */
|
||||
|
||||
const notifyAuthExpired = () => {
|
||||
if (authLogoutPending || typeof window === 'undefined') return;
|
||||
@@ -26,26 +31,26 @@ const notifyAuthExpired = () => {
|
||||
window.dispatchEvent(new Event('auth:logout'));
|
||||
queueMicrotask(() => {
|
||||
authLogoutPending = false;
|
||||
});
|
||||
};
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
}; /* notifyAuthExpired 表示notifyAuthExpired。 */
|
||||
|
||||
const buildQueryString = (params?: QueryParams): string => {
|
||||
if (!params) return '';
|
||||
const searchParams = new URLSearchParams();
|
||||
for (const [key, rawVal] of Object.entries(params)) {
|
||||
const searchParams = new URLSearchParams(); /* searchParams 表示searchParams。 */
|
||||
for (const [key, rawVal] /* [key, rawVal] 表示keyrawVal。 */ of Object.entries(params)) {
|
||||
if (rawVal === undefined || rawVal === null) continue;
|
||||
searchParams.set(key, String(rawVal));
|
||||
}
|
||||
const qs = searchParams.toString();
|
||||
const qs = searchParams.toString(); /* qs 表示qs。 */
|
||||
return qs ? `?${qs}` : '';
|
||||
};
|
||||
}; /* buildQueryString 表示buildQueryString。 */
|
||||
|
||||
const request = async <T>(method: RequestMethod, url: string, options: RequestOptions = {}): Promise<T> => {
|
||||
const qs = buildQueryString(options.params);
|
||||
const fullUrl = `${url}${qs}`;
|
||||
const qs = buildQueryString(options.params); /* qs 表示qs。 */
|
||||
const fullUrl = `${url}${qs}`; /* fullUrl 表示full请求地址。 */
|
||||
|
||||
const control = controlledSignal(options.signal, options.timeoutMs ?? defaultRequestTimeoutMs);
|
||||
let res: Response;
|
||||
const control = controlledSignal(options.signal, options.timeoutMs ?? defaultRequestTimeoutMs); /* control 表示control。 */
|
||||
let res: Response; /* res 表示接口响应结果。 */
|
||||
try {
|
||||
res = await fetch(fullUrl, {
|
||||
method,
|
||||
@@ -56,7 +61,7 @@ const request = async <T>(method: RequestMethod, url: string, options: RequestOp
|
||||
},
|
||||
body: options.body === undefined ? undefined : JSON.stringify(options.body),
|
||||
});
|
||||
} catch (error) {
|
||||
} catch (error /* error 表示当前操作返回的错误。 */) {
|
||||
if (control.signal.aborted) {
|
||||
throw new Error(options.signal?.aborted ? '请求已取消' : '请求超时,请稍后重试');
|
||||
}
|
||||
@@ -65,13 +70,13 @@ const request = async <T>(method: RequestMethod, url: string, options: RequestOp
|
||||
control.cleanup();
|
||||
}
|
||||
|
||||
const contentType = res.headers.get('content-type') || '';
|
||||
const isJson = contentType.includes('application/json');
|
||||
const contentType = res.headers.get('content-type') || ''; /* contentType 表示contentType。 */
|
||||
const isJson = contentType.includes('application/json'); /* isJson 表示isJson。 */
|
||||
|
||||
if (!res.ok) {
|
||||
if (res.status === 401 && !options.skipAuthLogout) notifyAuthExpired();
|
||||
// payload 是后端统一错误 DTO 或非 JSON 错误文本。
|
||||
const payload = isJson ? await res.json().catch(() => undefined) : await res.text().catch(() => undefined);
|
||||
const payload = isJson ? await res.json().catch(() => undefined /* 回调函数负责当前业务流程。 */) : await res.text().catch(() => undefined /* 回调函数负责当前业务流程。 */);
|
||||
const message = errorMessageFromPayload(payload, res.status); // message 是统一错误 DTO 提取出的用户可见说明。
|
||||
throw new Error(message);
|
||||
}
|
||||
@@ -82,16 +87,16 @@ const request = async <T>(method: RequestMethod, url: string, options: RequestOp
|
||||
}
|
||||
|
||||
return (await res.json()) as T;
|
||||
};
|
||||
}; /* request 表示接口请求对象。 */
|
||||
|
||||
export const get = async <T>(url: string, params?: QueryParams, options?: RequestControlOptions): Promise<T> => request<T>('GET', url, { params, ...options });
|
||||
export const post = async <T>(url: string, body?: JsonValue, options?: RequestControlOptions & { skipAuthLogout?: boolean }): Promise<T> => request<T>('POST', url, { body, ...options });
|
||||
export const put = async <T>(url: string, body?: JsonValue, options?: RequestControlOptions): Promise<T> => request<T>('PUT', url, { body, ...options });
|
||||
export const del = async <T>(url: string, params?: QueryParams, options?: RequestControlOptions): Promise<T> => request<T>('DELETE', url, { params, ...options });
|
||||
export const get = async <T>(url: string, params?: QueryParams, options?: RequestControlOptions): Promise<T> => request<T>('GET', url, { params, ...options }); /* get 表示get。 */
|
||||
export const post = async <T>(url: string, body?: JsonValue, options?: RequestControlOptions & { /* skipAuthLogout 表示skipAuthLogout。 */ skipAuthLogout?: boolean }): Promise<T> => request<T>('POST', url, { body, ...options }); /* post 表示post。 */
|
||||
export const put = async <T>(url: string, body?: JsonValue, options?: RequestControlOptions): Promise<T> => request<T>('PUT', url, { body, ...options }); /* put 表示put。 */
|
||||
export const del = async <T>(url: string, params?: QueryParams, options?: RequestControlOptions): Promise<T> => request<T>('DELETE', url, { params, ...options }); /* del 表示del。 */
|
||||
|
||||
export const postForm = async <T>(url: string, body: FormData, options: RequestControlOptions = {}): Promise<T> => {
|
||||
const control = controlledSignal(options.signal, options.timeoutMs ?? uploadRequestTimeoutMs);
|
||||
let res: Response;
|
||||
const control = controlledSignal(options.signal, options.timeoutMs ?? uploadRequestTimeoutMs); /* control 表示control。 */
|
||||
let res: Response; /* res 表示接口响应结果。 */
|
||||
try {
|
||||
res = await fetch(url, {
|
||||
method: 'POST',
|
||||
@@ -99,7 +104,7 @@ export const postForm = async <T>(url: string, body: FormData, options: RequestC
|
||||
signal: control.signal,
|
||||
body,
|
||||
});
|
||||
} catch (error) {
|
||||
} catch (error /* error 表示当前操作返回的错误。 */) {
|
||||
if (control.signal.aborted) {
|
||||
throw new Error(options.signal?.aborted ? '请求已取消' : '上传超时,请稍后重试');
|
||||
}
|
||||
@@ -108,35 +113,35 @@ export const postForm = async <T>(url: string, body: FormData, options: RequestC
|
||||
control.cleanup();
|
||||
}
|
||||
|
||||
const contentType = res.headers.get('content-type') || '';
|
||||
const isJson = contentType.includes('application/json');
|
||||
const payload = isJson ? await res.json().catch(() => undefined) : await res.text().catch(() => undefined);
|
||||
const contentType = res.headers.get('content-type') || ''; /* contentType 表示contentType。 */
|
||||
const isJson = contentType.includes('application/json'); /* isJson 表示isJson。 */
|
||||
const payload = isJson ? await res.json().catch(() => undefined /* 回调函数负责当前业务流程。 */) : await res.text().catch(() => undefined /* 回调函数负责当前业务流程。 */); /* payload 表示payload。 */
|
||||
|
||||
if (!res.ok) {
|
||||
if (res.status === 401) notifyAuthExpired();
|
||||
const message = errorMessageFromPayload(payload, res.status); // message 是上传失败时统一错误 DTO 提取出的说明。
|
||||
const err = new Error(message) as Error & { payload?: unknown };
|
||||
const err = new Error(message) as Error & { /* payload 表示payload。 */ payload?: unknown }; /* err 表示当前操作返回的错误。 */
|
||||
err.payload = payload;
|
||||
throw err;
|
||||
}
|
||||
|
||||
return payload as T;
|
||||
};
|
||||
}; /* postForm 表示postForm。 */
|
||||
|
||||
const controlledSignal = (external: AbortSignal | undefined, timeoutMs: number) => {
|
||||
const controller = new AbortController();
|
||||
const abortFromExternal = () => controller.abort(external?.reason);
|
||||
const controller = new AbortController(); /* controller 表示controller。 */
|
||||
const abortFromExternal = () => controller.abort(external?.reason); /* abortFromExternal 表示abortFromExternal。 */
|
||||
if (external?.aborted) abortFromExternal();
|
||||
else external?.addEventListener('abort', abortFromExternal, { once: true });
|
||||
const timer = globalThis.setTimeout(() => controller.abort(new DOMException('timeout', 'TimeoutError')), Math.max(1, timeoutMs));
|
||||
const timer = globalThis.setTimeout(() => controller.abort(new DOMException('timeout', 'TimeoutError')) /* 回调函数负责当前业务流程。 */, Math.max(1, timeoutMs)); /* timer 表示timer。 */
|
||||
return {
|
||||
signal: controller.signal,
|
||||
cleanup: () => {
|
||||
globalThis.clearTimeout(timer);
|
||||
external?.removeEventListener('abort', abortFromExternal);
|
||||
},
|
||||
} /* 回调函数负责当前业务流程。 */,
|
||||
};
|
||||
};
|
||||
}; /* controlledSignal 表示controlledSignal。 */
|
||||
|
||||
/** 判断响应体是否符合统一 HTTP 错误 DTO。 */
|
||||
const isApiErrorResponse = (payload: unknown): payload is ApiErrorResponse => {
|
||||
|
||||
+49
-49
@@ -2,48 +2,48 @@ import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { describe, expect, test } from 'vitest';
|
||||
|
||||
const repoRoot = resolve(__dirname);
|
||||
const repoRoot = resolve(__dirname); /* repoRoot 表示repoRoot。 */
|
||||
|
||||
const readFrontendFile = (relativePath: string) =>
|
||||
readFileSync(resolve(repoRoot, relativePath), 'utf8');
|
||||
readFileSync(resolve(repoRoot, relativePath), 'utf8'); /* readFrontendFile 表示readFrontendFile。 */
|
||||
|
||||
const extractSingleQuotedValues = (source: string, pattern: RegExp) => {
|
||||
const values = new Set<string>();
|
||||
for (const match of source.matchAll(pattern)) {
|
||||
const values = new Set<string>(); /* values 表示值集合。 */
|
||||
for (const match /* match 表示匹配结果。 */ of source.matchAll(pattern)) {
|
||||
values.add(match[1]);
|
||||
}
|
||||
return values;
|
||||
};
|
||||
}; /* extractSingleQuotedValues 表示extractSingleQuoted值集合。 */
|
||||
|
||||
describe('frontend navigation routing', () => {
|
||||
test('sidebar entries and App activeTab routes stay in sync', () => {
|
||||
const sidebar = readFrontendFile('components/Sidebar.tsx');
|
||||
const app = readFrontendFile('App.tsx');
|
||||
const sidebar = readFrontendFile('components/Sidebar.tsx'); /* sidebar 表示sidebar。 */
|
||||
const app = readFrontendFile('App.tsx'); /* app 表示app。 */
|
||||
|
||||
const sidebarIDs = extractSingleQuotedValues(sidebar, /id:\s*'([^']+)'/g);
|
||||
const appRouteIDs = extractSingleQuotedValues(app, /case\s+'([^']+)'/g);
|
||||
const sidebarIDs = extractSingleQuotedValues(sidebar, /id:\s*'([^']+)'/g); /* sidebarIDs 表示sidebarIDs。 */
|
||||
const appRouteIDs = extractSingleQuotedValues(app, /case\s+'([^']+)'/g); /* appRouteIDs 表示appRouteIDs。 */
|
||||
|
||||
expect([...sidebarIDs].sort()).toEqual([...appRouteIDs].sort());
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('active navigation uses the primary action blue', () => {
|
||||
const sidebar = readFrontendFile('components/Sidebar.tsx');
|
||||
const sidebar = readFrontendFile('components/Sidebar.tsx'); /* sidebar 表示sidebar。 */
|
||||
|
||||
expect(sidebar).toContain("'bg-brand text-white shadow-brand-active'");
|
||||
expect(sidebar).not.toContain("'bg-sky-500 text-white'");
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('logout button invalidates the backend session before clearing UI state', () => {
|
||||
const app = readFrontendFile('App.tsx');
|
||||
const app = readFrontendFile('App.tsx'); /* app 表示app。 */
|
||||
|
||||
expect(app).toContain('import { initializeAdmin, login, logout, verifySession }');
|
||||
expect(app).toContain('await logout();');
|
||||
expect(app).toContain('onLogout={handleLogout}');
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('settings page does not expose backend-inactive system controls', () => {
|
||||
const settings = readFrontendFile('components/Settings.tsx');
|
||||
const settingsConstants = readFrontendFile('app/features/settings/constants.ts');
|
||||
const settings = readFrontendFile('components/Settings.tsx'); /* settings 表示settings。 */
|
||||
const settingsConstants = readFrontendFile('app/features/settings/constants.ts'); /* settingsConstants 表示settingsConstants。 */
|
||||
|
||||
expect(settings).not.toContain('允许用户注册');
|
||||
expect(settings).not.toContain('显示默认登录信息');
|
||||
@@ -52,12 +52,12 @@ describe('frontend navigation routing', () => {
|
||||
expect(settings).not.toContain('默认自动回复内容');
|
||||
expect(settingsConstants).toContain('SETTINGS_SAVE_OMIT_KEYS');
|
||||
expect(settings).toContain('保存后需重启服务生效');
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('admin-only settings navigation is gated by session role', () => {
|
||||
const app = readFrontendFile('App.tsx');
|
||||
const sidebar = readFrontendFile('components/Sidebar.tsx');
|
||||
const settingsHook = readFrontendFile('app/features/settings/hooks.ts');
|
||||
const app = readFrontendFile('App.tsx'); /* app 表示app。 */
|
||||
const sidebar = readFrontendFile('components/Sidebar.tsx'); /* sidebar 表示sidebar。 */
|
||||
const settingsHook = readFrontendFile('app/features/settings/hooks.ts'); /* settingsHook 表示settingsHook。 */
|
||||
|
||||
expect(app).toContain('const [isAdmin, setIsAdmin] = useState(false)');
|
||||
expect(app).toContain('setIsAdmin(res.is_admin === true)');
|
||||
@@ -66,10 +66,10 @@ describe('frontend navigation routing', () => {
|
||||
expect(sidebar).toContain('isAdmin = false');
|
||||
expect(sidebar).toContain("...(isAdmin ? [{ id: 'settings'");
|
||||
expect(settingsHook).toContain('setLoadError');
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('captcha remote settings expose the reference privacy and fallback semantics', () => {
|
||||
const settings = readFrontendFile('components/Settings.tsx');
|
||||
const settings = readFrontendFile('components/Settings.tsx'); /* settings 表示settings。 */
|
||||
|
||||
expect(settings).toContain('远程过滑块配置');
|
||||
expect(settings).toContain("'captcha.remote_service_url'");
|
||||
@@ -77,12 +77,12 @@ describe('frontend navigation routing', () => {
|
||||
expect(settings).toContain("'captcha.remote_pass_cookies'");
|
||||
expect(settings).toContain('默认关闭');
|
||||
expect(settings).toContain('只有网络不可用或超时才回退本机引擎');
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('email notification config separates system and custom SMTP modes', () => {
|
||||
const notifications = readFrontendFile('components/Notifications.tsx');
|
||||
const notificationState = readFrontendFile('app/features/notifications/state.ts');
|
||||
const notificationModal = readFrontendFile('app/features/notifications/components/NotificationChannelModal.tsx');
|
||||
const notifications = readFrontendFile('components/Notifications.tsx'); /* notifications 表示notifications。 */
|
||||
const notificationState = readFrontendFile('app/features/notifications/state.ts'); /* notificationState 表示notificationState。 */
|
||||
const notificationModal = readFrontendFile('app/features/notifications/components/NotificationChannelModal.tsx'); /* notificationModal 表示notificationModal。 */
|
||||
|
||||
expect(notifications).toContain('interface NotificationsProps');
|
||||
expect(notifications).toContain('{isAdmin && <NotificationSmtpSettings');
|
||||
@@ -91,21 +91,21 @@ describe('frontend navigation routing', () => {
|
||||
expect(notificationModal).toContain('use_custom_smtp');
|
||||
expect(notificationState).not.toContain("key: 'from'");
|
||||
expect(notifications).not.toContain('注册验证码');
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('keyword reply UI matches contains-based backend behavior', () => {
|
||||
const rules = readFrontendFile('components/Rules.tsx');
|
||||
const rules = readFrontendFile('components/Rules.tsx'); /* rules 表示规则集合。 */
|
||||
|
||||
expect(rules).toContain('包含匹配');
|
||||
expect(rules).not.toContain('精确匹配');
|
||||
expect(rules).not.toContain('模糊包含');
|
||||
expect(rules).not.toContain('匹配类型');
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('vite proxy does not advertise removed backend routes', () => {
|
||||
const vite = readFrontendFile('vite.config.ts');
|
||||
const vite = readFrontendFile('vite.config.ts'); /* vite 表示vite。 */
|
||||
|
||||
for (const staleRoute of [
|
||||
for (const staleRoute /* staleRoute 表示staleRoute。 */ of [
|
||||
'/backup',
|
||||
'/logs',
|
||||
'/register',
|
||||
@@ -116,52 +116,52 @@ describe('frontend navigation routing', () => {
|
||||
]) {
|
||||
expect(vite).not.toContain(`'${staleRoute}'`);
|
||||
}
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('item delivery shortcut opens existing automation rule modal', () => {
|
||||
const rules = readFrontendFile('components/Rules.tsx');
|
||||
const existingRuleBranch = rules.match(/if \(rule\) \{([\s\S]*?)\} else \{/);
|
||||
const rules = readFrontendFile('components/Rules.tsx'); /* rules 表示规则集合。 */
|
||||
const existingRuleBranch = rules.match(/if \(rule\) \{([\s\S]*?)\} else \{/); /* existingRuleBranch 表示existing当前规则Branch。 */
|
||||
|
||||
expect(existingRuleBranch?.[1]).toContain('openAutomationRule(rule)');
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('item delivery shortcut is not marked handled before async open completes', () => {
|
||||
const rules = readFrontendFile('components/Rules.tsx');
|
||||
const rules = readFrontendFile('components/Rules.tsx'); /* rules 表示规则集合。 */
|
||||
|
||||
expect(rules).not.toContain('handledDeliveryTarget.current = initialDeliveryTarget.requestId');
|
||||
expect(rules).toContain('onDeliveryTargetHandled?.();');
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('automation editor keeps multiple delivery contents for normal products', () => {
|
||||
const rules = readFrontendFile('components/Rules.tsx');
|
||||
const rules = readFrontendFile('components/Rules.tsx'); /* rules 表示规则集合。 */
|
||||
|
||||
expect(rules).toContain('添加发货内容');
|
||||
expect(rules).toContain('{displayVariants.map((variant, index) => (');
|
||||
expect(rules).toContain(': variants.map(variant => ({');
|
||||
expect(rules).not.toContain(': (isMultiSpecRule ? variants : [variants[0]]).map');
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('batch publishing help explains card fields without required-field jargon', () => {
|
||||
const itemList = readFrontendFile('components/ItemList.tsx');
|
||||
const itemList = readFrontendFile('components/ItemList.tsx'); /* itemList 表示当前商品List。 */
|
||||
|
||||
expect(itemList).not.toContain('条件必填');
|
||||
expect(itemList).toContain('“付款后发送的卡密”怎么填');
|
||||
expect(itemList).toContain('101:1:0;102:2:3');
|
||||
expect(itemList).toContain('买家购买 3 件时会发送 6 份');
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('item publish image previews revoke object urls', () => {
|
||||
const itemList = readFrontendFile('components/ItemList.tsx');
|
||||
const itemList = readFrontendFile('components/ItemList.tsx'); /* itemList 表示当前商品List。 */
|
||||
|
||||
expect(itemList).toContain('setPublishImagePreviews');
|
||||
expect(itemList).toContain('URL.createObjectURL(file)');
|
||||
expect(itemList).toContain('URL.revokeObjectURL(preview.url)');
|
||||
expect(itemList).not.toContain('src={URL.createObjectURL(file)}');
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('QR verification removes the external link and clearly requires in-app risk verification', () => {
|
||||
const accounts = readFrontendFile('components/AccountList.tsx');
|
||||
const riskPanel = readFrontendFile('components/RiskVerificationPanel.tsx');
|
||||
const accounts = readFrontendFile('components/AccountList.tsx'); /* accounts 表示账号集合。 */
|
||||
const riskPanel = readFrontendFile('components/RiskVerificationPanel.tsx'); /* riskPanel 表示riskPanel。 */
|
||||
expect(accounts).not.toContain('href={verificationUrl}');
|
||||
expect(accounts).not.toContain('setVerificationUrl');
|
||||
expect(accounts).toContain('RiskVerificationPanel');
|
||||
@@ -171,18 +171,18 @@ describe('frontend navigation routing', () => {
|
||||
expect(riskPanel).not.toContain('我已在闲鱼 App 完成验证');
|
||||
expect(riskPanel).not.toContain('<button');
|
||||
expect(riskPanel).not.toContain('重试');
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('account editor exposes password-login refresh and never renders its verification URL', () => {
|
||||
const accounts = [
|
||||
readFrontendFile('components/AccountList.tsx'),
|
||||
readFrontendFile('app/features/accounts/components/AccountEditModal.tsx'),
|
||||
readFrontendFile('app/features/accounts/submoduleHooks.ts'),
|
||||
].join('\n');
|
||||
].join('\n'); /* accounts 表示账号集合。 */
|
||||
expect(accounts).toContain('passwordLogin({');
|
||||
expect(accounts).toContain('checkPasswordLoginStatus(sessionId, controller.signal)');
|
||||
expect(accounts).toContain('密码登录刷新授权');
|
||||
expect(accounts).toContain('账号已触发平台风控,需要完成人脸识别');
|
||||
expect(accounts).not.toContain('result.verification_url');
|
||||
});
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
@@ -2,27 +2,27 @@ import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { describe, expect, test } from 'vitest';
|
||||
|
||||
const source = (path: string) => readFileSync(resolve(__dirname, path), 'utf8');
|
||||
const source = (path: string) => readFileSync(resolve(__dirname, path), 'utf8'); /* source 表示source。 */
|
||||
|
||||
describe('responsive rules layout', () => {
|
||||
test('allows the rules page to shrink inside the sidebar layout', () => {
|
||||
const app = source('App.tsx');
|
||||
const rules = source('components/Rules.tsx');
|
||||
const app = source('App.tsx'); /* app 表示app。 */
|
||||
const rules = source('components/Rules.tsx'); /* rules 表示规则集合。 */
|
||||
expect(app).toContain('h-screen min-w-0 flex-1 overflow-x-hidden');
|
||||
expect(rules).toContain('min-w-0 space-y-8');
|
||||
expect(rules).toContain('xl:grid-cols-[minmax(270px,0.72fr)_minmax(0,1.28fr)]');
|
||||
expect(rules).not.toContain('2xl:grid-cols-[360px_1fr]');
|
||||
});
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
describe('rules summary counts', () => {
|
||||
test('uses server-side aggregate counts instead of the current page length', () => {
|
||||
const rules = source('components/Rules.tsx');
|
||||
const api = source('services/api.ts');
|
||||
const rules = source('components/Rules.tsx'); /* rules 表示规则集合。 */
|
||||
const api = source('services/api.ts'); /* api 表示api。 */
|
||||
expect(rules).toContain('automationTriggerCounts');
|
||||
expect(rules).toContain('{automationTriggerCounts[trigger] || 0}');
|
||||
expect(rules).toContain('筛选结果构成');
|
||||
expect(rules).not.toContain('rulesByTrigger[trigger].length');
|
||||
expect(api).toContain('trigger_counts');
|
||||
});
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
@@ -95,7 +95,9 @@ function hasChineseComment(sourceFile, node) {
|
||||
if (trailingRanges.some((range) => {
|
||||
// commentStartLine 是行尾注释起始所在的零基行号。
|
||||
const commentStartLine = sourceFile.getLineAndCharacterOfPosition(range.pos).line;
|
||||
return commentStartLine === startLine && HAN_PATTERN.test(sourceText.slice(range.pos, range.end));
|
||||
// commentOnFunctionEnd 允许多行回调在表达式末尾使用行尾块注释说明职责。
|
||||
const commentOnFunctionEnd = commentStartLine >= startLine && commentStartLine <= sourceFile.getLineAndCharacterOfPosition(anchor.end).line;
|
||||
return commentOnFunctionEnd && HAN_PATTERN.test(sourceText.slice(range.pos, range.end));
|
||||
})) {
|
||||
return true;
|
||||
}
|
||||
@@ -107,7 +109,8 @@ function hasChineseComment(sourceFile, node) {
|
||||
}
|
||||
// inlineSuffix 是节点结束位置紧邻的内联注释,用于支持循环变量和行尾字段注释。
|
||||
const inlineSuffix = sourceText.slice(node.end, Math.min(sourceText.length, node.end + 200));
|
||||
const suffixMatch = inlineSuffix.match(/^\s*(?:\/\*[\s\S]*?\*\/|\/\/[^\n]*)/);
|
||||
// wrappedSuffix 允许回调结束后先出现调用闭合符,再用块注释说明回调职责。
|
||||
const suffixMatch = inlineSuffix.match(/^\s*[),;]*\s*(?:\/\*[\s\S]*?\*\/|\/\/[^\n]*)/);
|
||||
if (suffixMatch && HAN_PATTERN.test(suffixMatch[0])) {
|
||||
return true;
|
||||
}
|
||||
@@ -184,6 +187,8 @@ function writeBaseline(filePath, findings) {
|
||||
|
||||
// readBaseline 读取历史问题并建立快速查询集合。
|
||||
function readBaseline(filePath) {
|
||||
// baselineMissing 表示最终严格门禁已删除历史基线文件,此时必须按空集合执行。
|
||||
if (!fs.existsSync(filePath)) return new Set();
|
||||
// baselineText 是基线文件的 JSON 文本。
|
||||
const baselineText = fs.readFileSync(filePath, "utf8");
|
||||
// baselineFindings 是反序列化后的历史问题数组。
|
||||
|
||||
@@ -21,7 +21,7 @@ test('maps AMap POI fields to the publish location shape', () => {
|
||||
poi_name: '人民广场',
|
||||
province: '上海市',
|
||||
});
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('drops incomplete or invalid AMap POIs', () => {
|
||||
expect(amapPOIToPublishLocation({
|
||||
@@ -32,4 +32,4 @@ test('drops incomplete or invalid AMap POIs', () => {
|
||||
cityname: '上海市',
|
||||
location: { lng: 0, lat: 31.2 },
|
||||
})).toBeNull();
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
@@ -1,33 +1,46 @@
|
||||
import type { PublishLocation } from './api';
|
||||
|
||||
const AMAP_SCRIPT_ID = 'ydisks-amap-js-api';
|
||||
const AMAP_SCRIPT_ID = 'ydisks-amap-js-api'; /* AMAP_SCRIPT_ID 表示AMAPSCRIPTID。 */
|
||||
// 高德 JS API 的 Key 是前端公开 Key;部署时可通过 VITE_AMAP_JS_KEY 覆盖。
|
||||
const DEFAULT_AMAP_JS_KEY = 'c9b68d4ce9a2a97f22a4a439404488ca';
|
||||
|
||||
export interface AMapLocationValue {
|
||||
lng: number;
|
||||
lat: number;
|
||||
// lng 表示lng。
|
||||
lng: number;
|
||||
// lat 表示lat。
|
||||
lat: number;
|
||||
}
|
||||
|
||||
export interface AMapPOI {
|
||||
id?: string;
|
||||
name?: string;
|
||||
address?: string;
|
||||
adname?: string;
|
||||
cityname?: string;
|
||||
adcode?: string | number;
|
||||
pname?: string;
|
||||
location?: AMapLocationValue;
|
||||
// id 表示id。
|
||||
id?: string;
|
||||
// name 表示name。
|
||||
name?: string;
|
||||
// address 表示address。
|
||||
address?: string;
|
||||
// adname 表示adname。
|
||||
adname?: string;
|
||||
// cityname 表示cityname。
|
||||
cityname?: string;
|
||||
// adcode 表示adcode。
|
||||
adcode?: string | number;
|
||||
// pname 表示pname。
|
||||
pname?: string;
|
||||
// location 表示location。
|
||||
location?: AMapLocationValue;
|
||||
}
|
||||
|
||||
interface AMapPlaceSearchResult {
|
||||
poiList?: {
|
||||
pois?: AMapPOI[];
|
||||
// poiList 表示poiList。
|
||||
poiList?: {
|
||||
// pois 表示pois。
|
||||
pois?: AMapPOI[];
|
||||
};
|
||||
}
|
||||
|
||||
interface AMapPlaceSearch {
|
||||
searchNearBy(
|
||||
// searchNearBy 表示searchNearBy。
|
||||
searchNearBy(
|
||||
keyword: string,
|
||||
center: [number, number],
|
||||
radius: number,
|
||||
@@ -36,42 +49,47 @@ interface AMapPlaceSearch {
|
||||
}
|
||||
|
||||
interface AMapAPI {
|
||||
PlaceSearch: new (options: { extensions: 'all'; pageSize: number }) => AMapPlaceSearch;
|
||||
// PlaceSearch 表示PlaceSearch。
|
||||
PlaceSearch: new (options: { /* extensions 表示extensions。 */ extensions: 'all'; /* pageSize 表示pageSize。 */ pageSize: number }) => AMapPlaceSearch;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
AMap?: AMapAPI;
|
||||
__ydisksAmapLoaded?: () => void;
|
||||
// AMap 表示AMap。
|
||||
AMap?: AMapAPI;
|
||||
// __ydisksAmapLoaded 表示ydisksAmapLoaded。
|
||||
__ydisksAmapLoaded?: () => void;
|
||||
}
|
||||
|
||||
interface ImportMetaEnv {
|
||||
readonly VITE_AMAP_JS_KEY?: string;
|
||||
// VITE_AMAP_JS_KEY 表示VITEAMAPJSKEY。
|
||||
readonly VITE_AMAP_JS_KEY?: string;
|
||||
}
|
||||
|
||||
interface ImportMeta {
|
||||
readonly env: ImportMetaEnv;
|
||||
// env 表示env。
|
||||
readonly env: ImportMetaEnv;
|
||||
}
|
||||
}
|
||||
|
||||
let amapLoadPromise: Promise<AMapAPI> | null = null;
|
||||
let amapLoadPromise: Promise<AMapAPI> | null = null; /* amapLoadPromise 表示amapLoadPromise。 */
|
||||
|
||||
const configuredAmapKey = (): string => {
|
||||
const key = import.meta.env.VITE_AMAP_JS_KEY?.trim();
|
||||
const key = import.meta.env.VITE_AMAP_JS_KEY?.trim(); /* key 表示key。 */
|
||||
return key || DEFAULT_AMAP_JS_KEY;
|
||||
};
|
||||
}; /* configuredAmapKey 表示configuredAmapKey。 */
|
||||
|
||||
const loadAMap = (): Promise<AMapAPI> => {
|
||||
if (window.AMap) return Promise.resolve(window.AMap);
|
||||
if (amapLoadPromise) return amapLoadPromise;
|
||||
|
||||
amapLoadPromise = new Promise<AMapAPI>((resolve, reject) => {
|
||||
const existing = document.getElementById(AMAP_SCRIPT_ID) as HTMLScriptElement | null;
|
||||
const script = existing || document.createElement('script');
|
||||
const existing = document.getElementById(AMAP_SCRIPT_ID) as HTMLScriptElement | null; /* existing 表示existing。 */
|
||||
const script = existing || document.createElement('script'); /* script 表示script。 */
|
||||
const cleanup = () => {
|
||||
window.__ydisksAmapLoaded = undefined;
|
||||
window.clearTimeout(timeout);
|
||||
};
|
||||
}; /* cleanup 表示cleanup。 */
|
||||
const finish = () => {
|
||||
if (window.AMap) {
|
||||
cleanup();
|
||||
@@ -80,11 +98,11 @@ const loadAMap = (): Promise<AMapAPI> => {
|
||||
cleanup();
|
||||
reject(new Error('高德地图 API 加载完成但未找到 AMap 对象'));
|
||||
}
|
||||
};
|
||||
}; /* finish 表示finish。 */
|
||||
const timeout = window.setTimeout(() => {
|
||||
cleanup();
|
||||
reject(new Error('高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置'));
|
||||
}, 15_000);
|
||||
} /* 回调函数负责当前业务流程。 */, 15_000); /* timeout 表示timeout。 */
|
||||
|
||||
window.__ydisksAmapLoaded = finish;
|
||||
script.id = AMAP_SCRIPT_ID;
|
||||
@@ -93,22 +111,22 @@ const loadAMap = (): Promise<AMapAPI> => {
|
||||
script.onerror = () => {
|
||||
cleanup();
|
||||
reject(new Error('高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置'));
|
||||
};
|
||||
} /* 回调函数负责当前业务流程。 */;
|
||||
if (!existing) document.head.appendChild(script);
|
||||
}).catch(error => {
|
||||
} /* 回调函数负责当前业务流程。 */).catch(error => {
|
||||
amapLoadPromise = null;
|
||||
throw error;
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
return amapLoadPromise;
|
||||
};
|
||||
}; /* loadAMap 表示loadAMap。 */
|
||||
|
||||
const validCoordinate = (value: number): boolean => Number.isFinite(value) && value !== 0;
|
||||
const validCoordinate = (value: number): boolean => Number.isFinite(value) && value !== 0; /* validCoordinate 表示validCoordinate。 */
|
||||
|
||||
// 字段映射与闲鱼网页版发布页一致:adcode → divisionId,name → poi,pname/cityname/adname → 行政区。
|
||||
export const amapPOIToPublishLocation = (poi: AMapPOI): PublishLocation | null => {
|
||||
const longitude = Number(poi.location?.lng);
|
||||
const latitude = Number(poi.location?.lat);
|
||||
const longitude = Number(poi.location?.lng); /* longitude 表示longitude。 */
|
||||
const latitude = Number(poi.location?.lat); /* latitude 表示latitude。 */
|
||||
const location: PublishLocation = {
|
||||
area: String(poi.adname || '').trim(),
|
||||
city: String(poi.cityname || '').trim(),
|
||||
@@ -118,7 +136,7 @@ export const amapPOIToPublishLocation = (poi: AMapPOI): PublishLocation | null =
|
||||
poi_id: String(poi.id || '').trim(),
|
||||
poi_name: String(poi.name || '').trim(),
|
||||
province: String(poi.pname || '').trim(),
|
||||
};
|
||||
}; /* location 表示location。 */
|
||||
if (!location.division_id || !location.province || !location.city || !location.poi_id || !location.poi_name) {
|
||||
return null;
|
||||
}
|
||||
@@ -132,9 +150,9 @@ export const getPublishLocations = async (longitude: number, latitude: number):
|
||||
if (!validCoordinate(longitude) || !validCoordinate(latitude) || longitude < -180 || longitude > 180 || latitude < -90 || latitude > 90) {
|
||||
throw new Error('经纬度无效');
|
||||
}
|
||||
const amap = await loadAMap();
|
||||
const amap = await loadAMap(); /* amap 表示amap。 */
|
||||
return new Promise<PublishLocation[]>((resolve, reject) => {
|
||||
const placeSearch = new amap.PlaceSearch({ extensions: 'all', pageSize: 10 });
|
||||
const placeSearch = new amap.PlaceSearch({ extensions: 'all', pageSize: 10 }); /* placeSearch 表示placeSearch。 */
|
||||
placeSearch.searchNearBy('', [longitude, latitude], 1_000, (status, result) => {
|
||||
if (status !== 'complete') {
|
||||
if (status === 'no_data') {
|
||||
@@ -146,8 +164,8 @@ export const getPublishLocations = async (longitude: number, latitude: number):
|
||||
}
|
||||
const locations = (result?.poiList?.pois || [])
|
||||
.map(amapPOIToPublishLocation)
|
||||
.filter((location): location is PublishLocation => location !== null);
|
||||
.filter((location): location is PublishLocation => location !== null /* 回调函数负责当前业务流程。 */); /* locations 表示locations。 */
|
||||
resolve(locations);
|
||||
});
|
||||
});
|
||||
};
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
}; /* getPublishLocations 表示getPublishLocations。 */
|
||||
+104
-104
@@ -45,32 +45,32 @@ import {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('updateSystemSettings uses one atomic bulk request', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true }));
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
await updateSystemSettings({ theme_color: 'blue', renewal_log_retention_days: 15 });
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/v1/settings/system', expect.objectContaining({ method: 'PUT', credentials: 'include' }));
|
||||
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();
|
||||
const controller = new AbortController(); /* controller 表示controller。 */
|
||||
|
||||
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' }] }))
|
||||
.mockResolvedValueOnce(jsonResponse({ messages: [{ account_id: 'a1', chat_id: 'c1', id: 1 }] }))
|
||||
.mockImplementation(() => Promise.resolve(jsonResponse({ success: true, message: { id: 2 } })));
|
||||
.mockImplementation(() => Promise.resolve(jsonResponse({ success: true, message: { id: 2 } })) /* 回调函数负责当前业务流程。 */); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
await getChatSessions('a1');
|
||||
await getChatMessages('a1', 'c1', 9);
|
||||
@@ -80,7 +80,7 @@ test('chat APIs preserve account and conversation scope', async () => {
|
||||
expect(fetchMock.mock.calls[1][0]).toBe('/api/v1/chat/messages?account_id=a1&chat_id=c1&before_id=9');
|
||||
expect(JSON.parse(fetchMock.mock.calls[2][1].body)).toMatchObject({ account_id: 'a1', chat_id: 'c1', buyer_id: 'b1' });
|
||||
expect(JSON.parse(fetchMock.mock.calls[3][1].body)).toEqual({ account_id: 'a1', chat_id: 'c1' });
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('Chat 会话、消息和发送 API 转发外部取消信号', async () => {
|
||||
// fetchMock 验证会话切换、消息分页和文本/图片发送共享取消控制能力。
|
||||
@@ -103,10 +103,10 @@ test('Chat 会话、消息和发送 API 转发外部取消信号', async () => {
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(3, '/api/v1/chat/messages', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(4, '/api/v1/chat/images', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(5, '/api/v1/chat/read', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('account task APIs keep rating and polish account-scoped', async () => {
|
||||
const fetchMock = vi.fn().mockImplementation(() => Promise.resolve(jsonResponse({ success: true, summary: { task_type: 'auto_rate' } })));
|
||||
const fetchMock = vi.fn().mockImplementation(() => Promise.resolve(jsonResponse({ success: true, summary: { task_type: 'auto_rate' } })) /* 回调函数负责当前业务流程。 */); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
await updateAccountTaskSettings('a1', {
|
||||
account_id: 'a1', auto_rate_enabled: true, rate_content: '交易愉快',
|
||||
@@ -117,7 +117,7 @@ test('account task APIs keep rating and polish account-scoped', async () => {
|
||||
expect(fetchMock.mock.calls[0][1].method).toBe('PUT');
|
||||
expect(fetchMock.mock.calls[1][0]).toBe('/api/v1/account-tasks/a1/run');
|
||||
expect(JSON.parse(fetchMock.mock.calls[1][1].body)).toEqual({ task_type: 'auto_rate' });
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('账号自动任务 API 转发外部取消信号', async () => {
|
||||
// fetchMock 验证读取、保存和执行账号任务都支持请求取消。
|
||||
@@ -128,26 +128,26 @@ test('账号自动任务 API 转发外部取消信号', async () => {
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
// controller 是 AccountAutomation feature Hook 使用的请求控制器。
|
||||
const controller = new AbortController();
|
||||
const settings = { account_id: 'a1', auto_rate_enabled: true, rate_content: '交易愉快', auto_polish_enabled: false, polish_time: '03:00' };
|
||||
const settings = { account_id: 'a1', auto_rate_enabled: true, rate_content: '交易愉快', auto_polish_enabled: false, polish_time: '03:00' }; /* settings 表示settings。 */
|
||||
await getAccountTaskSettings('a1', { signal: controller.signal });
|
||||
await updateAccountTaskSettings('a1', settings, { signal: controller.signal });
|
||||
await runAccountTask('a1', 'auto_rate', { signal: controller.signal });
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(1, '/api/v1/account-tasks/a1', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(2, '/api/v1/account-tasks/a1', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(3, '/api/v1/account-tasks/a1/run', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('getItemPublishBatches unwraps persisted batch list', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ batches: [{ id: 'batch-1', status: 'running' }] }));
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ batches: [{ id: 'batch-1', status: 'running' }] })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
await expect(getItemPublishBatches(10)).resolves.toEqual([{ id: 'batch-1', status: 'running' }]);
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/v1/items/publish-batches?limit=10', expect.objectContaining({ credentials: 'include' }));
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('automation issue APIs expose and resolve quarantined work', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
.mockResolvedValueOnce(jsonResponse({ runs: [{ id: 1 }], pending_tasks: [{ id: 2 }] }))
|
||||
.mockImplementation(() => Promise.resolve(jsonResponse({ success: true })));
|
||||
.mockImplementation(() => Promise.resolve(jsonResponse({ success: true })) /* 回调函数负责当前业务流程。 */); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
await expect(getAutomationIssues()).resolves.toEqual({ runs: [{ id: 1 }], pending_tasks: [{ id: 2 }] });
|
||||
await resolveAutomationRun(1, 'continue');
|
||||
@@ -155,47 +155,47 @@ test('automation issue APIs expose and resolve quarantined work', async () => {
|
||||
expect(fetchMock.mock.calls[1][0]).toBe('/api/v1/automation-runs/1/resolve');
|
||||
expect(JSON.parse(fetchMock.mock.calls[1][1].body)).toEqual({ resolution: 'continue' });
|
||||
expect(fetchMock.mock.calls[2][0]).toBe('/api/v1/automation-pending-tasks/2/resolve');
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('order multipart requests use the shared authenticated form request path', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true }));
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
await syncOrders('acc1', 'pending_ship');
|
||||
await importOrders(new FormData());
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(1, '/api/v1/orders/refresh', expect.objectContaining({ method: 'POST', credentials: 'include', body: expect.any(FormData) }));
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(2, '/api/v1/orders/import', expect.objectContaining({ method: 'POST', credentials: 'include', body: expect.any(FormData) }));
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('legacy notification channel aliases are normalized for the editor', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse([{ id: 1, name: '旧飞书', type: 'lark', config: 'not-json', enabled: true }])));
|
||||
const result = await getNotificationChannels();
|
||||
const result = await getNotificationChannels(); /* result 表示处理结果。 */
|
||||
expect(result.data?.[0]).toMatchObject({ type: 'feishu', config: {} });
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
const jsonResponse = (body: unknown) => new Response(JSON.stringify(body), {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
});
|
||||
}); /* jsonResponse 表示json接口响应结果。 */
|
||||
|
||||
test('getOrders normalizes backend order fields', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({
|
||||
orders: [{ order_id: 'o1', order_status: 'shipped', quantity: '2' }],
|
||||
total: 1,
|
||||
}));
|
||||
})); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
const result = await getOrders(undefined, 'all', 1, 20, ' buyer ');
|
||||
const result = await getOrders(undefined, 'all', 1, 20, ' buyer '); /* result 表示处理结果。 */
|
||||
expect(result.data[0]).toMatchObject({ id: 'o1', status: 'shipped', quantity: 2 });
|
||||
expect(result.total).toBe(1);
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/v1/orders?page=1&page_size=20&search=buyer', expect.objectContaining({ method: 'GET' }));
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('getOrders maps unsupported backend statuses to unknown', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({
|
||||
data: [{ order_id: 'o-unknown', order_status: 'legacy_status' }],
|
||||
})));
|
||||
const result = await getOrders();
|
||||
const result = await getOrders(); /* result 表示处理结果。 */
|
||||
expect(result.data[0].status).toBe('unknown');
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('订单查询和导入 API 转发外部取消信号', async () => {
|
||||
// fetchMock 是同时验证订单查询和文件上传请求控制参数的替身。
|
||||
@@ -209,7 +209,7 @@ test('订单查询和导入 API 转发外部取消信号', async () => {
|
||||
await importOrders(new FormData(), { signal: controller.signal });
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(1, '/api/v1/orders?page=1&page_size=20', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(2, '/api/v1/orders/import', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('Dashboard 统计 API 转发外部取消信号', async () => {
|
||||
// fetchMock 验证 Dashboard 的概览、趋势和订单明细共用同一个取消信号。
|
||||
@@ -229,7 +229,7 @@ test('Dashboard 统计 API 转发外部取消信号', async () => {
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(1, '/api/v1/analytics/dashboard', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(3, expect.stringContaining('/api/v1/analytics/orders?'), expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(4, expect.stringContaining('/api/v1/analytics/orders/valid?'), expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('Settings 配置、模型和凭据 API 转发外部取消信号', async () => {
|
||||
// fetchMock 验证 Settings 的读取、模型发现和凭据保存共享取消控制能力。
|
||||
@@ -249,7 +249,7 @@ test('Settings 配置、模型和凭据 API 转发外部取消信号', async ()
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(2, '/api/v1/settings/ai-models', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(3, '/api/v1/session', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(4, '/api/v1/session/credentials', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('通知渠道和 SMTP API 转发外部取消信号', async () => {
|
||||
// fetchMock 验证渠道读取、保存和 SMTP 读写都支持取消控制。
|
||||
@@ -269,7 +269,7 @@ test('通知渠道和 SMTP API 转发外部取消信号', async () => {
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(2, '/api/v1/notifications/channels/channel-1', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(3, '/api/v1/settings/system', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(4, '/api/v1/settings/system', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('getShippingRulesPage sends filters and preserves pagination metadata', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({
|
||||
@@ -279,7 +279,7 @@ test('getShippingRulesPage sends filters and preserves pagination metadata', asy
|
||||
page_size: 20,
|
||||
total_pages: 2,
|
||||
trigger_counts: { order_paid: 8, buyer_reviewed: 7, review_missing_timeout: 6 },
|
||||
}));
|
||||
})); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
const result = await getShippingRulesPage({
|
||||
@@ -289,7 +289,7 @@ test('getShippingRulesPage sends filters and preserves pagination metadata', asy
|
||||
search: ' 商品 ',
|
||||
page: 2,
|
||||
pageSize: 20,
|
||||
});
|
||||
}); /* result 表示处理结果。 */
|
||||
|
||||
expect(result).toMatchObject({
|
||||
total: 21,
|
||||
@@ -303,59 +303,59 @@ test('getShippingRulesPage sends filters and preserves pagination metadata', asy
|
||||
'/api/v1/automation-rules?page=2&page_size=20&cookie_id=acc1&trigger_type=order_paid&enabled=false&search=%E5%95%86%E5%93%81',
|
||||
expect.objectContaining({ method: 'GET', credentials: 'include' }),
|
||||
);
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('getValidOrders accepts wrapped responses', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({
|
||||
orders: [{ order_id: 'o2', order_status: 'completed', quantity: '3' }],
|
||||
}));
|
||||
})); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
vi.spyOn(Date.prototype, 'getTimezoneOffset').mockReturnValue(-480);
|
||||
const result = await getValidOrders({ start_date: '2026-01-01', end_date: '2026-01-02' });
|
||||
const result = await getValidOrders({ start_date: '2026-01-01', end_date: '2026-01-02' }); /* result 表示处理结果。 */
|
||||
expect(result).toEqual({
|
||||
orders: [expect.objectContaining({ id: 'o2', status: 'completed', quantity: 3 })],
|
||||
total: 1,
|
||||
truncated: false,
|
||||
});
|
||||
expect(fetchMock.mock.calls[0][0]).toContain('timezone_offset_minutes=480');
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('getOrderAnalytics sends the browser timezone offset', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ revenue_stats: {}, daily_stats: [], status_stats: [], city_stats: [] }));
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ revenue_stats: {}, daily_stats: [], status_stats: [], city_stats: [] })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
vi.spyOn(Date.prototype, 'getTimezoneOffset').mockReturnValue(-330);
|
||||
await getOrderAnalytics({ start_date: '2026-01-01', end_date: '2026-01-02' });
|
||||
expect(fetchMock.mock.calls[0][0]).toContain('timezone_offset_minutes=330');
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('paid orders are normalized to pending shipment', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({ data: [{ order_id: 'o-paid', order_status: 'paid' }] })));
|
||||
const result = await getOrders();
|
||||
const result = await getOrders(); /* result 表示处理结果。 */
|
||||
expect(result.data[0].status).toBe('pending_ship');
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('completeQRVerification sends only the immutable target account', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true, account_id: 'acc1' }));
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true, account_id: 'acc1' })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
await completeQRVerification('session-1', 'acc1');
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/v1/qr-login/complete-verification/session-1', expect.objectContaining({
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ target_account_id: 'acc1' }),
|
||||
}));
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('deleteItemPublishBatch removes an abandoned preview', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true }));
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
await deleteItemPublishBatch('preview-1');
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/v1/items/publish-batches/preview-1', expect.objectContaining({
|
||||
method: 'DELETE',
|
||||
credentials: 'include',
|
||||
}));
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('publishItem allows virtual publishing without an optional location', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true }));
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
await publishItem({
|
||||
cookie_id: 'acc1',
|
||||
@@ -366,9 +366,9 @@ test('publishItem allows virtual publishing without an optional location', async
|
||||
postage_mode: 'none',
|
||||
images: [],
|
||||
});
|
||||
const body = fetchMock.mock.calls[0][1].body as FormData;
|
||||
const body = fetchMock.mock.calls[0][1].body as FormData; /* body 表示请求体。 */
|
||||
expect(body.get('location')).toBeNull();
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('getItems normalizes multi-spec flags from backend values', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse([{
|
||||
@@ -385,7 +385,7 @@ test('getItems normalizes multi-spec flags from backend values', async () => {
|
||||
multi_quantity_delivery: 1,
|
||||
}])));
|
||||
|
||||
const items = await getItems();
|
||||
const items = await getItems(); /* items 表示商品集合。 */
|
||||
expect(items[0]).toMatchObject({
|
||||
id: 'cookie-1-item-1',
|
||||
is_multi_spec: false,
|
||||
@@ -398,10 +398,10 @@ test('getItems normalizes multi-spec flags from backend values', async () => {
|
||||
is_multi_qty_ship: true,
|
||||
multi_quantity_delivery: true,
|
||||
});
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('getItems forwards the selected account filter', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse([]));
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse([])); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await getItems('account-2');
|
||||
@@ -410,7 +410,7 @@ test('getItems forwards the selected account filter', async () => {
|
||||
method: 'GET',
|
||||
credentials: 'include',
|
||||
}));
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('getSystemSettings normalizes numeric renewal retention', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({
|
||||
@@ -418,13 +418,13 @@ test('getSystemSettings normalizes numeric renewal retention', async () => {
|
||||
renewal_log_retention_days: 'invalid',
|
||||
})));
|
||||
|
||||
const settings = await getSystemSettings();
|
||||
const settings = await getSystemSettings(); /* settings 表示settings。 */
|
||||
expect(settings.ai_model).toBe('qwen-plus');
|
||||
expect(settings.renewal_log_retention_days).toBe(10);
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('logout calls backend session invalidation route', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true }));
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await logout();
|
||||
@@ -433,10 +433,10 @@ test('logout calls backend session invalidation route', async () => {
|
||||
credentials: 'include',
|
||||
}));
|
||||
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({});
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('account cookie APIs include login_method when provided', async () => {
|
||||
const fetchMock = vi.fn().mockImplementation(() => Promise.resolve(jsonResponse({ success: true })));
|
||||
const fetchMock = vi.fn().mockImplementation(() => Promise.resolve(jsonResponse({ success: true })) /* 回调函数负责当前业务流程。 */); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await addAccount('acc1', 'unb=acc1', 'qr_scan');
|
||||
@@ -460,10 +460,10 @@ test('account cookie APIs include login_method when provided', async () => {
|
||||
value: 'unb=acc1; x=1',
|
||||
login_method: 'qr_scan',
|
||||
});
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('account editor settings use one aggregate request', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true }));
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
await updateAccountSettings('acc1', {
|
||||
remark: 'main', auto_confirm: false, pause_duration: 5,
|
||||
@@ -475,7 +475,7 @@ test('account editor settings use one aggregate request', async () => {
|
||||
remark: 'main', auto_confirm: false, pause_duration: 5,
|
||||
username: 'user', show_browser: true, channel_ids: [1, 2],
|
||||
});
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('getAccountDetails normalizes show_browser and never exposes password', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse([{
|
||||
@@ -491,7 +491,7 @@ test('getAccountDetails normalizes show_browser and never exposes password', asy
|
||||
login_password: 'should-not-leak',
|
||||
}])));
|
||||
|
||||
const accounts = await getAccountDetails();
|
||||
const accounts = await getAccountDetails(); /* accounts 表示账号集合。 */
|
||||
expect(accounts[0]).toMatchObject({
|
||||
id: 'acc1',
|
||||
username: 'login-user',
|
||||
@@ -500,10 +500,10 @@ test('getAccountDetails normalizes show_browser and never exposes password', asy
|
||||
paused_until: 1780000000,
|
||||
paused: true,
|
||||
});
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('updateAccountLoginInfo sends exactly provided fields', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true }));
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await updateAccountLoginInfo('acc1', { username: 'login-user', show_browser: false });
|
||||
@@ -515,10 +515,10 @@ test('updateAccountLoginInfo sends exactly provided fields', async () => {
|
||||
username: 'login-user',
|
||||
show_browser: false,
|
||||
});
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('updateAccountLoginInfo can request explicit password clearing', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true }));
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await updateAccountLoginInfo('acc1', { username: 'login-user', clear_password: true, show_browser: false });
|
||||
@@ -527,10 +527,10 @@ test('updateAccountLoginInfo can request explicit password clearing', async () =
|
||||
clear_password: true,
|
||||
show_browser: false,
|
||||
});
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('updateItem sends only the fields selected by the editor', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true }));
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await updateItem('acc1', 'item1', { item_title: '改名商品' });
|
||||
@@ -541,13 +541,13 @@ test('updateItem sends only the fields selected by the editor', async () => {
|
||||
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({
|
||||
item_title: '改名商品',
|
||||
});
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('password login service uses upstream-compatible routes', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true, session_id: 'sid', status: 'processing' }))
|
||||
.mockResolvedValueOnce(jsonResponse({ status: 'success', account_id: 'acc1', cookie_count: 2 }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true }));
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await passwordLogin({ account_id: 'acc1', account: 'u', password: 'p' });
|
||||
@@ -561,13 +561,13 @@ test('password login service uses upstream-compatible routes', async () => {
|
||||
password: 'p',
|
||||
});
|
||||
|
||||
const status = await checkPasswordLoginStatus('sid');
|
||||
const status = await checkPasswordLoginStatus('sid'); /* status 表示status。 */
|
||||
expect(status.status).toBe('success');
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(2, '/api/v1/password-login/check/sid', expect.objectContaining({ method: 'GET' }));
|
||||
|
||||
await cancelPasswordLogin('sid');
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(3, '/api/v1/password-login/cancel/sid', expect.objectContaining({ method: 'DELETE' }));
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('账号编辑子模块请求支持取消过期响应', async () => {
|
||||
// fetchMock 是验证请求取消信号透传的测试替身。
|
||||
@@ -576,7 +576,7 @@ test('账号编辑子模块请求支持取消过期响应', async () => {
|
||||
.mockResolvedValueOnce(jsonResponse({ ai_enabled: true }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true, session_id: 'sid' }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
const controller = new AbortController();
|
||||
const controller = new AbortController(); /* controller 表示controller。 */
|
||||
|
||||
await getLongLoginSettings('acc1', { signal: controller.signal });
|
||||
await getAccountAISettings('acc1', { signal: controller.signal });
|
||||
@@ -585,7 +585,7 @@ test('账号编辑子模块请求支持取消过期响应', async () => {
|
||||
expect(fetchMock.mock.calls[0][1].signal).toBeInstanceOf(AbortSignal);
|
||||
expect(fetchMock.mock.calls[1][1].signal).toBeInstanceOf(AbortSignal);
|
||||
expect(fetchMock.mock.calls[2][1].signal).toBeInstanceOf(AbortSignal);
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('getShippingRules exposes buyer reviewed gift rules as automation rules', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse([{
|
||||
@@ -610,7 +610,7 @@ test('getShippingRules exposes buyer reviewed gift rules as automation rules', a
|
||||
}],
|
||||
}])));
|
||||
|
||||
const rules = await getShippingRules();
|
||||
const rules = await getShippingRules(); /* rules 表示规则集合。 */
|
||||
expect(rules[0]).toMatchObject({
|
||||
id: '12',
|
||||
trigger_type: 'buyer_reviewed',
|
||||
@@ -622,7 +622,7 @@ test('getShippingRules exposes buyer reviewed gift rules as automation rules', a
|
||||
spec_value: '赠品',
|
||||
card_id: 7,
|
||||
});
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('getReplyRules labels keyword matching according to engine contains behavior', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse([{
|
||||
@@ -631,10 +631,10 @@ test('getReplyRules labels keyword matching according to engine contains behavio
|
||||
reply: '马上安排',
|
||||
type: 'image',
|
||||
image_url: 'https://img.example/reply.png',
|
||||
}]));
|
||||
}])); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
const rules = await getReplyRules('acc1');
|
||||
const rules = await getReplyRules('acc1'); /* rules 表示规则集合。 */
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/v1/reply-rules/acc1/typed', expect.objectContaining({ method: 'GET' }));
|
||||
expect(rules[0]).toMatchObject({
|
||||
id: '42',
|
||||
@@ -644,10 +644,10 @@ test('getReplyRules labels keyword matching according to engine contains behavio
|
||||
type: 'image',
|
||||
image_url: 'https://img.example/reply.png',
|
||||
});
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('updateReplyRule preserves keyword image metadata when saving text edits', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true }));
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await updateReplyRule({ id: '42', keyword: '发货', reply_content: '稍后安排', item_id: 'item-1' }, 'acc1');
|
||||
@@ -660,20 +660,20 @@ test('updateReplyRule preserves keyword image metadata when saving text edits',
|
||||
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({
|
||||
keyword: '发货', reply: '稍后安排', item_id: 'item-1', type: 'text', image_url: '',
|
||||
});
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('updateReplyRule clears stale content when switching reply type', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true }));
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await updateReplyRule({ id: '42', keyword: '发货', type: 'image', image_url: 'https://img.example/new.png' }, 'acc1');
|
||||
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({
|
||||
keyword: '发货', reply: '', item_id: '', type: 'image', image_url: 'https://img.example/new.png',
|
||||
});
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('deleteReplyRule deletes one stable keyword row instead of replacing the list', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true }));
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await deleteReplyRule('42', 'acc1');
|
||||
@@ -682,10 +682,10 @@ test('deleteReplyRule deletes one stable keyword row instead of replacing the li
|
||||
method: 'DELETE',
|
||||
credentials: 'include',
|
||||
}));
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('createNotificationChannel persists email recipient as to_email config', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true }));
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await createNotificationChannel({
|
||||
@@ -700,16 +700,16 @@ test('createNotificationChannel persists email recipient as to_email config', as
|
||||
},
|
||||
});
|
||||
|
||||
const body = JSON.parse(fetchMock.mock.calls[0][1].body);
|
||||
const body = JSON.parse(fetchMock.mock.calls[0][1].body); /* body 表示请求体。 */
|
||||
expect(body.type).toBe('email');
|
||||
expect(JSON.parse(body.config)).toMatchObject({
|
||||
to_email: 'to@example.com',
|
||||
});
|
||||
expect(JSON.parse(body.config)).not.toHaveProperty('from');
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('createNotificationChannel allows email channel to rely on system SMTP settings', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true }));
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await createNotificationChannel({
|
||||
@@ -720,15 +720,15 @@ test('createNotificationChannel allows email channel to rely on system SMTP sett
|
||||
},
|
||||
});
|
||||
|
||||
const body = JSON.parse(fetchMock.mock.calls[0][1].body);
|
||||
const body = JSON.parse(fetchMock.mock.calls[0][1].body); /* body 表示请求体。 */
|
||||
expect(body.type).toBe('email');
|
||||
expect(JSON.parse(body.config)).toEqual({
|
||||
to_email: 'to@example.com',
|
||||
});
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('updateNotificationChannel supports partial enabled updates', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true }));
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await updateNotificationChannel('7', { enabled: false });
|
||||
@@ -740,10 +740,10 @@ test('updateNotificationChannel supports partial enabled updates', async () => {
|
||||
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({
|
||||
enabled: false,
|
||||
});
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('updateShippingRule posts buyer reviewed gift payload to automation-rules', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true, id: 1 }));
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true, id: 1 })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await updateShippingRule({
|
||||
@@ -764,7 +764,7 @@ test('updateShippingRule posts buyer reviewed gift payload to automation-rules',
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
}));
|
||||
const body = JSON.parse(fetchMock.mock.calls[0][1].body);
|
||||
const body = JSON.parse(fetchMock.mock.calls[0][1].body); /* body 表示请求体。 */
|
||||
expect(body).toMatchObject({
|
||||
cookie_id: 'cookie-1',
|
||||
item_id: 'item-1',
|
||||
@@ -778,10 +778,10 @@ test('updateShippingRule posts buyer reviewed gift payload to automation-rules',
|
||||
sort_order: 1,
|
||||
}),
|
||||
]);
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('updateShippingRule posts every matching card action before confirm shipment', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true, id: 3 }));
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true, id: 3 })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await updateShippingRule({
|
||||
@@ -809,7 +809,7 @@ test('updateShippingRule posts every matching card action before confirm shipmen
|
||||
],
|
||||
});
|
||||
|
||||
const body = JSON.parse(fetchMock.mock.calls[0][1].body);
|
||||
const body = JSON.parse(fetchMock.mock.calls[0][1].body); /* body 表示请求体。 */
|
||||
expect(body.trigger_type).toBe('order_paid');
|
||||
expect(body.actions).toEqual([
|
||||
expect.objectContaining({
|
||||
@@ -831,10 +831,10 @@ test('updateShippingRule posts every matching card action before confirm shipmen
|
||||
expect(JSON.parse(body.actions[0].config_json)).toEqual({ spec_name: '套餐', spec_value: '30天', delay_override: false });
|
||||
expect(JSON.parse(body.actions[1].config_json)).toEqual({ spec_name: '套餐', spec_value: '30天', delay_override: true });
|
||||
expect(body.actions[1].delay_seconds).toBe(0);
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('updateShippingRule preserves text actions while editing card variants', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true, id: 4 }));
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true, id: 4 })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await updateShippingRule({
|
||||
@@ -846,17 +846,17 @@ test('updateShippingRule preserves text actions while editing card variants', as
|
||||
actions: [{ action_type: 'send_text', message_template: '发货提示', enabled: true, sort_order: 2 }],
|
||||
});
|
||||
|
||||
const body = JSON.parse(fetchMock.mock.calls[0][1].body);
|
||||
expect(body.actions.map((action: { action_type: string }) => action.action_type)).toEqual([
|
||||
const body = JSON.parse(fetchMock.mock.calls[0][1].body); /* body 表示请求体。 */
|
||||
expect(body.actions.map((action: { /* action_type 表示actiontype。 */ action_type: string }) => action.action_type /* 回调函数负责当前业务流程。 */)).toEqual([
|
||||
'send_card',
|
||||
'send_text',
|
||||
'confirm_shipment',
|
||||
]);
|
||||
expect(body.actions[1].message_template).toBe('发货提示');
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('updateShippingRule posts review request text action without card requirement', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true, id: 2 }));
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true, id: 2 })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await updateShippingRule({
|
||||
@@ -873,7 +873,7 @@ test('updateShippingRule posts review request text action without card requireme
|
||||
}],
|
||||
});
|
||||
|
||||
const body = JSON.parse(fetchMock.mock.calls[0][1].body);
|
||||
const body = JSON.parse(fetchMock.mock.calls[0][1].body); /* body 表示请求体。 */
|
||||
expect(body.trigger_type).toBe('review_missing_timeout');
|
||||
expect(body.actions).toEqual([
|
||||
expect.objectContaining({
|
||||
@@ -882,7 +882,7 @@ test('updateShippingRule posts review request text action without card requireme
|
||||
message_template: '亲,方便的话麻烦给个评价~',
|
||||
}),
|
||||
]);
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
// 会话 API 使用版本化兼容入口。
|
||||
const runVersionedSessionAPITest = async () => {
|
||||
|
||||
@@ -7,14 +7,14 @@ describe('normalizeSMTPSettings', () => {
|
||||
smtp_from_name: '',
|
||||
smtp_from_address: 'sender@example.com',
|
||||
});
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('migrates a legacy display name and falls back to the SMTP user address', () => {
|
||||
expect(normalizeSMTPSettings({ smtp_from: '闲鱼助手', smtp_user: 'login@example.com' })).toMatchObject({
|
||||
smtp_from_name: '闲鱼助手',
|
||||
smtp_from_address: 'login@example.com',
|
||||
});
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('preserves explicit split sender fields', () => {
|
||||
expect(normalizeSMTPSettings({
|
||||
@@ -25,12 +25,12 @@ describe('normalizeSMTPSettings', () => {
|
||||
smtp_from_name: '新名称',
|
||||
smtp_from_address: 'new@example.com',
|
||||
});
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('normalizes persisted SMTP transport strings', () => {
|
||||
expect(normalizeSMTPSettings({ smtp_use_tls: 'false', smtp_use_ssl: 'true' })).toMatchObject({
|
||||
smtp_use_tls: false,
|
||||
smtp_use_ssl: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
@@ -1,6 +1,6 @@
|
||||
export const normalizeSMTPSettings = (settings: Record<string, any>): Record<string, any> => {
|
||||
const legacyFrom = String(settings.smtp_from || '').trim();
|
||||
const legacyIsAddress = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(legacyFrom);
|
||||
const legacyFrom = String(settings.smtp_from || '').trim(); /* legacyFrom 表示legacyFrom。 */
|
||||
const legacyIsAddress = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(legacyFrom); /* legacyIsAddress 表示legacyIsAddress。 */
|
||||
return {
|
||||
...settings,
|
||||
smtp_from_name: settings.smtp_from_name || (legacyIsAddress ? '' : legacyFrom),
|
||||
@@ -8,7 +8,7 @@ export const normalizeSMTPSettings = (settings: Record<string, any>): Record<str
|
||||
smtp_use_tls: parseSettingBoolean(settings.smtp_use_tls, true),
|
||||
smtp_use_ssl: parseSettingBoolean(settings.smtp_use_ssl, false),
|
||||
};
|
||||
};
|
||||
}; /* normalizeSMTPSettings 表示normalizeSMTPSettings。 */
|
||||
|
||||
const parseSettingBoolean = (value: unknown, fallback: boolean): boolean => {
|
||||
if (typeof value === 'boolean') return value;
|
||||
@@ -17,4 +17,4 @@ const parseSettingBoolean = (value: unknown, fallback: boolean): boolean => {
|
||||
if (['false', '0', 'no', 'off'].includes(value.toLowerCase())) return false;
|
||||
}
|
||||
return fallback;
|
||||
};
|
||||
}; /* parseSettingBoolean 表示parseSettingBoolean。 */
|
||||
@@ -3,7 +3,7 @@ import type { UserConfig } from 'vite';
|
||||
import config from './vite.config';
|
||||
|
||||
test('development server proxies versioned API and health checks', () => {
|
||||
const proxy = (config as UserConfig).server?.proxy;
|
||||
const proxy = (config as UserConfig).server?.proxy; /* proxy 表示proxy。 */
|
||||
expect(proxy).toBeDefined();
|
||||
expect(proxy).toHaveProperty('/api');
|
||||
expect(proxy).toHaveProperty('/health');
|
||||
@@ -15,4 +15,4 @@ test('development server proxies versioned API and health checks', () => {
|
||||
expect(proxy).not.toHaveProperty('/qr-login');
|
||||
expect(proxy).not.toHaveProperty('/items');
|
||||
expect(proxy).not.toHaveProperty('/cookies');
|
||||
});
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
@@ -97,6 +97,11 @@ func collectFindings(root string) ([]Finding, error) {
|
||||
if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, ".gen.go") {
|
||||
return nil
|
||||
}
|
||||
// relativePath 用于识别仓库明确冻结、不得改写的 CAPTCHA 源码文件。
|
||||
relativePath, relativeErr := filepath.Rel(root, path)
|
||||
if relativeErr == nil && isFrozenGoFile(filepath.ToSlash(relativePath)) {
|
||||
return nil
|
||||
}
|
||||
// fileFindings 是当前文件的问题;parseErr 表示 AST 解析失败的原因。
|
||||
fileFindings, parseErr := inspectGoFile(root, path)
|
||||
if parseErr != nil {
|
||||
@@ -111,6 +116,21 @@ func collectFindings(root string) ([]Finding, error) {
|
||||
return findings, nil
|
||||
}
|
||||
|
||||
// isFrozenGoFile 判断文件是否属于生产冻结的滑块/CAPTCHA 实现及测试。
|
||||
func isFrozenGoFile(relativePath string) bool {
|
||||
// frozenFiles 是与 AGENTS.md 及冻结规范一致的源码边界清单。
|
||||
frozenFiles := map[string]bool{
|
||||
"internal/browser/slider.go": true,
|
||||
"internal/browser/slider_test.go": true,
|
||||
"internal/browser/token_captcha.go": true,
|
||||
"internal/browser/token_captcha_test.go": true,
|
||||
"internal/browser/token_captcha_fallback.go": true,
|
||||
"internal/browser/token_captcha_fallback_integration_test.go": true,
|
||||
"internal/browser/token_captcha_orchestrator_test.go": true,
|
||||
}
|
||||
return frozenFiles[relativePath]
|
||||
}
|
||||
|
||||
// shouldSkipDirectory 判断目录是否为依赖、构建产物或运行时数据目录。
|
||||
func shouldSkipDirectory(path, root string) bool {
|
||||
// relativePath 用统一的分隔符表达目录,避免跨平台判断差异。
|
||||
@@ -347,6 +367,10 @@ func readBaseline(path string) (map[string]struct{}, error) {
|
||||
// data 是基线文件的 JSON 内容。
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
// baselineMissing 表示严格门禁已删除历史基线文件,按空集合继续检查。
|
||||
if os.IsNotExist(err) {
|
||||
return map[string]struct{}{}, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
// findings 是反序列化后的历史问题列表。
|
||||
|
||||
Reference in new issue
Block a user