阶段四:完成 React Feature 化和异步状态修复

This commit is contained in:
Christ committed 2026-08-19 01:02:19 +08:00
1 parent 4227e3dd56
commit e92549da48
176 files changed
+849 -650

No files matched your search

+3 -3
View File
@@ -41,11 +41,11 @@ shared,feature adapter 直接转换领域 DTO 为 feature-owned UI model。
| 1. 稳定性、安全和启动生命周期 | 已完成(既有基线) | 已按当前工作树复核原子 data key、同步 Bind、启动回滚、无秘密告警及该阶段命令。六阶段治理建立时这些改动已经存在;禁止为纠正历史提交名重新提交或改写历史。 |
| 2. Server 组合根和应用服务迁移 | 已完成 | `internal/composition` 已成为唯一生产组合根;旧 Server 组合根与生命周期反转已删除。Server 仅接收经校验的消费者 Port,阶段二 AST 门禁和完整验收均已通过。最终提交绑定见 `refactoring-progress.md`。 |
| 3. 生命周期、Engine 和 Automation 重新验收 | 已完成 | 已完成后台任务 owner/Context/Cancel/Wait 收口、同步凭证更新的调用 Context 传递、浏览器组合根生命周期接入和 AST 生命周期门禁;最终提交与完整证据见 `refactoring-progress.md`。 |
| 4. React Feature 化和异步状态修复 | 当前阶段 | ApiError、定位和批量状态代码是输入;DTO barrel、根级地图服务和 DTO 直连仍未收口。 |
| 5. DB 与事务治理重新验收 | 待执行 | 不得提前。 |
| 4. React Feature 化和异步状态修复 | 已完成 | 已完成领域契约直接模块、feature API adapter 边界、统一 ApiError、items 地图迁移、定位取消/超时、批量轮询代次隔离、严格 TypeScript 检查和嵌入产物重建;最终证据见 `refactoring-progress.md`。 |
| 5. DB 与事务治理重新验收 | 当前阶段 | 仅允许开展上层裸数据库、Unit of Work、claim/lease/补偿和多数据库验收;不得提前进入阶段六收口。 |
| 6. 全量架构、兼容退场和注释收口 | 待执行 | 门禁规则已在基础验证层预建;本阶段只激活最终质量规则、清零违规并完成兼容和注释退场。 |
顺序固定为 1 -> 2 -> 3 -> 4 -> 5 -> 6。阶段一是治理建立前的既有基线例外;从阶段二开始,每阶段必须有唯一最终中文提交和完整原始命令输出。阶段三已完成,阶段四是唯一允许继续执行的阶段;阶段五及之后不得提前执行。
顺序固定为 1 -> 2 -> 3 -> 4 -> 5 -> 6。阶段一是治理建立前的既有基线例外;从阶段二开始,每阶段必须有唯一最终中文提交和完整原始命令输出。阶段四已完成,阶段五是唯一允许继续执行的阶段;阶段六不得提前执行。
## 阶段一:稳定性、安全和启动生命周期
+51 -4
View File
@@ -134,7 +134,54 @@ $ git diff --check
## 下一阶段入口
当前阶段为阶段四:React Feature 化和异步状态修复。阶段四开始前先运行 architecturecheck,激活已有 React
feature、传输契约、网络旁路、动态 import 和严格 TypeScript 门禁;在同一阶段完成 ApiError、领域契约拆分、
items 地图迁移、定位取消/超时、批量轮询与嵌入产物重建。不得提前进入数据库或最终收口阶段,也不得修改冻结
CAPTCHA。
阶段四已完成,阶段五:DB 与事务治理重新验收为唯一当前阶段。开始阶段五前先运行 architecturecheck,确认
前序 React feature、传输契约、网络旁路和严格 TypeScript 门禁继续 fail-closed;不得提前进入阶段六最终收口,
也不得修改冻结 CAPTCHA。
## 阶段四:React Feature 化和异步状态修复
- 最终提交绑定:`HEAD` 的唯一中文提交 `阶段四:完成 React Feature 化和异步状态修复`。
- 交付范围:公开 `ApiError` 保留 `status/code/message/request_id/details/payload`;JSON、FormData、非 JSON 和损坏 JSON 错误统一解析并覆盖 401 会话失效通知。`shared/api-contract/index.ts` 已删除,契约按 session、accounts、items、orders、automation、notifications、settings、chat、cards、admin、common 直接模块拆分;生产 UI、Hook、状态和组件只能通过 feature `api.ts` adapter 读取 DTO。地图服务及其测试已迁入 `app/features/items`,定位使用 AbortController、generation 和 AMap timeout;批量任务将 pending/running/canceling 统一轮询,关闭、重开、卸载和晚到响应均由独立取消器与代次隔离。
- 门禁收口:阶段四 React 门禁增加真实源码扫描,禁止 feature UI/Hook/状态绕过 API adapter 直接导入 transport DTO;`noUnusedLocals` 与 `noUnusedParameters` 已开启并清零。
### 强制验收原始输出
```text
$ npm test --prefix frontend
Test Files 67 passed (67)
Tests 402 passed (402)
$ npm run typecheck --prefix frontend
(无输出,退出码 0)
$ npm run comments:check --prefix frontend
commentlint: 通过(无缺少中文注释或模板化注释)
$ npm run build --prefix frontend
vite v6.4.3 building for production...
✓ built in 2.76s
$ make cover-frontend
Test Files 67 passed (67)
Tests 402 passed (402)
Statements : 79.82% (3704/4640)
Lines : 82.17% (3236/3938)
$ go run ./tools/architecturecheck
architecturecheck: 通过
$ git diff --check
(无输出,退出码 0)
```
### 验收边界
- 覆盖率:V8 statements 79.82%、lines 82.17%;覆盖率报告位于未跟踪 `frontend/coverage/`,不纳入提交。
- 浏览器:未运行真实账号浏览器集成;本阶段使用 jsdom 和确定性 AMap loader/search 替身覆盖定位取消、超时和晚到回调。
- 外部服务:未运行 MySQL/PostgreSQL、`cmd/dbverify` 或真实平台调用;这些属于阶段五或真实外部环境例外。
- 冻结 CAPTCHA:`internal/browser/slider.go`、`token_captcha*.go` 及其测试和规范未修改。
- 生成物:已由 `npm run build --prefix frontend` 重建 `internal/webui/static`,未手工修改嵌入文件。
## 阶段五入口
阶段五现在是唯一当前阶段。下一步只处理 DB 与事务治理重新验收:清除上层裸 `Store.DB`、`sql.DB`、`sql.Tx` 和 row model 泄露,核对 Unit of Work、claim/lease、取消、重试及补偿,并在可用时运行 SQLite、MySQL、PostgreSQL 和 `cmd/dbverify` 证据。不得在阶段五提前执行阶段六兼容退场、复杂度或全量注释收口。
@@ -1,5 +1,5 @@
import { get, post, put, type RequestControlOptions } from '../../../shared/http/client';
import type { AccountTaskSettings, AccountTaskSettingsResponse, AccountTaskRunResponseEnvelope } from '../../../shared/api-contract';
import type { AccountTaskRunResponseEnvelope,AccountTaskSettings,AccountTaskSettingsResponse } from './api';
import { get,post,put,type RequestControlOptions } from '../../../shared/http/client';
/** 获取指定账号的自动评价与自动擦亮设置。 */
export const getAccountTaskSettings = async (accountID: string, options?: RequestControlOptions): Promise<AccountTaskSettingsResponse> => get(`/api/v1/account-tasks/${accountID}`, undefined, options);
@@ -1,8 +1,8 @@
// @vitest-environment jsdom
import { act, renderHook, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, test, vi } from 'vitest';
import type { AccountDetail, AccountTaskSettingsResponse } from '../../../shared/api-contract';
import { getAccountTaskSettings, runAccountTask, updateAccountTaskSettings } from './accountAutomationApi';
import { act,renderHook,waitFor } from '@testing-library/react';
import { beforeEach,describe,expect,test,vi } from 'vitest';
import type { AccountDetail,AccountTaskSettingsResponse } from '../../../shared/api-contract/accounts';
import { getAccountTaskSettings,runAccountTask,updateAccountTaskSettings } from './accountAutomationApi';
import { useAccountAutomation } from './accountAutomationHooks';
vi.mock('./accountAutomationApi', /* apiMockFactory 提供账号任务 Hook 的确定性 API 替身。 */ () => ({
@@ -1,8 +1,8 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import type { AccountTaskSettings, AccountTaskSummary } from '../../../shared/api-contract';
import { getAccountTaskSettings, runAccountTask, updateAccountTaskSettings } from './accountAutomationApi';
import { accountTaskErrorMessage, buildAccountTaskDefaults, canStartAccountTask, isAccountTaskAbortError, isCurrentAccountTaskRequest } from './accountAutomationState';
import type { AccountAutomationOptions, AccountAutomationState, AccountTaskType } from './accountAutomationTypes';
import { useCallback,useEffect,useRef,useState } from 'react';
import type { AccountTaskSettings,AccountTaskSummary } from './api';
import { getAccountTaskSettings,runAccountTask,updateAccountTaskSettings } from './accountAutomationApi';
import { accountTaskErrorMessage,buildAccountTaskDefaults,canStartAccountTask,isAccountTaskAbortError,isCurrentAccountTaskRequest } from './accountAutomationState';
import type { AccountAutomationOptions,AccountAutomationState,AccountTaskType } from './accountAutomationTypes';
/** AccountAutomation Hook 的完整返回值。 */
export type UseAccountAutomationResult = AccountAutomationState & {
@@ -1,6 +1,6 @@
import { expect, test } from 'vitest';
import type { AccountDetail } from '../../../shared/api-contract';
import { buildAccountTaskDefaults, canStartAccountTask, isCurrentAccountTaskRequest } from './accountAutomationState';
import { expect,test } from 'vitest';
import type { AccountDetail } from '../../../shared/api-contract/accounts';
import { buildAccountTaskDefaults,canStartAccountTask,isCurrentAccountTaskRequest } from './accountAutomationState';
// accountFixture 是覆盖任务默认值和账号禁用边界的最小账号数据。
const accountFixture: AccountDetail = {
@@ -1,4 +1,4 @@
import type { AccountDetail, AccountTaskSettings } from '../../../shared/api-contract';
import type { AccountDetail,AccountTaskSettings } from './api';
import type { AccountTaskType } from './accountAutomationTypes';
/** 根据账号详情创建任务设置初始草稿。 */
@@ -1,4 +1,4 @@
import type { AccountDetail, AccountTaskSettings, AccountTaskSummary } from '../../../shared/api-contract';
import type { AccountDetail,AccountTaskSettings,AccountTaskSummary } from './api';
/** 账号任务类型。 */
export type AccountTaskType = 'auto_rate' | 'auto_polish';
@@ -1,4 +1,4 @@
import { describe, expect, test } from 'vitest';
import { describe,expect,test } from 'vitest';
import { shouldSaveNotificationBindings } from './accountBindings';
describe('notification binding save guard', /* 当前回调处理用户交互或异步状态变化。 */ () => {
+18 -15
View File
@@ -1,12 +1,22 @@
import { get, post, put, del, postForm, type RequestControlOptions } from '../../../shared/http/client';
import {
SessionResponse, AccountDetail, AccountSummaryResponse, Order, PaginatedResponse,
AdminStats, DashboardStats, Card, SystemSettings, OrderAnalytics,
Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction, AutomationTriggerType,
NotificationChannel, NotificationEventType, AccountTaskSettings, ChatSession, ChatMessage, ItemListEnvelope, AutomationIssuesEnvelope,
CookieSettingsResponse, CookieProfileResponse, ItemDetailResponse, ItemPublishResponse, ItemSyncResponse, OrderDTOResponse, OrderDetailResponse, OrderSingleRefreshResponse, OrderBatchResponse, OrderRefreshResponse, OrderRefreshJobStartResponse, OrderRefreshJobStatusResponse, OrderRefreshJobCancelResponse, AutomationRuleResponse, AutomationRulePageResponse, AIReplySettingsResponse, AIModelsResponse, UserSettingResponse, CardBatchResponse, CardAppendResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchListResponse, BatchIDResponse, ItemPublishBatchResponse, BatchCancelResponse, MutationIDResponse, OperationResponse, NotificationChannelResponse, NotificationBinding, AccountBindingsResponse, CardListResponse, KeywordTypedResponse, DefaultReplyResponse, AccountTaskSettingsResponse, AccountTaskRunResponseEnvelope, AdminStatsResponse, DashboardStatsResponse, OrderAnalyticsResponse, QRLoginGenerateResponse, QRLoginStatusResponse, QRLoginVerificationResponse, ValidOrderResponse, ValidOrdersResponse
} from '../../../shared/api-contract';
import { collectionFrom, objectFrom } from '../../../shared/http/contract';
AIReplySettings,
AIReplySettingsResponse,
AccountBindingsResponse,
AccountDetail,AccountSummaryResponse,
AccountTaskRunResponseEnvelope,
AccountTaskSettings,
AccountTaskSettingsResponse,
CookieProfileResponse,
CookieSettingsResponse,
NotificationChannel,
NotificationChannelResponse,
NotificationEventType,
OperationResponse,
QRLoginGenerateResponse,QRLoginStatusResponse,QRLoginVerificationResponse
} from '../../../shared/api-contract/accounts';
import { del,get,post,put,type RequestControlOptions } from '../../../shared/http/client';
import { collectionFrom,objectFrom } from '../../../shared/http/contract';
export type * from '../../../shared/api-contract/accounts';
// Accounts
// addAccount 新增账号。
export const addAccount = async (id: string, value: string, loginMethod?: string): Promise<OperationResponse> => {
@@ -278,13 +288,6 @@ const parseNotificationEventTypes = (raw: unknown): NotificationEventType[] => {
return raw.split(/[,\s;]+/).map(/* 当前回调用于处理集合元素或接口响应。 */ v => v.trim()).filter(Boolean) as NotificationEventType[];
};
// stringifyNotificationEventTypes 序列化通知事件类型。
const stringifyNotificationEventTypes = (events?: NotificationEventType[]): string => {
// clean 清理后的事件类型列表,用于当前 API 处理流程。
const clean = Array.from(new Set((events || []).filter(Boolean)));
return clean.length > 0 ? JSON.stringify(clean) : '';
};
// getNotificationChannels 读取通知渠道。
export const getNotificationChannels = async (options?: RequestControlOptions): Promise<{ /** success 表示是否成功。 */ success: boolean; /** data 表示数据。 */ data?: NotificationChannel[] }> => {
// result 接口响应结果,用于当前 API 处理流程。
@@ -1,7 +1,7 @@
import { Bot,Loader2,Save,Settings,X } from 'lucide-react';
import React from 'react';
import { createPortal } from 'react-dom';
import { Bot, Loader2, Save, Settings, X } from 'lucide-react';
import type { AccountDetail, AIReplySettings } from '../../../../shared/api-contract';
import type { AccountDetail,AIReplySettings } from '../api';
// AccountAISettingsModalProps 描述账号 AI 设置弹窗需要的状态和回调。
export interface AccountAISettingsModalProps {
@@ -1,6 +1,6 @@
import { CalendarClock,Loader2,MessageSquareQuote,Play,Save,Sparkles,X } from 'lucide-react';
import React from 'react';
import { CalendarClock, Loader2, MessageSquareQuote, Play, Save, Sparkles, X } from 'lucide-react';
import { AccountDetail, AccountTaskSettings } from '../../../../shared/api-contract';
import { AccountDetail,AccountTaskSettings } from '../api';
import { useAccountAutomation } from '../accountAutomationHooks';
interface Props {
@@ -1,6 +1,6 @@
import { AlertCircle,Bot,CalendarClock,Check,Clock,Edit2,Loader2,MessageCircle,Power,QrCode,RefreshCw,Sparkles,Trash2,User } from 'lucide-react';
import React from 'react';
import { AlertCircle, Bot, CalendarClock, Check, Clock, Loader2, MessageCircle, Power, QrCode, RefreshCw, Sparkles, Trash2, User, Edit2 } from 'lucide-react';
import type { AccountDetail } from '../../../../shared/api-contract';
import type { AccountDetail } from '../api';
import { accountRuntimePresentation } from '../runtime';
// AccountCardProps 描述账号卡片展示所需的数据和动作。
@@ -1,7 +1,7 @@
import { AlertCircle,Loader2,Trash2,X } from 'lucide-react';
import React from 'react';
import { createPortal } from 'react-dom';
import { AlertCircle, Loader2, Trash2, X } from 'lucide-react';
import type { AccountDetail } from '../../../../shared/api-contract';
import type { AccountDetail } from '../api';
// AccountDeleteDialogProps 描述账号删除确认框需要的状态和回调。
export interface AccountDeleteDialogProps {
@@ -1,9 +1,9 @@
import { Bell,Check,Clock,Eye,EyeOff,Key,Loader2,X } from 'lucide-react';
import React from 'react';
import { createPortal } from 'react-dom';
import { Bell, Check, Clock, Eye, EyeOff, Key, Loader2, X } from 'lucide-react';
import type { NotificationChannel } from '../api';
import type { AccountEditForm,AccountEditModalProps } from '../types';
import { SquareQRCode } from './SquareQRCode';
import type { NotificationChannel } from '../../../../shared/api-contract';
import type { AccountEditForm, AccountEditModalProps } from '../types';
// AccountEditModal 负责账号备注、暂停、登录信息和通知绑定的编辑界面。
export const AccountEditModal: React.FC<AccountEditModalProps> = ({
@@ -1,7 +1,7 @@
import { Check,Loader2,X } from 'lucide-react';
import React from 'react';
import { createPortal } from 'react-dom';
import { Check, Loader2, X } from 'lucide-react';
import type { AccountDetail } from '../../../../shared/api-contract';
import type { AccountDetail } from '../api';
import { RiskVerificationPanel } from './RiskVerificationPanel';
import { SquareQRCode } from './SquareQRCode';
@@ -1,6 +1,5 @@
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import { expect,test } from 'vitest';
import { RiskVerificationPanel } from './RiskVerificationPanel';
test('risk verification panel explains automatic refresh without manual controls', /* 当前回调处理用户交互或异步状态变化。 */ () => {
@@ -1,5 +1,5 @@
import { AlertTriangle,Loader2 } from 'lucide-react';
import React from 'react';
import { AlertTriangle, Loader2 } from 'lucide-react';
interface RiskVerificationPanelProps {
/** faceQrUrl 表示人脸验证二维码地址。 */ faceQrUrl?: string;
@@ -1,6 +1,5 @@
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import { expect,test } from 'vitest';
import { SquareQRCode } from './SquareQRCode';
test('login QR code preserves a square aspect ratio without stretching', /* 当前回调处理用户交互或异步状态变化。 */ () => {
@@ -1,7 +1,7 @@
// @vitest-environment jsdom
import { fireEvent, render, screen, cleanup } from '@testing-library/react';
import { afterEach, describe, expect, test, vi } from 'vitest';
import type { AccountDetail, AIReplySettings } from '../../../../shared/api-contract';
import { cleanup,fireEvent,render,screen } from '@testing-library/react';
import { afterEach,describe,expect,test,vi } from 'vitest';
import type { AccountDetail,AIReplySettings } from '../../../../shared/api-contract/accounts';
import { AccountAISettingsModal } from './AccountAISettingsModal';
import { AccountCard } from './AccountCard';
import { AccountDeleteDialog } from './AccountDeleteDialog';
@@ -1,9 +1,9 @@
// @vitest-environment jsdom
import { renderHook, waitFor } from '@testing-library/react';
import { renderHook,waitFor } from '@testing-library/react';
import { act } from 'react';
import { beforeEach, describe, expect, test, vi } from 'vitest';
import type { AccountDetail } from '../../../shared/api-contract';
import { getAccountDetails, getAccountRuntimeStatuses, getAllAISettings } from './api';
import { beforeEach,describe,expect,test,vi } from 'vitest';
import type { AccountDetail } from '../../../shared/api-contract/accounts';
import { getAccountDetails,getAccountRuntimeStatuses,getAllAISettings } from './api';
import { useAccountsData } from './hooks';
vi.mock('./api', /* accountsApiMockFactory 提供账号列表 Hook 的确定性 API 替身。 */ () => ({
+3 -3
View File
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useRef, useState, type Dispatch, type SetStateAction } from 'react';
import { getAccountDetails, getAccountRuntimeStatuses, getAllAISettings } from './api';
import type { AccountDetail } from '../../../shared/api-contract';
import { useCallback,useEffect,useRef,useState,type Dispatch,type SetStateAction } from 'react';
import type { AccountDetail } from './api';
import { getAccountDetails,getAccountRuntimeStatuses,getAllAISettings } from './api';
import { mergeAccountRuntimeStatuses } from './runtime';
import type { AccountAISettingsState } from './types';
@@ -1,8 +1,8 @@
// @vitest-environment jsdom
import { cleanup,fireEvent,render,screen,waitFor } from '@testing-library/react';
import React from 'react';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import type { AccountDetail } from '../../../../shared/api-contract';
import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest';
import type { AccountDetail } from '../../../../shared/api-contract/accounts';
// accountListMocks 保存 AccountList 页面测试使用的 API、Hook 和轮询替身。
const accountListMocks = vi.hoisted(/* accountListMockFactory 创建页面测试共享替身。 */ () => ({
@@ -1,21 +1,21 @@
import React, { useState } from 'react';
import { Loader2,QrCode,User } from 'lucide-react';
import React,{ useState } from 'react';
import { createPortal } from 'react-dom';
import { AccountDetail } from '../../../../shared/api-contract';
import { AccountDetail } from '../api';
import {
updateAccountStatus,
deleteAccount,
refreshAccountProfile,
deleteAccount,
refreshAccountProfile,
updateAccountStatus,
} from '../api';
import { Loader2, QrCode, User } from 'lucide-react';
import AccountAutomationModal from '../components/AccountAutomationModal';
import { AccountEditModal } from '../components/AccountEditModal';
import { AccountAISettingsModal } from '../components/AccountAISettingsModal';
import AccountAutomationModal from '../components/AccountAutomationModal';
import { AccountCard } from '../components/AccountCard';
import { AccountDeleteDialog } from '../components/AccountDeleteDialog';
import { AccountEditModal } from '../components/AccountEditModal';
import { AccountQRCodeModal } from '../components/AccountQRCodeModal';
import { useAccountsData } from '../hooks';
import { useAccountQRCodeLogin } from '../qrLogin';
import { useAccountSubmodules, type AccountModalType } from '../submoduleHooks';
import { useAccountSubmodules,type AccountModalType } from '../submoduleHooks';
import type { AccountEditForm } from '../types';
// AccountList 渲染账号列表组件。
@@ -1,7 +1,7 @@
// @vitest-environment jsdom
import { act, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import type { AccountDetail } from '../../../shared/api-contract';
import { act,renderHook } from '@testing-library/react';
import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest';
import type { AccountDetail } from '../../../shared/api-contract/accounts';
// qrLoginMocks 保存二维码登录协调器测试使用的接口替身。
const qrLoginMocks = vi.hoisted(/* qrLoginMockFactory 创建二维码登录 API 替身。 */ () => ({
+4 -4
View File
@@ -1,7 +1,7 @@
import { useEffect, useRef, useState } from 'react';
import type { AccountDetail } from '../../../shared/api-contract';
import { checkQRLoginStatus, completeQRVerification, generateQRLogin } from './api';
import { createLatestRequestGate, createQRLoginPoller } from './qrPolling';
import { useEffect,useRef,useState } from 'react';
import type { AccountDetail } from './api';
import { checkQRLoginStatus,completeQRVerification,generateQRLogin } from './api';
import { createLatestRequestGate,createQRLoginPoller } from './qrPolling';
// AccountQRCodeLoginOptions 描述二维码登录协调器需要的页面刷新回调。
export interface AccountQRCodeLoginOptions {
@@ -1,5 +1,5 @@
import { afterEach, expect, test, vi } from 'vitest';
import { createLatestRequestGate, createQRLoginPoller } from './qrPolling';
import { afterEach,expect,test,vi } from 'vitest';
import { createLatestRequestGate,createQRLoginPoller } from './qrPolling';
afterEach(/* 当前回调处理用户交互或异步状态变化。 */ () => {
vi.useRealTimers();
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'vitest';
import type { AccountDetail } from '../../../shared/api-contract';
import { accountRuntimePresentation, isOlderStatus, mergeAccountRuntimeStatuses } from './runtime';
import { describe,expect,test } from 'vitest';
import type { AccountDetail } from '../../../shared/api-contract/accounts';
import { accountRuntimePresentation,isOlderStatus,mergeAccountRuntimeStatuses } from './runtime';
// account 创建运行状态测试使用的最小账号对象。
const account = (overrides: Partial<AccountDetail> = {}): AccountDetail => ({
+1 -1
View File
@@ -1,5 +1,5 @@
import type { AccountDetail } from './api';
import type { AccountRuntimeStatus } from './api';
import type { AccountDetail } from '../../../shared/api-contract';
import type { AccountRuntimePresentation } from './types';
// isOlderStatus 判断传入的运行时快照是否早于账号当前已展示的快照。
+6 -6
View File
@@ -1,10 +1,10 @@
import { expect, test } from 'vitest';
import type { AccountDetail } from '../../../shared/api-contract';
import { expect,test } from 'vitest';
import type { AccountDetail } from '../../../shared/api-contract/accounts';
import {
buildAccountLoginInfoUpdate,
isCurrentAccountRequest,
passwordLoginViewFromStatus,
shouldUpdateAccountPause,
buildAccountLoginInfoUpdate,
isCurrentAccountRequest,
passwordLoginViewFromStatus,
shouldUpdateAccountPause,
} from './state';
// account 是账号编辑状态测试使用的最小领域对象。
+2 -2
View File
@@ -1,6 +1,6 @@
import type { AccountDetail } from '../../../shared/api-contract';
import type { AccountDetail } from './api';
import type { PasswordLoginStatusResponse } from './api';
import type { AccountEditForm, PasswordLoginView } from './types';
import type { AccountEditForm,PasswordLoginView } from './types';
// AccountLoginEditFields 描述账号编辑表单中参与登录信息比较的字段。
export type AccountLoginEditFields = Pick<AccountEditForm, 'username' | 'login_password' | 'show_browser'> & Pick<Partial<AccountEditForm>, 'clear_password'>;
@@ -1,22 +1,22 @@
// @vitest-environment jsdom
import { act, renderHook, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, test, vi } from 'vitest';
import type { Dispatch, SetStateAction } from 'react';
import type { AccountDetail, AIReplySettings } from '../../../shared/api-contract';
import { act,renderHook } from '@testing-library/react';
import type { Dispatch,SetStateAction } from 'react';
import { beforeEach,describe,expect,test,vi } from 'vitest';
import type { AccountDetail,AIReplySettings } from '../../../shared/api-contract/accounts';
import {
cancelPasswordLogin,
checkPasswordLoginStatus,
getAccountAISettings,
getAccountBindings,
getLongLoginSettings,
getNotificationChannels,
passwordLogin,
setLongLoginSettings,
updateAccountAISettings,
updateAccountPauseDuration,
updateAccountSettings,
cancelPasswordLogin,
checkPasswordLoginStatus,
getAccountAISettings,
getAccountBindings,
getLongLoginSettings,
getNotificationChannels,
passwordLogin,
setLongLoginSettings,
updateAccountAISettings,
updateAccountPauseDuration,
updateAccountSettings,
} from './api';
import { useAccountSubmodules, type AccountModalType } from './submoduleHooks';
import { useAccountSubmodules,type AccountModalType } from './submoduleHooks';
import type { AccountEditForm } from './types';
vi.mock('./api', /* accountsSubmoduleApiMockFactory 提供账号子模块 Hook 的确定性 API 替身。 */ () => ({
@@ -1,9 +1,9 @@
import { useCallback, useEffect, useRef, useState, type Dispatch, type SetStateAction } from 'react';
import type { AccountDetail, AIReplySettings, NotificationChannel } from '../../../shared/api-contract';
import { cancelPasswordLogin, checkPasswordLoginStatus, getAccountAISettings, getAccountBindings, getLongLoginSettings, getNotificationChannels, passwordLogin, setLongLoginSettings, updateAccountAISettings, updateAccountPauseDuration, updateAccountSettings } from './api';
import { buildAccountLoginInfoUpdate, isCurrentAccountRequest, passwordLoginViewFromStatus, shouldUpdateAccountPause } from './state';
import type { AccountEditForm, LongLoginState, PasswordLoginView } from './types';
import { useCallback,useEffect,useRef,useState,type Dispatch,type SetStateAction } from 'react';
import type { AccountDetail,AIReplySettings,NotificationChannel } from './api';
import { shouldSaveNotificationBindings } from './accountBindings';
import { cancelPasswordLogin,checkPasswordLoginStatus,getAccountAISettings,getAccountBindings,getLongLoginSettings,getNotificationChannels,passwordLogin,setLongLoginSettings,updateAccountAISettings,updateAccountPauseDuration,updateAccountSettings } from './api';
import { buildAccountLoginInfoUpdate,isCurrentAccountRequest,passwordLoginViewFromStatus,shouldUpdateAccountPause } from './state';
import type { AccountEditForm,LongLoginState,PasswordLoginView } from './types';
/** AccountList 当前编辑弹窗类型。 */
export type AccountModalType = 'edit' | 'ai-settings' | null;
+2 -2
View File
@@ -1,5 +1,5 @@
import type { Dispatch, SetStateAction } from 'react';
import type { AccountDetail, AIReplySettings, NotificationChannel } from '../../../shared/api-contract';
import type { Dispatch,SetStateAction } from 'react';
import type { AccountDetail,AIReplySettings,NotificationChannel } from './api';
// AccountEditForm 描述账号编辑弹窗中的可编辑字段。
export interface AccountEditForm {
+34 -22
View File
@@ -1,27 +1,39 @@
import { afterEach, expect, test, vi } from 'vitest';
import { afterEach,expect,test,vi } from 'vitest';
import {
addAccount,
cancelPasswordLogin,
checkPasswordLoginStatus,
checkQRLoginStatus, completeQRVerification, generateQRLogin,
getAllAISettings, getAccountAISettings, updateAccountAISettings,
getAccountDetails, getAccountRuntimeStatuses, updateAccountStatus, deleteAccount,
passwordLogin,
updateAccountCookie,
updateAccountLoginInfo,
updateAccountSettings, updateAccountRemark, updateAccountAutoConfirm, updateAccountPauseDuration, getLongLoginSettings, setLongLoginSettings, refreshAccountProfile,
getAccountTaskSettings, updateAccountTaskSettings,
runAccountTask,
addAccount,
cancelPasswordLogin,
checkPasswordLoginStatus,
checkQRLoginStatus,completeQRVerification,
deleteAccount,
generateQRLogin,
getAccountAISettings,
getAccountDetails,getAccountRuntimeStatuses,
getAccountTaskSettings,
getAllAISettings,
getLongLoginSettings,
passwordLogin,
refreshAccountProfile,
runAccountTask,
setLongLoginSettings,
updateAccountAISettings,
updateAccountAutoConfirm,
updateAccountCookie,
updateAccountLoginInfo,
updateAccountPauseDuration,
updateAccountRemark,
updateAccountSettings,
updateAccountStatus,
updateAccountTaskSettings,
} from './accounts/api';
import { appendCardData, batchCreateCards, createCard, deleteCard, getCardDetails, getCards, updateCard } from './cards/api';
import { getChatMessagePage, getChatMessages, getChatSessionPage, getChatSessions, markChatRead, sendChatImage, sendChatMessage } from './chat/api';
import { getDashboardStats, getOrderAnalytics, getValidOrders } from './dashboard/api';
import { createItem, deleteItem, deleteItemPublishBatch, cancelItemPublishBatch, getItemDetail, getItemPublishBatch, getItemPublishBatches, getItems, previewItemPublishBatch, publishItem, recommendPublishCategory, retryFailedItemPublishBatch, startItemPublishBatch, syncItemsFromAccount, updateItem } from './items/api';
import { createNotificationChannel, deleteAccountNotifications, deleteMessageNotification, deleteNotificationChannel, getAccountBindings, getMessageNotifications, getNotificationChannels, setAccountBindings, setMessageNotification, testNotificationChannel, updateNotificationChannel } from './notifications/api';
import { cancelOrderRefreshJob, deleteOrder, getAdminStats, getOrderDetail, getOrders, importOrders, manualShipOrder, syncOrders, syncSingleOrder, updateOrder } from './orders/api';
import { clearDefaultReplyRecords, deleteDefaultReply, deleteReplyRule, deleteShippingRule, getAutomationIssues, getDefaultReplies, getDefaultReply, getReplyRules, getShippingRules, getShippingRulesPage, resolveAutomationRun, resolveDeferredAutomationTask, updateDefaultReply, updateReplyRule, updateShippingRule } from './rules/api';
import { initializeAdmin, login, logout, verifySession } from './session/api';
import { changePassword, fetchAIModels, getSystemSettings, updateLoginCredentials, updateSystemSettings } from './settings/api';
import { appendCardData,batchCreateCards,createCard,deleteCard,getCardDetails,getCards,updateCard } from './cards/api';
import { getChatMessagePage,getChatMessages,getChatSessionPage,getChatSessions,markChatRead,sendChatImage,sendChatMessage } from './chat/api';
import { getDashboardStats,getOrderAnalytics,getValidOrders } from './dashboard/api';
import { cancelItemPublishBatch,createItem,deleteItem,deleteItemPublishBatch,getItemDetail,getItemPublishBatch,getItemPublishBatches,getItems,previewItemPublishBatch,publishItem,recommendPublishCategory,retryFailedItemPublishBatch,startItemPublishBatch,syncItemsFromAccount,updateItem } from './items/api';
import { createNotificationChannel,deleteAccountNotifications,deleteMessageNotification,deleteNotificationChannel,getAccountBindings,getMessageNotifications,getNotificationChannels,setAccountBindings,setMessageNotification,testNotificationChannel,updateNotificationChannel } from './notifications/api';
import { cancelOrderRefreshJob,deleteOrder,getAdminStats,getOrderDetail,getOrders,importOrders,manualShipOrder,syncOrders,syncSingleOrder,updateOrder } from './orders/api';
import { clearDefaultReplyRecords,deleteDefaultReply,deleteReplyRule,deleteShippingRule,getAutomationIssues,getDefaultReplies,getDefaultReply,getReplyRules,getShippingRules,getShippingRulesPage,resolveAutomationRun,resolveDeferredAutomationTask,updateDefaultReply,updateReplyRule,updateShippingRule } from './rules/api';
import { initializeAdmin,login,logout,verifySession } from './session/api';
import { changePassword,fetchAIModels,getSystemSettings,updateLoginCredentials,updateSystemSettings } from './settings/api';
import { getHealth } from './system/api';
afterEach(() => {
+8 -8
View File
@@ -1,12 +1,12 @@
import { get, post, put, del, postForm, type RequestControlOptions } from '../../../shared/http/client';
import {
SessionResponse, AccountDetail, AccountSummaryResponse, Order, PaginatedResponse,
AdminStats, DashboardStats, Card, SystemSettings, OrderAnalytics,
Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction, AutomationTriggerType,
NotificationChannel, NotificationEventType, AccountTaskSettings, ChatSession, ChatMessage, ItemListEnvelope, AutomationIssuesEnvelope,
CookieSettingsResponse, CookieProfileResponse, ItemDetailResponse, ItemPublishResponse, ItemSyncResponse, OrderDTOResponse, OrderDetailResponse, OrderSingleRefreshResponse, OrderBatchResponse, OrderRefreshResponse, OrderRefreshJobStartResponse, OrderRefreshJobStatusResponse, OrderRefreshJobCancelResponse, AutomationRuleResponse, AutomationRulePageResponse, AIReplySettingsResponse, AIModelsResponse, UserSettingResponse, CardBatchResponse, CardAppendResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchListResponse, BatchIDResponse, ItemPublishBatchResponse, BatchCancelResponse, MutationIDResponse, OperationResponse, NotificationChannelResponse, NotificationBinding, AccountBindingsResponse, CardListResponse, KeywordTypedResponse, DefaultReplyResponse, AccountTaskSettingsResponse, AccountTaskRunResponseEnvelope, AdminStatsResponse, DashboardStatsResponse, OrderAnalyticsResponse, QRLoginGenerateResponse, QRLoginStatusResponse, QRLoginVerificationResponse, ValidOrderResponse, ValidOrdersResponse
} from '../../../shared/api-contract';
import { collectionFrom, objectFrom } from '../../../shared/http/contract';
Card,
CardAppendResponse,
CardBatchResponse,
MutationIDResponse,OperationResponse
} from '../../../shared/api-contract/cards';
import { del,get,post,postForm,put,type RequestControlOptions } from '../../../shared/http/client';
import { collectionFrom } from '../../../shared/http/contract';
export type * from '../../../shared/api-contract/cards';
// Cards
// normalizeCard 归一化卡密数据。
const normalizeCard = (item: any): Card => {
@@ -1,6 +1,6 @@
import { expect, test } from 'vitest';
import type { Card } from '../../../shared/api-contract';
import { canSubmitAppend, filterCards, isCurrentCardRequest, previewAppendContent } from './batchState';
import { expect,test } from 'vitest';
import type { Card } from '../../../shared/api-contract/cards';
import { canSubmitAppend,filterCards,isCurrentCardRequest,previewAppendContent } from './batchState';
// cards 是卡密筛选测试使用的最小卡密组列表。
const cards = [
+1 -1
View File
@@ -1,4 +1,4 @@
import type { Card } from '../../../shared/api-contract';
import type { Card } from './api';
// filterCards 按类型和名称筛选卡密组,两个条件同时满足才保留。
export const filterCards = (
@@ -1,8 +1,7 @@
// @vitest-environment jsdom
import { act, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import type { Card } from '../../../shared/api-contract';
import { createCard, deleteCard, updateCard } from './api';
import { act,renderHook } from '@testing-library/react';
import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest';
import type { Card } from '../../../shared/api-contract/cards';
import { useCardActions } from './cardActions';
// cardActionMocks 保存卡密动作 Hook 测试使用的 API 替身。
+4 -4
View File
@@ -1,8 +1,8 @@
import { useCallback, useMemo, useState, type Dispatch, type SetStateAction } from 'react';
import type { Card } from '../../../shared/api-contract';
import { createCard, deleteCard, updateCard } from './api';
import { useCallback,useMemo,useState,type Dispatch,type SetStateAction } from 'react';
import type { Card } from './api';
import { createCard,deleteCard,updateCard } from './api';
import { filterCards } from './batchState';
import type { AddCardForm, EditCardForm } from './types';
import type { AddCardForm,EditCardForm } from './types';
// emptyAddForm 创建新增卡密组表单的初始值。
export const emptyAddForm = (): AddCardForm => ({
@@ -1,7 +1,7 @@
import { FileDown,ListPlus,Loader2,Plus,Upload,X } from 'lucide-react';
import React from 'react';
import { createPortal } from 'react-dom';
import { FileDown, ListPlus, Loader2, Plus, Upload, X } from 'lucide-react';
import type { Card } from '../../../../shared/api-contract';
import type { Card } from '../api';
import type { CardBatchModalProps } from '../types';
// BatchCardImportModal 负责卡密批量创建和单组库存追加的交互界面。
@@ -1,6 +1,6 @@
import { Code,CreditCard,FileText,Image as ImageIcon } from 'lucide-react';
import React from 'react';
import { Code, CreditCard, FileText, Image as ImageIcon } from 'lucide-react';
import type { Card } from '../../../../shared/api-contract';
import type { Card } from '../api';
// CardIconProps 描述库存图标所需的卡密类型参数。
interface CardIconProps {
+5 -5
View File
@@ -1,9 +1,9 @@
// @vitest-environment jsdom
import { act, renderHook, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, test, vi } from 'vitest';
import type { Card } from '../../../shared/api-contract';
import { appendCardData, batchCreateCards, getCards } from './api';
import { useCardBatchActions, useCardsData } from './hooks';
import { act,renderHook,waitFor } from '@testing-library/react';
import { beforeEach,describe,expect,test,vi } from 'vitest';
import type { Card } from '../../../shared/api-contract/cards';
import { appendCardData,batchCreateCards,getCards } from './api';
import { useCardBatchActions,useCardsData } from './hooks';
vi.mock('./api', /* cardsApiMockFactory 提供卡密 Hook 的确定性 API 替身。 */ () => ({
appendCardData: vi.fn(),
+4 -4
View File
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useMemo, useRef, useState, type Dispatch, type SetStateAction } from 'react';
import { appendCardData, batchCreateCards, getCards } from './api';
import type { Card } from '../../../shared/api-contract';
import { canSubmitAppend, isCurrentCardRequest, previewAppendContent } from './batchState';
import { useCallback,useEffect,useMemo,useRef,useState,type Dispatch,type SetStateAction } from 'react';
import type { Card } from './api';
import { appendCardData,batchCreateCards,getCards } from './api';
import { canSubmitAppend,isCurrentCardRequest,previewAppendContent } from './batchState';
import type { CardBatchState } from './types';
// CardsDataResult 暴露卡密库存、加载状态和可复用刷新动作。
@@ -1,8 +1,7 @@
// @vitest-environment jsdom
import React from 'react';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import type { Card } from '../../../../shared/api-contract';
import { cleanup,fireEvent,render,screen,waitFor } from '@testing-library/react';
import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest';
import type { Card } from '../../../../shared/api-contract/cards';
// cardListMocks 保存卡密页面测试使用的 Hook、API 和批量弹窗替身。
const cardListMocks = vi.hoisted(/* cardListMockFactory 创建卡密页面共享替身。 */ () => ({
@@ -1,11 +1,11 @@
import { Copy,CreditCard,Edit,FileText,Image as ImageIcon,Package,Plus,Save,Search,SlidersHorizontal,Trash2,Upload,X } from 'lucide-react';
import React from 'react';
import { createPortal } from 'react-dom';
import { Card } from '../../../../shared/api-contract';
import { Plus, CreditCard, FileText, Image as ImageIcon, Edit, Trash2, Save, X, Eye, EyeOff, Package, Copy, Upload, Loader2, Search, SlidersHorizontal } from 'lucide-react';
import { Card } from '../api';
import { useCardActions } from '../cardActions';
import { BatchCardImportModal } from '../components/BatchCardImportModal';
import { CardIcon } from '../components/CardIcon';
import { useCardBatchActions, useCardsData } from '../hooks';
import { useCardActions } from '../cardActions';
import { useCardBatchActions,useCardsData } from '../hooks';
// CardList 渲染卡密列表组件。
const CardList: React.FC = () => {
+2 -2
View File
@@ -1,5 +1,5 @@
import type { Dispatch, SetStateAction } from 'react';
import type { Card, CardAppendResponse, CardBatchResponse } from '../../../shared/api-contract';
import type { Dispatch,SetStateAction } from 'react';
import type { Card,CardAppendResponse,CardBatchResponse } from './api';
// AddCardForm 描述新增卡密组弹窗中的可编辑字段。
export interface AddCardForm {
+8 -8
View File
@@ -1,12 +1,12 @@
import { get, post, put, del, postForm, type RequestControlOptions } from '../../../shared/http/client';
import {
SessionResponse, AccountDetail, AccountSummaryResponse, Order, PaginatedResponse,
AdminStats, DashboardStats, Card, SystemSettings, OrderAnalytics,
Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction, AutomationTriggerType,
NotificationChannel, NotificationEventType, AccountTaskSettings, ChatSession, ChatMessage, ItemListEnvelope, AutomationIssuesEnvelope,
CookieSettingsResponse, CookieProfileResponse, ItemDetailResponse, ItemPublishResponse, ItemSyncResponse, OrderDTOResponse, OrderDetailResponse, OrderSingleRefreshResponse, OrderBatchResponse, OrderRefreshResponse, OrderRefreshJobStartResponse, OrderRefreshJobStatusResponse, OrderRefreshJobCancelResponse, AutomationRuleResponse, AutomationRulePageResponse, AIReplySettingsResponse, AIModelsResponse, UserSettingResponse, CardBatchResponse, CardAppendResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchListResponse, BatchIDResponse, ItemPublishBatchResponse, BatchCancelResponse, MutationIDResponse, OperationResponse, NotificationChannelResponse, NotificationBinding, AccountBindingsResponse, CardListResponse, KeywordTypedResponse, DefaultReplyResponse, AccountTaskSettingsResponse, AccountTaskRunResponseEnvelope, AdminStatsResponse, DashboardStatsResponse, OrderAnalyticsResponse, QRLoginGenerateResponse, QRLoginStatusResponse, QRLoginVerificationResponse, ValidOrderResponse, ValidOrdersResponse
} from '../../../shared/api-contract';
import { collectionFrom, objectFrom } from '../../../shared/http/contract';
AccountDetail,
ChatMessage,
ChatSession,
OperationResponse
} from '../../../shared/api-contract/chat';
import { get,post,postForm,type RequestControlOptions } from '../../../shared/http/client';
import { objectFrom } from '../../../shared/http/contract';
export type * from '../../../shared/api-contract/chat';
import type { ChatReadReceipt } from './types';
/** 聊天账号选择器读取非敏感账号摘要。 */
+5 -5
View File
@@ -1,10 +1,10 @@
// @vitest-environment jsdom
import { act, renderHook, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, test, vi } from 'vitest';
import type { AccountDetail, ChatMessage, ChatSession } from '../../../shared/api-contract';
import { getAccountDetails, getAccountRuntimeStatuses, getChatMessagePage, getChatSessionPage, markChatRead, sendChatImage, sendChatMessage } from './api';
import { act,renderHook,waitFor } from '@testing-library/react';
import { beforeEach,describe,expect,test,vi } from 'vitest';
import type { AccountDetail,ChatMessage,ChatSession } from '../../../shared/api-contract/chat';
import { getAccountDetails,getAccountRuntimeStatuses,getChatMessagePage,getChatSessionPage,markChatRead,sendChatImage,sendChatMessage } from './api';
import { useChat } from './hooks';
import { publishChatConnectionState, publishChatLiveMessage } from './liveEvents';
import { publishChatConnectionState,publishChatLiveMessage } from './liveEvents';
vi.mock('./api', /* chatApiMockFactory 提供聊天 Hook 的确定性 API 替身。 */ () => ({
getAccountDetails: vi.fn(),
+7 -7
View File
@@ -1,11 +1,11 @@
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import type React from 'react';
import type { AccountDetail, ChatMessage, ChatSession } from '../../../shared/api-contract';
import { emojiURL, renderXianyuText, xianyuEmojis } from '../../../chatEmojis';
import { getAccountDetails, getAccountRuntimeStatuses, getChatMessagePage, getChatSessionPage, markChatRead, sendChatImage, sendChatMessage } from './api';
import { publishChatUnreadStatus, subscribeToChatLiveEvents } from './liveEvents';
import { collectChatReadReceipts, filterChatSessions, formatClock, isChatAbortError, isCurrentChatRequest, markOutgoingMessagesReadByIncoming, mergeLiveMessage, mergeOlderMessages, messageTime } from './state';
import type { ChatFeatureState, ChatLiveState, SessionsByAccount } from './types';
import { useCallback,useEffect,useLayoutEffect,useMemo,useRef,useState } from 'react';
import { emojiURL,renderXianyuText,xianyuEmojis } from '../../../chatEmojis';
import type { AccountDetail,ChatMessage,ChatSession } from './api';
import { getAccountDetails,getAccountRuntimeStatuses,getChatMessagePage,getChatSessionPage,markChatRead,sendChatImage,sendChatMessage } from './api';
import { publishChatUnreadStatus,subscribeToChatLiveEvents } from './liveEvents';
import { collectChatReadReceipts,filterChatSessions,formatClock,isChatAbortError,isCurrentChatRequest,markOutgoingMessagesReadByIncoming,mergeLiveMessage,mergeOlderMessages,messageTime } from './state';
import type { ChatFeatureState,ChatLiveState,SessionsByAccount } from './types';
/** PendingImagePreview 描述等待用户确认的本地图片预览及其资源所有权。 */
type PendingImagePreview = {
+1 -1
View File
@@ -1,4 +1,4 @@
import type { ChatMessage } from '../../../shared/api-contract';
import type { ChatMessage } from './api';
import type { ChatLiveState } from './types';
/** ChatLiveEvent 描述全局聊天连接向已挂载聊天页面发布的最小实时事件集合。 */
+4 -4
View File
@@ -1,12 +1,12 @@
import React from 'react';
import {
AlertCircle, Check, CheckCheck, ImagePlus, Loader2, MessageCircleMore, RefreshCw,
Search, Send, Smile, UserRound, Wifi, WifiOff, X,
AlertCircle,Check,CheckCheck,ImagePlus,Loader2,MessageCircleMore,RefreshCw,
Search,Send,Smile,UserRound,Wifi,WifiOff,X,
} from 'lucide-react';
import React from 'react';
import Lightbox from 'yet-another-react-lightbox';
import 'yet-another-react-lightbox/styles.css';
import { useChat } from '../hooks';
import { unreadBadgeClassName, unreadBadgeLabel } from '../state';
import { unreadBadgeClassName,unreadBadgeLabel } from '../state';
// Chat 展示实时会话、消息分页和消息发送界面。
const Chat: React.FC = () => {
+3 -3
View File
@@ -1,6 +1,6 @@
import { expect, test } from 'vitest';
import type { ChatMessage, ChatSession } from '../../../shared/api-contract';
import { collectChatReadReceipts, filterChatSessions, formatClock, isChatAbortError, isCurrentChatRequest, markOutgoingMessagesReadByIncoming, mergeLiveMessage, mergeOlderMessages, messageTime, unreadBadgeClassName, unreadBadgeLabel } from './state';
import { expect,test } from 'vitest';
import type { ChatMessage,ChatSession } from '../../../shared/api-contract/chat';
import { collectChatReadReceipts,filterChatSessions,formatClock,isChatAbortError,isCurrentChatRequest,markOutgoingMessagesReadByIncoming,mergeLiveMessage,mergeOlderMessages,messageTime,unreadBadgeClassName,unreadBadgeLabel } from './state';
// sessionFixture 是覆盖搜索、未读筛选和联系人隔离的最小会话数据。
const sessionFixture: ChatSession[] = [
+1 -1
View File
@@ -1,4 +1,4 @@
import type { ChatMessage, ChatSession } from '../../../shared/api-contract';
import type { ChatMessage,ChatSession } from './api';
import type { ChatReadReceipt } from './types';
/** 将未读数规范为徽标可展示的文本,超过两位数时统一显示 99+。 */
@@ -1,10 +1,10 @@
// @vitest-environment jsdom
import { act, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import type { ChatMessage } from '../../../shared/api-contract';
import { getAccountDetails, getChatSessionPage } from './api';
import { act,renderHook } from '@testing-library/react';
import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest';
import type { ChatMessage } from '../../../shared/api-contract/chat';
import { getAccountDetails,getChatSessionPage } from './api';
import { publishChatUnreadStatus } from './liveEvents';
import { formatChatNewMessageTitle, useChatTitleNotification, useChatTitleNotifier } from './titleNotification';
import { formatChatNewMessageTitle,useChatTitleNotification,useChatTitleNotifier } from './titleNotification';
vi.mock('./api', /* chatApiMockFactory 提供标题通知初始化未读状态读取的确定性 API 替身。 */ () => ({
getAccountDetails: vi.fn(),
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import type { ChatMessage } from '../../../shared/api-contract';
import { getAccountDetails, getChatSessionPage } from './api';
import { publishChatConnectionState, publishChatLiveMessage, subscribeToChatUnreadStatus } from './liveEvents';
import { useCallback,useEffect,useRef,useState } from 'react';
import type { ChatMessage } from './api';
import { getAccountDetails,getChatSessionPage } from './api';
import { publishChatConnectionState,publishChatLiveMessage,subscribeToChatUnreadStatus } from './liveEvents';
/** titleFlashIntervalMs 定义浏览器标题在提示文本与原始标题间切换的周期,单位为毫秒。 */
const titleFlashIntervalMs = 1_000;
+1 -1
View File
@@ -1,4 +1,4 @@
import type { AccountDetail, ChatMessage, ChatSession } from '../../../shared/api-contract';
import type { AccountDetail,ChatMessage,ChatSession } from './api';
/** 按账号保存会话列表。 */
export type SessionsByAccount = Record<string, ChatSession[]>;
@@ -1,6 +1,6 @@
import React from 'react';
import { ShoppingCart } from 'lucide-react';
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, BarChart, Bar, Cell } from 'recharts';
import React from 'react';
import { Area,AreaChart,Bar,BarChart,CartesianGrid,Cell,ResponsiveContainer,Tooltip,XAxis,YAxis } from 'recharts';
import type { DashboardChartPoint } from './state';
/** 趋势图组件的输入参数。 */
+4 -3
View File
@@ -1,7 +1,8 @@
import { get, type RequestControlOptions } from '../../../shared/http/client';
import { collectionFrom, objectFrom } from '../../../shared/http/contract';
import type { DashboardStatsResponse, Item, ItemListEnvelope, Order, OrderAnalyticsResponse, OrderStatus, ValidOrderResponse, ValidOrdersResponse } from '../../../shared/api-contract';
import { formatLocalDate } from '../../../dateRange';
import type { DashboardStatsResponse,Item,ItemListEnvelope,Order,OrderAnalyticsResponse,OrderStatus,ValidOrderResponse,ValidOrdersResponse } from '../../../shared/api-contract/admin';
import { get,type RequestControlOptions } from '../../../shared/http/client';
import { collectionFrom,objectFrom } from '../../../shared/http/contract';
export type * from '../../../shared/api-contract/admin';
/** 仪表盘订单明细接口转换后的分页结果。 */
export interface ValidOrdersResult {
@@ -1,10 +1,10 @@
// @vitest-environment jsdom
import { act, renderHook, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, test, vi } from 'vitest';
import type { DashboardStats, Item, OrderAnalyticsResponse } from '../../../shared/api-contract';
import { getDashboardStats, getItems, getOrderAnalytics, getValidOrders } from './api';
import { useDashboard } from './hooks';
import { act,renderHook,waitFor } from '@testing-library/react';
import { beforeEach,describe,expect,test,vi } from 'vitest';
import type { DashboardStats,Item,OrderAnalyticsResponse } from '../../../shared/api-contract/admin';
import { getDashboardStats,getItems,getOrderAnalytics,getValidOrders } from './api';
import type { UseDashboardOptions } from './hooks';
import { useDashboard } from './hooks';
vi.mock('./api', /* dashboardApiMockFactory 提供仪表盘 Hook 的确定性 API 替身。 */ () => ({
getDashboardStats: vi.fn(),
+5 -6
View File
@@ -1,9 +1,8 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { getDateRange, getPreviousDateRange } from '../../../dateRange';
import type { TimeRange } from '../../../dateRange';
import { buildCategoryData, buildChartData, buildItemNameMap, buildProductSalesData, buildSourceData, getMaxProductSales, getRangeLabel, getTrendPercent, isCurrentDashboardRequest } from './state';
import { getDashboardStats, getItems, getOrderAnalytics, getValidOrders } from './api';
import type { DashboardData, DashboardRangeSelection, DashboardStatus } from './types';
import { useCallback,useEffect,useMemo,useRef,useState } from 'react';
import { getDateRange,getPreviousDateRange } from '../../../dateRange';
import { getDashboardStats,getItems,getOrderAnalytics,getValidOrders } from './api';
import { buildCategoryData,buildChartData,buildItemNameMap,buildProductSalesData,buildSourceData,getMaxProductSales,getRangeLabel,getTrendPercent,isCurrentDashboardRequest } from './state';
import type { DashboardData,DashboardRangeSelection,DashboardStatus } from './types';
/** Dashboard Hook 的输入参数。 */
export type UseDashboardOptions = DashboardRangeSelection & { /** customRangeVersion 表示自定义范围版本。 */ customRangeVersion: number };
@@ -1,8 +1,7 @@
import React from 'react';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { renderToStaticMarkup } from 'react-dom/server';
import { describe, expect, test } from 'vitest';
import { describe,expect,test } from 'vitest';
import { StatusBadge } from './Dashboard';
// dashboardSource 仪表盘测试数据源。
@@ -1,11 +1,11 @@
import React, { useState } from 'react';
import { OrderStatus } from '../../../../shared/api-contract';
import { getDateRange, TimeRange } from '../../../../dateRange';
import { Activity,AlertCircle,DollarSign,ExternalLink,Package,PackageCheck,ShoppingCart,TrendingUp,Users } from 'lucide-react';
import React,{ useState } from 'react';
import { Cell,Legend,Pie,PieChart,ResponsiveContainer,Tooltip } from 'recharts';
import { getDateRange,TimeRange } from '../../../../dateRange';
import { formatLocalDateTime } from '../../../../dateTime';
import { TrendingUp, Users, ShoppingCart, AlertCircle, DollarSign, Activity, Package, ArrowUpRight, Calendar, X, BarChart3, PackageCheck, ExternalLink, Eye, Edit } from 'lucide-react';
import { Tooltip, ResponsiveContainer, PieChart, Pie, Cell, Legend } from 'recharts';
import { useDashboard } from '../hooks';
import { OrderStatus } from '../api';
import { DashboardTrendChart } from '../DashboardTrendChart';
import { useDashboard } from '../hooks';
// cssColor 状态颜色样式。
const cssColor = (token: string, alpha?: number) => (
@@ -84,8 +84,6 @@ const Dashboard: React.FC = () => {
const stats = data?.stats || null;
// analytics 统计分析数据。
const analytics = data?.analytics || null;
// previousAnalytics 上一份统计数据。
const previousAnalytics = data?.previousAnalytics || null;
// validOrders 有效订单列表。
const validOrders = data?.validOrders.orders || [];
// validOrdersTotal 有效数据订单列表总数,负责当前功能中的对应处理。
@@ -1,6 +1,6 @@
import { expect, test } from 'vitest';
import type { OrderAnalytics } from '../../../shared/api-contract';
import { buildCategoryData, buildChartData, buildItemNameMap, buildProductSalesData, buildSourceData, getMaxProductSales, getRangeLabel, getTrendPercent, isCurrentDashboardRequest } from './state';
import { expect,test } from 'vitest';
import type { OrderAnalytics } from '../../../shared/api-contract/admin';
import { buildCategoryData,buildChartData,buildItemNameMap,buildProductSalesData,buildSourceData,getMaxProductSales,getRangeLabel,getTrendPercent,isCurrentDashboardRequest } from './state';
// analyticsFixture 是覆盖趋势、商品排行和零值边界的最小分析数据。
const analyticsFixture: OrderAnalytics = {
+2 -2
View File
@@ -1,5 +1,5 @@
import type { Item, OrderAnalytics } from '../../../shared/api-contract';
import type { DateRange, TimeRange } from '../../../dateRange';
import type { TimeRange } from '../../../dateRange';
import type { Item,OrderAnalytics } from './api';
import type { DashboardRangeSelection } from './types';
/** 趋势图中的单个日期数据点。 */
+2 -2
View File
@@ -1,5 +1,5 @@
import type { Item, Order, OrderAnalytics, DashboardStats } from '../../../shared/api-contract';
import type { DateRange, TimeRange } from '../../../dateRange';
import type { DateRange,TimeRange } from '../../../dateRange';
import type { DashboardStats,Item,Order,OrderAnalytics } from './api';
/** Dashboard 请求状态。 */
export type DashboardRequestState = 'idle' | 'loading' | 'success' | 'error';
@@ -1,6 +1,6 @@
// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { getPublishLocations, amapPOIToPublishLocation } from './amapLocation';
import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest';
import { amapPOIToPublishLocation,getPublishLocations } from './amapLocation';
// placeSearchFactory 创建不访问高德网络的地点搜索替身。
const placeSearchFactory = (status: string, pois: unknown[] = []) => vi.fn(function placeSearchConstructor() {
@@ -1,5 +1,5 @@
// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest';
// SCRIPT_ID 是高德脚本加载器使用的固定 DOM 标识。
const SCRIPT_ID = 'ydisks-amap-js-api';
@@ -1,4 +1,4 @@
import { expect, test } from 'vitest';
import { expect,test } from 'vitest';
import { amapPOIToPublishLocation } from './amapLocation';
test('maps AMap POI fields to the publish location shape', () => {
@@ -1,4 +1,4 @@
import type { PublishLocation } from '../shared/api-contract';
import type { PublishLocation } from './api';
const AMAP_SCRIPT_ID = 'ydisks-amap-js-api'; /* AMAP_SCRIPT_ID 表示AMAPSCRIPTID。 */
// 高德 JS API 的 Key 是前端公开 Key;部署时可通过 VITE_AMAP_JS_KEY 覆盖。
@@ -0,0 +1,13 @@
import { describe, expect, test } from 'vitest';
import { ApiError } from '../../../shared/http/client';
import { itemErrorMessage } from './api';
// 商品 API 错误码适配测试覆盖权限、冲突、人工核对和可重试的恢复分支。
describe('items API error adapter', /* 商品错误适配测试组覆盖稳定机器码到恢复指引的映射。 */ () => {
test('按统一机器错误码输出可执行的恢复提示', /* 当前回调验证权限、冲突、人工核对和重试提示。 */ () => {
expect(itemErrorMessage(new ApiError(403, { code: 'stock_permission_missing', message: 'forbidden' }), 'fallback')).toContain('库存发布权限');
expect(itemErrorMessage(new ApiError(409, { code: 'conflict', message: 'conflict' }), 'fallback')).toContain('刷新后重试');
expect(itemErrorMessage(new ApiError(502, { code: 'external_result_unknown', message: 'unknown' }), 'fallback')).toContain('人工核对');
expect(itemErrorMessage(new ApiError(503, { code: 'retryable', message: 'retry' }), 'fallback')).toContain('稍后重试');
});
});
+43 -11
View File
@@ -1,14 +1,21 @@
import { get, post, put, del, postForm, type RequestControlOptions } from '../../../shared/http/client';
import type { PublishLocation } from '../../../shared/api-contract/items';
import {
SessionResponse, AccountDetail, AccountSummaryResponse, Order, PaginatedResponse,
AdminStats, DashboardStats, Card, SystemSettings, OrderAnalytics,
Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction, AutomationTriggerType,
NotificationChannel, NotificationEventType, AccountTaskSettings, ChatSession, ChatMessage, ItemListEnvelope, AutomationIssuesEnvelope,
CookieSettingsResponse, CookieProfileResponse, ItemDetailResponse, ItemPublishResponse, ItemSyncResponse, OrderDTOResponse, OrderDetailResponse, OrderSingleRefreshResponse, OrderBatchResponse, OrderRefreshResponse, OrderRefreshJobStartResponse, OrderRefreshJobStatusResponse, OrderRefreshJobCancelResponse, AutomationRuleResponse, AutomationRulePageResponse, AIReplySettingsResponse, AIModelsResponse, UserSettingResponse, CardBatchResponse, CardAppendResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchListResponse, BatchIDResponse, ItemPublishBatchResponse, BatchCancelResponse, MutationIDResponse, OperationResponse, NotificationChannelResponse, NotificationBinding, AccountBindingsResponse, CardListResponse, KeywordTypedResponse, DefaultReplyResponse, AccountTaskSettingsResponse, AccountTaskRunResponseEnvelope, AdminStatsResponse, DashboardStatsResponse, OrderAnalyticsResponse, QRLoginGenerateResponse, QRLoginStatusResponse, QRLoginVerificationResponse, ValidOrderResponse, ValidOrdersResponse
} from '../../../shared/api-contract';
import { collectionFrom, objectFrom } from '../../../shared/http/contract';
import { getPublishLocations as queryPublishLocations, type PublishLocationRequestOptions } from '../../../services/amapLocation';
import type { PublishLocation } from '../../../shared/api-contract';
AccountDetail,
BatchCancelResponse,
BatchIDResponse,
CategoryRecommendationResponse,
Item,
ItemDetailResponse,
ItemPublishBatchPreviewResponse,
ItemPublishBatchResponse,
ItemPublishResponse,ItemSyncResponse,
OperationResponse,
ShippingRule
} from '../../../shared/api-contract/items';
import { ApiError,del,get,post,postForm,put,type RequestControlOptions } from '../../../shared/http/client';
import { collectionFrom } from '../../../shared/http/contract';
export type * from '../../../shared/api-contract/items';
import { getPublishLocations as queryPublishLocations,type PublishLocationRequestOptions } from './amapLocation';
/** 商品账号筛选器读取非敏感账号摘要。 */
export const getAccountDetails = async (options?: RequestControlOptions): Promise<AccountDetail[]> => get('/api/v1/accounts/details', undefined, options);
@@ -18,7 +25,32 @@ export const getShippingRules = async (options?: RequestControlOptions): Promise
// getPublishLocations 通过 feature API 边界读取地点,并把取消/超时控制传入地图服务。
export const getPublishLocations = (longitude: number, latitude: number, options?: PublishLocationRequestOptions): Promise<PublishLocation[]> => queryPublishLocations(longitude, latitude, options);
export type { PublishLocation } from '../../../shared/api-contract';
export type { PublishLocation } from '../../../shared/api-contract/items';
// itemErrorMessage 将统一 HTTP 错误码归一为商品 feature 可执行的用户提示。
export const itemErrorMessage = (error: unknown, fallback: string): string => {
if (error instanceof ApiError) {
switch (error.code) {
case 'stock_permission_missing':
return '发布失败:该账号没有库存发布权限,无法按库存数量发布商品。请换账号或先在闲鱼确认库存能力。';
case 'conflict':
case 'item_conflict':
return '商品状态已发生变化,请刷新后重试。';
case 'external_result_unknown':
case 'manual_review_required':
return '平台结果暂时无法确认,请先人工核对闲鱼状态,再决定是否重试。';
case 'retryable':
case 'temporarily_unavailable':
return '平台暂时不可用,请稍后重试。';
default:
return error.message || fallback;
}
}
if (error instanceof Error) return error.message;
// message 保存兼容 API 错误对象中的文本说明。
const message = typeof error === 'object' && error !== null && 'message' in error ? (error as { /** message 是兼容错误对象中的文本说明。 */ message?: unknown }).message : undefined;
return typeof message === 'string' ? message : fallback;
};
// Items
// normalizeBooleanFlag 归一化布尔标记。
const normalizeBooleanFlag = (value: unknown): boolean =>
@@ -1,12 +1,12 @@
import { describe, expect, test } from 'vitest';
import { describe,expect,test } from 'vitest';
import {
batchStatusText,
batchStatusClass,
canRetryBatch,
canStartBatch,
isBatchInProgress,
isCurrentBatchRequest,
selectActivePublishBatch,
batchStatusClass,
batchStatusText,
canRetryBatch,
canStartBatch,
isBatchInProgress,
isCurrentBatchRequest,
selectActivePublishBatch,
} from './batchState';
// ItemList 批量行为测试覆盖预检、取消、重试和过期任务响应。
+11 -11
View File
@@ -1,16 +1,16 @@
// @vitest-environment jsdom
import { act, renderHook, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, test, vi } from 'vitest';
import type { BatchCancelResponse, BatchIDResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchResponse } from '../../../shared/api-contract';
import { act,renderHook } from '@testing-library/react';
import { beforeEach,describe,expect,test,vi } from 'vitest';
import type { BatchCancelResponse,BatchIDResponse,CategoryRecommendationResponse,ItemPublishBatchPreviewResponse,ItemPublishBatchResponse } from '../../../shared/api-contract/items';
import {
cancelItemPublishBatch,
deleteItemPublishBatch,
getItemPublishBatch,
getItemPublishBatches,
previewItemPublishBatch,
recommendPublishCategory,
retryFailedItemPublishBatch,
startItemPublishBatch,
cancelItemPublishBatch,
deleteItemPublishBatch,
getItemPublishBatch,
getItemPublishBatches,
previewItemPublishBatch,
recommendPublishCategory,
retryFailedItemPublishBatch,
startItemPublishBatch,
} from './api';
import { useItemPublishBatch } from './hooks';
+16 -16
View File
@@ -1,22 +1,22 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useCallback,useEffect,useRef,useState } from 'react';
import {
cancelItemPublishBatch,
deleteItemPublishBatch,
getItemPublishBatch,
getItemPublishBatches,
recommendPublishCategory,
previewItemPublishBatch,
retryFailedItemPublishBatch,
startItemPublishBatch,
cancelItemPublishBatch,
deleteItemPublishBatch,
getItemPublishBatch,
getItemPublishBatches,
previewItemPublishBatch,
recommendPublishCategory,
retryFailedItemPublishBatch,
startItemPublishBatch,
} from './api';
import { canRetryBatch, canStartBatch, isBatchInProgress, isCurrentBatchRequest, selectActivePublishBatch } from './batchState';
import { canRetryBatch,canStartBatch,isBatchInProgress,isCurrentBatchRequest,selectActivePublishBatch } from './batchState';
import type {
BatchFallbackCategory,
BatchPhase,
ItemPublishBatchOptions,
ItemPublishBatchState,
PublishBatchDetail,
PublishBatchPreview,
BatchFallbackCategory,
BatchPhase,
ItemPublishBatchOptions,
ItemPublishBatchState,
PublishBatchDetail,
PublishBatchPreview,
} from './types';
// useItemPublishBatch 集中管理批量铺货的表单、任务恢复、轮询和重试状态。
@@ -1,15 +1,16 @@
// @vitest-environment jsdom
import { act, renderHook } from '@testing-library/react';
import { act,renderHook } from '@testing-library/react';
import { useState } from 'react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import type { Item } from '../../../shared/api-contract';
import { createItem, deleteItem, getPublishLocations, publishItem, syncItemsFromAccount, updateItem } from './api';
import { useItemActions, type ItemActionsOptions } from './itemActions';
import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest';
import type { Item } from '../../../shared/api-contract/items';
import { createItem,deleteItem,getPublishLocations,publishItem,syncItemsFromAccount,updateItem } from './api';
import { useItemActions,type ItemActionsOptions } from './itemActions';
vi.mock('./api', /* itemActionsApiMockFactory 提供商品动作 Hook 的确定性 API 替身。 */ () => ({
createItem: vi.fn(),
deleteItem: vi.fn(),
getPublishLocations: vi.fn(),
itemErrorMessage: /* errorMessageMock 将测试动作中的异常转换为稳定回退文本。 */ (error: unknown, fallback: string) => error instanceof Error ? error.message : fallback,
publishItem: vi.fn(),
syncItemsFromAccount: vi.fn(),
updateItem: vi.fn(),
+3 -17
View File
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useRef, useState, type Dispatch, type SetStateAction } from 'react';
import type { Item } from '../../../shared/api-contract';
import { createItem, deleteItem, getPublishLocations, publishItem, syncItemsFromAccount, updateItem } from './api';
import { useCallback,useEffect,useRef,useState,type Dispatch,type SetStateAction } from 'react';
import type { Item } from './api';
import type { PublishLocation } from './api';
import { createItem,deleteItem,getPublishLocations,itemErrorMessage,publishItem,syncItemsFromAccount,updateItem } from './api';
// AddItemForm 描述手动添加商品弹窗的表单字段。
export interface AddItemForm {
@@ -135,14 +135,6 @@ export const emptyAddItemForm = (): AddItemForm => ({ cookie_id: '', item_id: ''
// emptyPublishItemForm 创建普通发布商品表单的初始值。
export const emptyPublishItemForm = (cookieID = ''): PublishItemForm => ({ cookie_id: cookieID, title: '', description: '', price: '', original_price: '', quantity: '1', postage_mode: 'free', postage: '', images: [] });
// itemErrorMessage 将未知异常转换为稳定的商品操作提示。
const itemErrorMessage = (error: unknown, fallback: string): string => {
if (error instanceof Error) return error.message;
// message 保存兼容 API 错误对象中的文本说明。
const message = typeof error === 'object' && error !== null && 'message' in error ? (error as { /** message 是兼容错误对象中的文本说明。 */ message?: unknown }).message : undefined;
return typeof message === 'string' ? message : fallback;
};
// useItemActions 集中管理商品同步、编辑、删除、添加、普通发布和定位动作。
export const useItemActions = ({ selectedAccount, setSelectedAccount, setItems, loadItems, loadShippingRules, onConfigureDelivery, setBatchLocations, setBatchLocation }: ItemActionsOptions): ItemActionsState => {
// loading 表示商品同步请求是否正在执行。
@@ -302,12 +294,6 @@ export const useItemActions = ({ selectedAccount, setSelectedAccount, setItems,
}
} catch (/* error 表示商品发布请求异常。 */ error: unknown) {
console.error('发布商品失败:', error);
// payload 保存服务端返回的结构化错误载荷。
const payload = (error as { /** payload 是服务端结构化错误载荷。 */ payload?: { /** code 是服务端错误码。 */ code?: unknown } })?.payload;
if (payload?.code === 'stock_permission_missing') {
alert('发布失败:该账号没有库存发布权限,无法按库存数量发布商品。请换账号或先在闲鱼确认库存能力。');
return;
}
alert(itemErrorMessage(error, '发布失败,请重试'));
} finally {
setPublishing(false);
+10 -11
View File
@@ -1,19 +1,18 @@
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { ArrowRight,Box,CheckCircle2,CircleDashed,Edit,Filter,Link2,LocateFixed,PackagePlus,Plus,RefreshCw,Save,Search,ShoppingBag,Trash2,UploadCloud,User,X } from 'lucide-react';
import React,{ useCallback,useEffect,useMemo,useRef,useState } from 'react';
import { createPortal } from 'react-dom';
import type { Item } from '../../../../shared/api-contract';
import type { AccountDetail,Item,ShippingRule } from '../api';
import {
getItems,
getAccountDetails,
getShippingRules,
getItemPublishBatches,
getAccountDetails,
getItemPublishBatches,
getItems,
getShippingRules,
} from '../api';
import type { AccountDetail, ShippingRule } from '../../../../shared/api-contract';
import type { ItemListProps } from '../types';
import { batchStatusClass,batchStatusText } from '../batchState';
import { BatchPhaseIndicator } from '../components/BatchPhaseIndicator';
import { useItemPublishBatch } from '../hooks';
import { useItemActions } from '../itemActions';
import { batchStatusClass, batchStatusText } from '../batchState';
import { BatchPhaseIndicator } from '../components/BatchPhaseIndicator';
import { ArrowRight, Box, CheckCircle2, CircleDashed, Edit, Filter, Link2, LocateFixed, PackagePlus, Plus, RefreshCw, Save, Search, ShoppingBag, Trash2, UploadCloud, User, X } from 'lucide-react';
import type { ItemListProps } from '../types';
// formatItemPrice 将商品价格转换为本地化展示文本。
const formatItemPrice = (price?: string) => {
+2 -2
View File
@@ -1,5 +1,5 @@
import type { Dispatch, SetStateAction } from 'react';
import type { Item, AccountDetail, ShippingRule } from '../../../shared/api-contract';
import type { Dispatch,SetStateAction } from 'react';
import type { AccountDetail,Item,ShippingRule } from './api';
import type { PublishLocation } from './api';
// ItemListProps 描述商品页面从父级接收的规则配置回调。
+3 -2
View File
@@ -1,5 +1,6 @@
import { del, get, post, put, type RequestControlOptions } from '../../../shared/http/client';
import type { MutationIDResponse, NotificationBinding, NotificationChannel, NotificationChannelResponse, NotificationEventType, OperationResponse, SystemSettings } from '../../../shared/api-contract';
import type { MutationIDResponse,NotificationBinding,NotificationChannel,NotificationChannelResponse,NotificationEventType,OperationResponse,SystemSettings } from '../../../shared/api-contract/notifications';
import { del,get,post,put,type RequestControlOptions } from '../../../shared/http/client';
export type * from '../../../shared/api-contract/notifications';
/** 通知渠道写入时使用的具名请求 DTO。 */
export interface NotificationChannelRequest {
@@ -1,7 +1,7 @@
import { Bell,Edit2,Loader2,Send,Trash2 } from 'lucide-react';
import React from 'react';
import { Bell, Edit2, Loader2, Send, Trash2 } from 'lucide-react';
import type { NotificationChannel } from '../../../../shared/api-contract';
import { notificationChannelTypes, notificationEventSummary } from '../state';
import type { NotificationChannel } from '../api';
import { notificationChannelTypes,notificationEventSummary } from '../state';
// NotificationChannelListProps 描述通知渠道列表的操作边界。
export interface NotificationChannelListProps {
@@ -1,11 +1,11 @@
import { Bell,Check,Eye,EyeOff,Loader2,X } from 'lucide-react';
import React from 'react';
import { createPortal } from 'react-dom';
import { Bell, Check, Eye, EyeOff, Loader2, X } from 'lucide-react';
import { enableCustomSMTP } from '../../../../notificationEmailConfig';
import type { NotificationChannel,NotificationChannelType,NotificationEventType,SystemSettings } from '../api';
import { notificationChannelTypes } from '../state';
import { NotificationEventSelector } from './NotificationEventSelector';
import type { NotificationChannel, NotificationChannelType, NotificationEventType, SystemSettings } from '../../../../shared/api-contract';
import type { NotificationForm } from '../types';
import { NotificationEventSelector } from './NotificationEventSelector';
// NotificationChannelModalProps 描述渠道编辑弹窗所需的状态和回调。
export interface NotificationChannelModalProps {
@@ -1,7 +1,7 @@
import React from 'react';
import { Check } from 'lucide-react';
import React from 'react';
import type { NotificationEventType } from '../api';
import { notificationEvents } from '../state';
import type { NotificationEventType } from '../../../../shared/api-contract';
// NotificationEventSelectorProps 描述通知事件绑定组件的输入状态。
export interface NotificationEventSelectorProps {
@@ -1,6 +1,6 @@
import { Eye,EyeOff,Loader2,Mail,Save } from 'lucide-react';
import React from 'react';
import { Eye, EyeOff, Loader2, Mail, Save } from 'lucide-react';
import type { SystemSettings } from '../../../../shared/api-contract';
import type { SystemSettings } from '../api';
// NotificationSmtpSettingsProps 描述系统 SMTP 配置面板所需的状态和事件。
export interface NotificationSmtpSettingsProps {
@@ -1,8 +1,8 @@
// @vitest-environment jsdom
import { act, renderHook, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, test, vi } from 'vitest';
import type { NotificationChannel, SystemSettings } from '../../../shared/api-contract';
import { createNotificationChannel, deleteNotificationChannel, getNotificationChannels, getSystemSettings, testNotificationChannel, updateNotificationChannel, updateSystemSettings } from './api';
import { act,renderHook,waitFor } from '@testing-library/react';
import { beforeEach,describe,expect,test,vi } from 'vitest';
import type { NotificationChannel,SystemSettings } from '../../../shared/api-contract/notifications';
import { createNotificationChannel,deleteNotificationChannel,getNotificationChannels,getSystemSettings,testNotificationChannel,updateNotificationChannel,updateSystemSettings } from './api';
import { useNotifications } from './hooks';
vi.mock('./api', /* notificationsApiMockFactory 提供通知 Hook 的确定性 API 替身。 */ () => ({
+5 -5
View File
@@ -1,8 +1,8 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import type { NotificationChannel, NotificationChannelType, SystemSettings } from '../../../shared/api-contract';
import { createNotificationChannel, deleteNotificationChannel, getNotificationChannels, getSystemSettings, testNotificationChannel, updateNotificationChannel, updateSystemSettings } from './api';
import { buildNotificationPayload, emptyNotificationForm, isCurrentNotificationRequest, notificationErrorMessage, normalizeNotificationForm, validateNotificationForm } from './state';
import type { NotificationForm, NotificationState } from './types';
import { useCallback,useEffect,useRef,useState } from 'react';
import type { NotificationChannel,SystemSettings } from './api';
import { createNotificationChannel,deleteNotificationChannel,getNotificationChannels,getSystemSettings,testNotificationChannel,updateNotificationChannel,updateSystemSettings } from './api';
import { buildNotificationPayload,emptyNotificationForm,isCurrentNotificationRequest,normalizeNotificationForm,notificationErrorMessage,validateNotificationForm } from './state';
import type { NotificationForm,NotificationState } from './types';
// useNotifications 统一管理通知渠道、事件订阅和系统 SMTP 的异步状态。
export const useNotifications = (isAdmin: boolean): NotificationState => {
@@ -1,5 +1,5 @@
import { Bell,Check,Loader2,Plus,RefreshCw,X } from 'lucide-react';
import React from 'react';
import { Bell, Check, Loader2, Plus, RefreshCw, X } from 'lucide-react';
import { NotificationChannelList } from '../components/NotificationChannelList';
import { NotificationChannelModal } from '../components/NotificationChannelModal';
import { NotificationSmtpSettings } from '../components/NotificationSmtpSettings';
@@ -1,7 +1,7 @@
import { expect, test } from 'vitest';
import type { NotificationChannel } from '../../../shared/api-contract';
import { expect,test } from 'vitest';
import type { NotificationChannel } from '../../../shared/api-contract/notifications';
import { buildNotificationPayload,emptyNotificationForm,isCurrentNotificationRequest,normalizeNotificationForm,notificationErrorMessage,notificationEventSummary,validateNotificationForm } from './state';
import type { NotificationForm } from './types';
import { buildNotificationPayload, emptyNotificationForm, isCurrentNotificationRequest, normalizeNotificationForm, notificationErrorMessage, notificationEventSummary, validateNotificationForm } from './state';
// createForm 创建通知渠道校验使用的最小表单对象。
const createForm = (overrides: Partial<NotificationForm> = {}): NotificationForm => ({
+4 -4
View File
@@ -1,7 +1,7 @@
import { Bell, Mail, MessageCircle, Send as Telegram, Webhook } from 'lucide-react';
import type { NotificationChannel, NotificationChannelType, NotificationEventType, SystemSettings } from '../../../shared/api-contract';
import { buildEmailChannelConfig, enableCustomSMTP, normalizeEmailChannelConfig } from '../../../notificationEmailConfig';
import type { NotificationChannelMeta, NotificationEventMeta, NotificationForm, NotificationPayload } from './types';
import { Bell,Mail,MessageCircle,Send as Telegram,Webhook } from 'lucide-react';
import { buildEmailChannelConfig,enableCustomSMTP,normalizeEmailChannelConfig } from '../../../notificationEmailConfig';
import type { NotificationChannel,NotificationChannelType,NotificationEventType,SystemSettings } from './api';
import type { NotificationChannelMeta,NotificationEventMeta,NotificationForm,NotificationPayload } from './types';
// notificationChannelTypes 是所有通知渠道的静态字段、图标和使用指南。
export const notificationChannelTypes: Record<NotificationChannelType, NotificationChannelMeta> = {
+2 -2
View File
@@ -1,5 +1,5 @@
import type { Dispatch, ElementType, SetStateAction } from 'react';
import type { NotificationChannel, NotificationChannelType, NotificationEventType, SystemSettings } from '../../../shared/api-contract';
import type { Dispatch,ElementType,SetStateAction } from 'react';
import type { NotificationChannel,NotificationChannelType,NotificationEventType,SystemSettings } from './api';
// NotificationField 描述通知渠道表单中的一个配置字段。
export interface NotificationField {
+16 -8
View File
@@ -1,12 +1,20 @@
import { get, post, put, del, postForm, type RequestControlOptions } from '../../../shared/http/client';
import {
SessionResponse, AccountDetail, AccountSummaryResponse, Order, PaginatedResponse,
AdminStats, DashboardStats, Card, SystemSettings, OrderAnalytics,
Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction, AutomationTriggerType,
NotificationChannel, NotificationEventType, AccountTaskSettings, ChatSession, ChatMessage, ItemListEnvelope, AutomationIssuesEnvelope,
CookieSettingsResponse, CookieProfileResponse, ItemDetailResponse, ItemPublishResponse, ItemSyncResponse, OrderDTOResponse, OrderDetailResponse, OrderSingleRefreshResponse, OrderBatchResponse, OrderRefreshResponse, OrderRefreshJobStartResponse, OrderRefreshJobStatusResponse, OrderRefreshJobCancelResponse, AutomationRuleResponse, AutomationRulePageResponse, AIReplySettingsResponse, AIModelsResponse, UserSettingResponse, CardBatchResponse, CardAppendResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchListResponse, BatchIDResponse, ItemPublishBatchResponse, BatchCancelResponse, MutationIDResponse, OperationResponse, NotificationChannelResponse, NotificationBinding, AccountBindingsResponse, CardListResponse, KeywordTypedResponse, DefaultReplyResponse, AccountTaskSettingsResponse, AccountTaskRunResponseEnvelope, AdminStatsResponse, DashboardStatsResponse, OrderAnalyticsResponse, QRLoginGenerateResponse, QRLoginStatusResponse, QRLoginVerificationResponse, ValidOrderResponse, ValidOrdersResponse
} from '../../../shared/api-contract';
import { collectionFrom, objectFrom } from '../../../shared/http/contract';
AccountDetail,
AdminStatsResponse,
Item,
OperationResponse,
Order,
OrderBatchResponse,
OrderDTOResponse,OrderDetailResponse,
OrderRefreshJobCancelResponse,
OrderRefreshJobStartResponse,OrderRefreshJobStatusResponse,
OrderRefreshResponse,
OrderSingleRefreshResponse,
PaginatedResponse
} from '../../../shared/api-contract/orders';
import { del,get,post,postForm,put,type RequestControlOptions } from '../../../shared/http/client';
import { collectionFrom,objectFrom } from '../../../shared/http/contract';
export type * from '../../../shared/api-contract/orders';
/** 订单筛选器读取非敏感账号摘要。 */
export const getAccountDetails = async (options?: RequestControlOptions): Promise<AccountDetail[]> => get('/api/v1/accounts/details', undefined, options);
@@ -1,6 +1,6 @@
import { Search,User as UserIcon } from 'lucide-react';
import React from 'react';
import { Search, User as UserIcon } from 'lucide-react';
import type { AccountDetail } from '../../../../shared/api-contract';
import type { AccountDetail } from '../api';
import { orderStatusOptions } from '../state';
// OrderFilterBarProps 描述订单状态、账号和文本筛选所需的页面状态。
@@ -1,6 +1,6 @@
import { Upload,X } from 'lucide-react';
import React from 'react';
import { createPortal } from 'react-dom';
import { Upload, X } from 'lucide-react';
import { failedOrderImportRows } from '../state';
import type { OrderImportState } from '../types';
+5 -5
View File
@@ -1,9 +1,9 @@
// @vitest-environment jsdom
import { act, renderHook, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, test, vi } from 'vitest';
import type { AccountDetail, Item } from '../../../shared/api-contract';
import { getAccountDetails, getItems, getOrders, importOrders } from './api';
import { useOrderImport, useOrderQuery } from './hooks';
import { act,renderHook,waitFor } from '@testing-library/react';
import { beforeEach,describe,expect,test,vi } from 'vitest';
import type { AccountDetail,Item } from '../../../shared/api-contract/orders';
import { getAccountDetails,getItems,getOrders,importOrders } from './api';
import { useOrderImport,useOrderQuery } from './hooks';
vi.mock('./api', /* ordersApiMockFactory 提供订单 Hook 的确定性 API 替身。 */ () => ({
getAccountDetails: vi.fn(),
+5 -5
View File
@@ -1,8 +1,8 @@
import { useCallback, useEffect, useMemo, useRef, useState, type Dispatch, type SetStateAction } from 'react';
import type { AccountDetail, Item, Order } from '../../../shared/api-contract';
import { getAccountDetails, getItems, getOrders, importOrders } from './api';
import { canSubmitOrderImport, isCurrentOrderRequest, normalizeOrderImportResult, orderErrorMessage, validateOrderImportFile } from './state';
import type { OrderImportState, OrderQueryState } from './types';
import { useCallback,useEffect,useMemo,useRef,useState } from 'react';
import type { AccountDetail,Item,Order } from './api';
import { getAccountDetails,getItems,getOrders,importOrders } from './api';
import { canSubmitOrderImport,isCurrentOrderRequest,normalizeOrderImportResult,orderErrorMessage,validateOrderImportFile } from './state';
import type { OrderImportState,OrderQueryState } from './types';
// OrderQueryOptions 描述订单查询 Hook 的固定分页参数。
interface OrderQueryOptions {
@@ -1,8 +1,7 @@
// @vitest-environment jsdom
import { act, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import type { Order } from '../../../shared/api-contract';
import { deleteOrder, manualShipOrder, syncOrders, syncSingleOrder, updateOrder } from './api';
import { act,renderHook } from '@testing-library/react';
import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest';
import type { Order } from '../../../shared/api-contract/orders';
import { useOrderActions } from './orderActions';
// orderActionMocks 保存订单动作 Hook 测试使用的 API 替身。
+3 -3
View File
@@ -1,6 +1,6 @@
import { useCallback, useState, type Dispatch, type SetStateAction } from 'react';
import type { Order, OrderStatus } from '../../../shared/api-contract';
import { deleteOrder, manualShipOrder, syncOrders, syncSingleOrder, updateOrder } from './api';
import { useCallback,useState,type Dispatch,type SetStateAction } from 'react';
import type { Order } from './api';
import { deleteOrder,manualShipOrder,syncOrders,syncSingleOrder,updateOrder } from './api';
// OrderShipMode 表示订单发货操作的两种业务模式。
export type OrderShipMode = 'status_only' | 'full_delivery';
@@ -1,8 +1,8 @@
// @vitest-environment jsdom
import { cleanup,fireEvent,render,screen,waitFor } from '@testing-library/react';
import React from 'react';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import type { Order } from '../../../../shared/api-contract';
import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest';
import type { Order } from '../../../../shared/api-contract/orders';
// orderListMocks 保存订单页面测试使用的 Hook、API 和子组件替身。
const orderListMocks = vi.hoisted(/* orderListMockFactory 创建订单页面共享替身。 */ () => ({
@@ -1,12 +1,12 @@
import { ChevronLeft,ChevronRight,Edit,ExternalLink,Eye,PackageCheck,Plus,RefreshCw,Save,Trash2,Truck,User as UserIcon,X } from 'lucide-react';
import React from 'react';
import { createPortal } from 'react-dom';
import type { OrderStatus } from '../../../../shared/api-contract';
import { formatLocalDateTime } from '../../../../dateTime';
import type { OrderStatus } from '../api';
import { OrderFilterBar } from '../components/OrderFilterBar';
import { OrderImportModal } from '../components/OrderImportModal';
import { useOrderImport, useOrderQuery } from '../hooks';
import { useOrderImport,useOrderQuery } from '../hooks';
import { useOrderActions } from '../orderActions';
import { Truck, RefreshCw, ChevronLeft, ChevronRight, PackageCheck, Edit, Eye, Plus, Save, X, User as UserIcon, ExternalLink, Trash2 } from 'lucide-react';
import { formatLocalDateTime } from '../../../../dateTime';
// StatusBadge 渲染订单状态徽标。
const StatusBadge: React.FC<{ /** status 表示状态。 */ status: OrderStatus }> = ({ status }) => {
@@ -56,7 +56,6 @@ const OrderList: React.FC = () => {
showEditModal,
editingOrder,
showShipModal,
shipOrderId,
shipLoading,
shipResult,
syncingOrderId,
+7 -7
View File
@@ -1,11 +1,11 @@
import { expect, test } from 'vitest';
import { expect,test } from 'vitest';
import {
canSubmitOrderImport,
failedOrderImportRows,
isCurrentOrderRequest,
normalizeOrderImportResult,
orderStatusOptions,
validateOrderImportFile,
canSubmitOrderImport,
failedOrderImportRows,
isCurrentOrderRequest,
normalizeOrderImportResult,
orderStatusOptions,
validateOrderImportFile,
} from './state';
// createFile 创建订单导入预检使用的最小浏览器文件对象。
Loaded 100 of 176 files, more files were not shown because too many files have changed in this diff. Show more