diff --git a/docs/architecture/refactoring-master-plan.md b/docs/architecture/refactoring-master-plan.md index 8d42c65..c551169 100644 --- a/docs/architecture/refactoring-master-plan.md +++ b/docs/architecture/refactoring-master-plan.md @@ -642,3 +642,4 @@ npm --prefix frontend run build | 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 完成:进入全仓重构计划最终审计 | | 2026-08-15 | 完成测试覆盖率提升切片“确定性 Browser/命令入口覆盖与前端覆盖率采集” | 新增 Cookie 快照、浏览器池/持久化上下文、登录页、订单 DOM、滑块页面辅助、命令行入口测试;修复 Playwright 数值类型导致的登录成功误判;新增 Go `cover-browser`、前端 V8 `test:coverage` 与 Makefile 入口;普通 Go 全量覆盖率 70.9%,本地 Chromium 覆盖 Browser 约 60.0%,前端当前全源覆盖率为语句 19.22%;真实账号/外部平台流程仍明确不触网 | 下一步:按覆盖率报告继续补齐前端页面行为与 Browser 非账号错误分支,不降低门禁或伪造 100% | +| 2026-08-15 | 完成测试覆盖率提升切片“前端规则与领域状态边界补测” | 新增规则工具、账号运行态、批量任务、仪表盘、通知和聊天状态的确定性边界测试,覆盖默认值、空值、状态映射、过期响应、错误消息、SMTP 校验和时间格式化;前端 196 个测试、类型检查、注释门禁通过,全源语句覆盖率提升至 22.02%;页面组件与真实平台账号流程仍按覆盖率报告列为后续切片,不降低门禁或伪造 100% | 下一步:补齐 React 页面/Hook 行为测试,并继续覆盖 Browser 非账号错误分支 | diff --git a/frontend/app/features/accounts/runtime.test.ts b/frontend/app/features/accounts/runtime.test.ts index 56ebea7..557a220 100644 --- a/frontend/app/features/accounts/runtime.test.ts +++ b/frontend/app/features/accounts/runtime.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from 'vitest'; import type { AccountDetail } from '../../../types'; -import { mergeAccountRuntimeStatuses } from './runtime'; +import { accountRuntimePresentation, isOlderStatus, mergeAccountRuntimeStatuses } from './runtime'; // account 创建运行状态测试使用的最小账号对象。 const account = (overrides: Partial = {}): AccountDetail => ({ @@ -57,4 +57,26 @@ describe('Accounts runtime state', /* 当前回调处理用户交互或异步状 const current = account(); expect(mergeAccountRuntimeStatuses([current], {})[0]).toBe(current); }); + + test('时间戳缺失或无效时不误判为旧状态', /* 当前回调处理用户交互或异步状态变化。 */ () => { + expect(isOlderStatus(undefined, '2026-01-01T00:00:00Z')).toBe(false); + expect(isOlderStatus('invalid', '2026-01-01T00:00:00Z')).toBe(false); + expect(isOlderStatus('2026-01-02T00:00:00Z', '2026-01-01T00:00:00Z')).toBe(true); + expect(isOlderStatus('2026-01-01T00:00:00Z', '2026-01-02T00:00:00Z')).toBe(false); + }); + + test('所有运行状态都映射到稳定的中文展示', /* 当前回调处理用户交互或异步状态变化。 */ () => { + // states 是运行状态到中文标签的完整断言表。 + const states = [ + ['online', '在线'], ['starting', '连接中'], ['connecting', '连接中'], ['reconnecting', '重连中'], + ['auth_expired', '登录已失效'], ['verification_required', '需要验证'], ['error', '运行异常'], ['stopped', '运行异常'], + ] as const; + states.forEach( + // state 是需要验证展示文案的运行状态和预期标签。 + ([state, label]) => expect(accountRuntimePresentation(account({ runtime_state: state })).label).toBe(label), + ); + expect(accountRuntimePresentation(account({ enabled: false, runtime_state: 'online' })).label).toBe('已停用'); + expect(accountRuntimePresentation(account({ runtime_state: 'disabled' })).label).toBe('已停用'); + expect(accountRuntimePresentation(account()).label).toBe('状态检测中'); + }); }); diff --git a/frontend/app/features/chat/state.test.ts b/frontend/app/features/chat/state.test.ts index d693121..f76a68d 100644 --- a/frontend/app/features/chat/state.test.ts +++ b/frontend/app/features/chat/state.test.ts @@ -1,6 +1,6 @@ import { expect, test } from 'vitest'; import type { ChatMessage, ChatSession } from '../../../types'; -import { filterChatSessions, isCurrentChatRequest, mergeLiveMessage, mergeOlderMessages } from './state'; +import { filterChatSessions, formatClock, isChatAbortError, isCurrentChatRequest, mergeLiveMessage, mergeOlderMessages, messageTime } from './state'; // sessionFixture 是覆盖搜索、未读筛选和联系人隔离的最小会话数据。 const sessionFixture: ChatSession[] = [ @@ -29,3 +29,20 @@ test('Chat 实时消息替换同键记录并拒绝过期请求', controller.abort(); expect(isCurrentChatRequest(3, 3, controller.signal)).toBe(false); }); + +test('Chat 状态工具覆盖追加消息、搜索字段和时间格式化', + // 边界场景测试验证新消息追加、不同搜索字段和取消错误识别。 + () => { + expect(filterChatSessions(sessionFixture, 'B2', false)).toEqual([sessionFixture[1]]); + expect(filterChatSessions(sessionFixture, '已发货', false)).toEqual([sessionFixture[1]]); + expect(filterChatSessions(sessionFixture, '不存在', false)).toEqual([]); + // incoming 是没有出现在当前列表中的实时消息。 + const incoming = { ...messageFixture, message_key: 'm2', content: '新消息' }; + expect(mergeLiveMessage([messageFixture], incoming)).toEqual([messageFixture, incoming]); + expect(isChatAbortError(new Error('请求已取消'))).toBe(true); + expect(isChatAbortError(new Error('网络失败'))).toBe(false); + expect(isChatAbortError('请求已取消')).toBe(false); + expect(formatClock(0)).toBe(''); + expect(formatClock(Date.now())).toMatch(/^\d{2}:\d{2}$/); + expect(messageTime(Date.now())).toMatch(/\d{2}\/\d{2}/); + }); diff --git a/frontend/app/features/dashboard/state.test.ts b/frontend/app/features/dashboard/state.test.ts index 256a45e..861c8de 100644 --- a/frontend/app/features/dashboard/state.test.ts +++ b/frontend/app/features/dashboard/state.test.ts @@ -1,6 +1,6 @@ import { expect, test } from 'vitest'; import type { OrderAnalytics } from '../../../types'; -import { buildChartData, buildProductSalesData, getTrendPercent, isCurrentDashboardRequest } from './state'; +import { buildCategoryData, buildChartData, buildItemNameMap, buildProductSalesData, buildSourceData, getMaxProductSales, getRangeLabel, getTrendPercent, isCurrentDashboardRequest } from './state'; // analyticsFixture 是覆盖趋势、商品排行和零值边界的最小分析数据。 const analyticsFixture: OrderAnalytics = { @@ -16,6 +16,37 @@ test('Dashboard 派生数据保持趋势和排行口径一致', expect(buildProductSalesData(analyticsFixture, { 'item-1': '测试商品' })).toEqual([{ name: '测试商品', sales: 3 }]); expect(getTrendPercent(analyticsFixture, { ...analyticsFixture, revenue_stats: { total_amount: 100, total_orders: 2 } })).toBe('+20.0%'); }); + +test('Dashboard 派生数据覆盖空值、零值和名称截断分支', + // 边界数据测试验证没有订单或缺少商品标题时仍能稳定渲染。 + () => { + // empty 是没有任何订单的分析结果。 + const empty = { revenue_stats: { total_amount: 0, total_orders: 0 }, daily_stats: [], item_stats: [] } as OrderAnalytics; + // longName 用于验证商品名称超过展示长度时会被截断。 + const longName = '这是一个超过十二个字符的商品名称'; + // analytics 是包含一个商品统计的非空分析结果。 + const analytics = { + ...empty, + revenue_stats: { total_amount: 10, total_orders: 2 }, + item_stats: [{ item_id: 'item-long', order_count: 2, total_amount: 10, avg_amount: 5 }], + } as OrderAnalytics; + expect(buildItemNameMap([{ item_id: 'item-long', item_title: '' } as never])).toEqual({ 'item-long': 'item-long' }); + expect(buildChartData(empty)).toEqual([]); + expect(buildChartData({ ...empty, daily_stats: [{ date: '2026-08-15', amount: 0, order_count: 0 }] })).toEqual([{ name: '08-15', amount: 0, orders: 0, avgAmount: 0 }]); + expect(buildProductSalesData({ ...analytics, item_stats: [{ ...analytics.item_stats![0], item_id: 'item-long' }] }, { 'item-long': longName })[0].name).toBe('这是一个超过十二个字符的...'); + expect(buildSourceData(analytics, {}, ['red'])[0]).toMatchObject({ name: 'item-long', percent: 100, color: 'red' }); + expect(buildCategoryData(analytics, {}, ['blue'])[0]).toMatchObject({ name: 'item-long', percentage: '100.0', color: 'blue' }); + expect(getTrendPercent(null, analytics)).toBeNull(); + expect(getTrendPercent(analytics, null)).toBeNull(); + expect(getTrendPercent(analytics, empty)).toBe('+100%'); + expect(getTrendPercent(empty, empty)).toBe('0%'); + expect(getTrendPercent({ ...analytics, revenue_stats: { total_amount: 50, total_orders: 1 } }, analytics)).toBe('+400.0%'); + expect(getRangeLabel({ range: 'today' } as never)).toBe('今天'); + expect(getRangeLabel({ range: 'custom' } as never)).toBe('自定义'); + expect(getRangeLabel({ range: 'unknown' } as never)).toBe('所选范围'); + expect(getMaxProductSales([])).toBe(1); + expect(getMaxProductSales([{ name: 'x', sales: 4 }])).toBe(4); + }); test('Dashboard 请求代次和取消信号拒绝过期响应', // 请求边界测试验证刷新后的旧请求不能覆盖新数据,主动取消也不会写入状态。 () => { diff --git a/frontend/app/features/items/batchState.test.ts b/frontend/app/features/items/batchState.test.ts index d4c224f..0e7773e 100644 --- a/frontend/app/features/items/batchState.test.ts +++ b/frontend/app/features/items/batchState.test.ts @@ -1,6 +1,7 @@ import { describe, expect, test } from 'vitest'; import { batchStatusText, + batchStatusClass, canRetryBatch, canStartBatch, isBatchInProgress, @@ -54,5 +55,27 @@ describe('ItemList batch state', () => { expect(selectActivePublishBatch([{ id: 'done', status: 'completed' }])).toBeUndefined(); expect(selectActivePublishBatch([{ id: 'done', status: 'completed' }, { id: 'active', status: 'running' }])?.id).toBe('active'); - }); }); + + test('covers all batch status labels and style groups', + // 状态展示场景回调验证后端状态到中文和样式的完整映射。 + () => { + // labels 是批量状态到中文文案的完整断言表。 + const labels: Record = { + preview: '待确认', pending: '等待中', running: '发布中', canceling: '正在安全取消', success: '成功', + failed: '失败', completed: '已完成', partially_failed: '部分失败', canceled: '已取消', unknown: 'unknown', + }; + Object.entries(labels).forEach( + // entry 是状态值和对应的中文文案。 + ([status, label]) => expect(batchStatusText(status)).toBe(label), + ); + expect(batchStatusText()).toBe('-'); + expect(batchStatusClass('success')).toContain('bg-emerald-50'); + expect(batchStatusClass('completed')).toContain('bg-emerald-50'); + expect(batchStatusClass('partially_failed')).toContain('bg-red-50'); + expect(batchStatusClass('failed')).toContain('bg-red-50'); + expect(batchStatusClass('running')).toContain('bg-blue-50'); + expect(batchStatusClass('canceled')).toContain('bg-gray-100'); + expect(batchStatusClass('pending')).toContain('bg-amber-50'); + }); +}); diff --git a/frontend/app/features/notifications/state.test.ts b/frontend/app/features/notifications/state.test.ts index 18881d7..5fef219 100644 --- a/frontend/app/features/notifications/state.test.ts +++ b/frontend/app/features/notifications/state.test.ts @@ -1,6 +1,7 @@ import { expect, test } from 'vitest'; +import type { NotificationChannel } from '../../../types'; import type { NotificationForm } from './types'; -import { buildNotificationPayload, isCurrentNotificationRequest, notificationEventSummary, validateNotificationForm } from './state'; +import { buildNotificationPayload, emptyNotificationForm, isCurrentNotificationRequest, normalizeNotificationForm, notificationErrorMessage, notificationEventSummary, validateNotificationForm } from './state'; // createForm 创建通知渠道校验使用的最小表单对象。 const createForm = (overrides: Partial = {}): NotificationForm => ({ @@ -29,3 +30,24 @@ test('通知请求代次拒绝过期响应', expect(isCurrentNotificationRequest(5, 5)).toBe(true); expect(isCurrentNotificationRequest(4, 5)).toBe(false); }); + +test('通知表单覆盖各渠道归一化和独立 SMTP 校验', + // 表单分支测试验证非邮件、继承 SMTP 和独立 SMTP 三条保存路径。 + () => { + expect(emptyNotificationForm()).toMatchObject({ name: '', type: 'bark', enabled: true, config: {}, event_types: [] }); + // webhook 是非邮件渠道配置复制测试使用的渠道对象。 + const webhook = { id: 'webhook-1', name: 'Webhook', type: 'webhook', config: { webhook_url: 'https://example.com' }, enabled: false } as NotificationChannel; + // smtp 是继承或补全独立 SMTP 配置时使用的系统设置。 + const smtp = { smtp_server: 'smtp.example.com', smtp_port: 465, smtp_user: 'sender@example.com', smtp_password: 'secret', smtp_from_address: 'sender@example.com' }; + expect(normalizeNotificationForm(webhook, smtp)).toMatchObject({ name: 'Webhook', type: 'webhook', enabled: false, config: { webhook_url: 'https://example.com' }, event_types: [] }); + // inherited 是未开启独立 SMTP 时的邮件渠道表单。 + const inherited = normalizeNotificationForm({ id: 'email-1', name: '邮件', type: 'email', config: { to_email: 'to@example.com' }, enabled: true }, smtp); + expect(inherited.config).toMatchObject({ to_email: 'to@example.com', use_custom_smtp: false }); + expect(validateNotificationForm({ ...createForm(), type: 'email', config: { to_email: 'to@example.com', use_custom_smtp: true } })).toBe('请填写 独立 SMTP 服务器'); + // custom 是字段完整的独立 SMTP 邮件渠道表单。 + const custom = { ...createForm(), type: 'email' as const, config: { to_email: 'to@example.com', use_custom_smtp: true, smtp_server: 'smtp.example.com', smtp_port: 465, smtp_user: 'sender@example.com', smtp_password: 'secret', smtp_from_address: 'sender@example.com' } }; + expect(validateNotificationForm(custom)).toBe(''); + expect(buildNotificationPayload(custom).config).toMatchObject({ to_email: 'to@example.com', use_custom_smtp: true }); + expect(notificationErrorMessage(new Error('网络失败'), '备用错误')).toBe('网络失败'); + expect(notificationErrorMessage({}, '备用错误')).toBe('备用错误'); + }); diff --git a/frontend/app/features/rules/utils.test.ts b/frontend/app/features/rules/utils.test.ts new file mode 100644 index 0000000..55656bc --- /dev/null +++ b/frontend/app/features/rules/utils.test.ts @@ -0,0 +1,95 @@ +import { describe, expect, test } from 'vitest'; +import type { AccountDetail, ShippingRule } from '../../../types'; +import { + accentClasses, + accountLabel, + actionSummary, + boolFlag, + buildReviewConfig, + cardActionsForTrigger, + defaultRuleName, + emptyVariant, + parseJSONObject, + shouldReplaceGeneratedName, + statusPill, +} from './utils'; + +// rule 是规则工具测试使用的最小规则对象。 +const rule = (overrides: Partial = {}): ShippingRule => ({ + id: 'rule-1', + name: '测试规则', + trigger_type: 'order_paid', + item_keyword: '', + card_group_id: 0, + priority: 1, + enabled: true, + actions: [], + variants: [], + ...overrides, +}); + +describe('规则工具函数', /* 当前回调处理规则配置和展示状态。 */ () => { + test('安全解析规则配置并规范化求评价参数', /* 当前回调处理规则配置和展示状态。 */ () => { + expect(parseJSONObject()).toEqual({}); + expect(parseJSONObject('{bad')).toEqual({}); + expect(parseJSONObject('[]')).toEqual({}); + expect(parseJSONObject('{"max_attempts": 3}')).toEqual({ max_attempts: 3 }); + expect(buildReviewConfig('{"after_shipped_hours": 48}')).toBe('{"after_shipped_hours":48,"repeat_interval_hours":24,"max_attempts":1}'); + expect(buildReviewConfig(undefined, { max_attempts: 4 })).toBe('{"after_shipped_hours":72,"repeat_interval_hours":24,"max_attempts":4}'); + }); + + test('生成规则名称并识别可替换的系统名称', /* 当前回调处理规则配置和展示状态。 */ () => { + expect(defaultRuleName('order_paid')).toBe('付款后自动发货'); + expect(defaultRuleName('buyer_reviewed', '数字商品')).toBe('评价后发送赠品 - 数字商品'); + expect(defaultRuleName('unknown' as never)).toBe('自动化规则'); + expect(shouldReplaceGeneratedName()).toBe(true); + expect(shouldReplaceGeneratedName(' ')).toBe(true); + expect(shouldReplaceGeneratedName('付款后自动发货')).toBe(true); + expect(shouldReplaceGeneratedName('付款后自动发货 - 旧商品')).toBe(true); + expect(shouldReplaceGeneratedName('我自定义的规则')).toBe(false); + }); + + test('创建三类触发器的默认动作链', /* 当前回调处理规则配置和展示状态。 */ () => { + expect(cardActionsForTrigger('review_missing_timeout')).toEqual([{ + action_type: 'send_text', message_template: '亲,商品使用满意的话,麻烦给个评价,谢谢~', enabled: true, sort_order: 1, + }]); + expect(cardActionsForTrigger('order_paid', 7)).toEqual([ + { action_type: 'send_card', card_id: 7, delivery_count: 1, enabled: true, sort_order: 1 }, + { action_type: 'confirm_shipment', enabled: true, sort_order: 2 }, + ]); + expect(cardActionsForTrigger('buyer_reviewed', 8)).toEqual([ + { action_type: 'send_card', card_id: 8, delivery_count: 1, enabled: true, sort_order: 1 }, + ]); + }); + + test('汇总动作、主题样式和布尔标志', /* 当前回调处理规则配置和展示状态。 */ () => { + expect(actionSummary(rule({ trigger_type: 'review_missing_timeout', actions: [{ action_type: 'send_text', message_template: '请评价', enabled: true }] }))).toBe('请评价'); + expect(actionSummary(rule({ trigger_type: 'review_missing_timeout', actions: [] }))).toBe('发送求评价文案'); + expect(actionSummary(rule({ actions: [] }))).toBe('未配置卡密库存'); + expect(actionSummary(rule({ actions: [ + { action_type: 'send_card', card_id: 1, card_name: '库存一', enabled: true }, + { action_type: 'send_card', card_id: 2, enabled: true }, + { action_type: 'send_text', message_template: '忽略', enabled: true }, + ] }))).toBe('库存一 / 卡密 2'); + expect(accentClasses('blue', true)).toContain('border-blue-500'); + expect(accentClasses('amber')).toContain('hover:border-amber-300'); + expect(accentClasses('unknown' as never)).toContain('border-blue-100'); + expect(statusPill(true)).toContain('bg-emerald-100'); + expect(statusPill(false)).toContain('bg-gray-200'); + expect(boolFlag(true)).toBe(true); + expect(boolFlag(1)).toBe(true); + expect(boolFlag('1')).toBe(true); + expect(boolFlag(false)).toBe(false); + expect(boolFlag('true')).toBe(false); + }); + + test('创建空规格并选择账号展示名称', /* 当前回调处理规则配置和展示状态。 */ () => { + expect(emptyVariant()).toEqual({ spec_name: '', spec_value: '', card_id: 0, delivery_count: 1, enabled: true, delay_override: false, delay_seconds: 0 }); + // idOnly 是仅包含平台账号标识的最小账号对象。 + const idOnly = { id: 'account-1' } as AccountDetail; + expect(accountLabel({ id: 'a', nickname: '昵称' } as AccountDetail)).toBe('昵称'); + expect(accountLabel({ id: 'a', remark: '备注' } as AccountDetail)).toBe('备注'); + expect(accountLabel(idOnly)).toBe('account-1'); + expect(accountLabel()).toBe('未知账号'); + }); +});