阶段七:完成 React Feature 化与前置重构收口

This commit is contained in:
Christ committed 2026-08-17 20:29:34 +08:00
1 parent 375e84d663
commit 1a228dc35c
305 files changed
+14179 -5431

No files matched your search

+49
View File
@@ -0,0 +1,49 @@
import React from 'react';
/** ErrorBoundaryProps 描述顶层错误边界可恢复的页面子树。 */
interface ErrorBoundaryProps {
/** children 是由错误边界保护的整个应用路由树。 */
children: React.ReactNode;
}
/** ErrorBoundaryState 只记录渲染期故障,避免把错误对象或敏感响应写入浏览器状态。 */
interface ErrorBoundaryState {
/** hasError 表示应用子树是否因渲染错误而被隔离。 */
hasError: boolean;
}
/** AppErrorBoundary 隔离未捕获的页面渲染错误,并提供不依赖网络请求的恢复入口。 */
export class AppErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> {
/** state 保存当前子树的错误隔离状态。 */
public state: ErrorBoundaryState = { hasError: false };
/** getDerivedStateFromError 在 React 捕获到子树异常时切换到静态恢复视图。 */
public static getDerivedStateFromError(): ErrorBoundaryState {
return { hasError: true };
}
/** handleReload 由用户点击触发,使用完整刷新重新建立会话和路由运行环境。 */
private handleReload = (): void => {
window.location.reload();
};
/** render 在正常路径渲染应用子树;捕获异常后只暴露安全的恢复界面。 */
public render(): React.ReactNode {
// hasError 表示当前是否需要显示错误隔离界面。
const { hasError } = this.state;
// children 是未发生渲染错误时应继续展示的应用路由树。
const { children } = this.props;
if (!hasError) return children;
return (
<main className="flex min-h-screen items-center justify-center bg-canvas p-6 text-ink">
<section className="max-w-md text-center">
<h1 className="text-xl font-semibold">页面暂时无法显示</h1>
<button className="ios-btn-primary mt-6 px-4 py-2" type="button" onClick={this.handleReload}>
重新加载
</button>
</section>
</main>
);
}
}
@@ -1,2 +0,0 @@
/** AccountAutomation feature 使用的账号任务 API。 */
export { getAccountTaskSettings, runAccountTask, updateAccountTaskSettings } from '../../../services/api';
@@ -0,0 +1,11 @@
import { get, post, put, type RequestControlOptions } from '../../../shared/http/client';
import type { AccountTaskSettings, AccountTaskSettingsResponse, AccountTaskRunResponseEnvelope } from '../../../shared/api-contract';
/** 获取指定账号的自动评价与自动擦亮设置。 */
export const getAccountTaskSettings = async (accountID: string, options?: RequestControlOptions): Promise<AccountTaskSettingsResponse> => get(`/api/v1/account-tasks/${accountID}`, undefined, options);
/** 保存指定账号的自动评价与自动擦亮设置。 */
export const updateAccountTaskSettings = async (accountID: string, settings: AccountTaskSettings, options?: RequestControlOptions): Promise<AccountTaskSettingsResponse> => put(`/api/v1/account-tasks/${accountID}`, settings, options);
/** 立即发起账号级计划任务,并使用较长超时覆盖平台执行窗口。 */
export const runAccountTask = async (accountID: string, taskType: 'auto_rate' | 'auto_polish', options?: RequestControlOptions): Promise<AccountTaskRunResponseEnvelope> => post(`/api/v1/account-tasks/${accountID}/run`, { task_type: taskType }, { timeoutMs: 120_000, ...options });
@@ -1,11 +1,11 @@
// @vitest-environment jsdom
import { act, renderHook, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, test, vi } from 'vitest';
import type { AccountDetail, AccountTaskSettingsResponse } from '../../../types';
import { getAccountTaskSettings, runAccountTask, updateAccountTaskSettings } from './api';
import { useAccountAutomation } from './hooks';
import type { AccountDetail, AccountTaskSettingsResponse } from '../../../shared/api-contract';
import { getAccountTaskSettings, runAccountTask, updateAccountTaskSettings } from './accountAutomationApi';
import { useAccountAutomation } from './accountAutomationHooks';
vi.mock('./api', /* apiMockFactory 提供账号任务 Hook 的确定性 API 替身。 */ () => ({
vi.mock('./accountAutomationApi', /* apiMockFactory 提供账号任务 Hook 的确定性 API 替身。 */ () => ({
getAccountTaskSettings: vi.fn(),
runAccountTask: vi.fn(),
updateAccountTaskSettings: vi.fn(),
@@ -1,8 +1,8 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import type { AccountTaskSettings, AccountTaskSummary } from '../../../types';
import { getAccountTaskSettings, runAccountTask, updateAccountTaskSettings } from './api';
import { accountTaskErrorMessage, buildAccountTaskDefaults, canStartAccountTask, isAccountTaskAbortError, isCurrentAccountTaskRequest } from './state';
import type { AccountAutomationOptions, AccountAutomationState, AccountTaskType } from './types';
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';
/** AccountAutomation Hook 的完整返回值。 */
export type UseAccountAutomationResult = AccountAutomationState & {
@@ -1,6 +1,6 @@
import { expect, test } from 'vitest';
import type { AccountDetail } from '../../../types';
import { buildAccountTaskDefaults, canStartAccountTask, isCurrentAccountTaskRequest } from './state';
import type { AccountDetail } from '../../../shared/api-contract';
import { buildAccountTaskDefaults, canStartAccountTask, isCurrentAccountTaskRequest } from './accountAutomationState';
// accountFixture 是覆盖任务默认值和账号禁用边界的最小账号数据。
const accountFixture: AccountDetail = {
@@ -1,5 +1,5 @@
import type { AccountDetail, AccountTaskSettings } from '../../../types';
import type { AccountTaskType } from './types';
import type { AccountDetail, AccountTaskSettings } from '../../../shared/api-contract';
import type { AccountTaskType } from './accountAutomationTypes';
/** 根据账号详情创建任务设置初始草稿。 */
export const buildAccountTaskDefaults = (account: AccountDetail): AccountTaskSettings => ({
@@ -1,4 +1,4 @@
import type { AccountDetail, AccountTaskSettings, AccountTaskSummary } from '../../../types';
import type { AccountDetail, AccountTaskSettings, AccountTaskSummary } from '../../../shared/api-contract';
/** 账号任务类型。 */
export type AccountTaskType = 'auto_rate' | 'auto_polish';
@@ -0,0 +1,16 @@
import { describe, expect, test } from 'vitest';
import { shouldSaveNotificationBindings } from './accountBindings';
describe('notification binding save guard', /* 当前回调处理用户交互或异步状态变化。 */ () => {
test('does not overwrite bindings when loading failed', /* 当前回调处理用户交互或异步状态变化。 */ () => {
expect(shouldSaveNotificationBindings(false, true)).toBe(false);
});
test('does not write unchanged bindings', /* 当前回调处理用户交互或异步状态变化。 */ () => {
expect(shouldSaveNotificationBindings(true, false)).toBe(false);
});
test('writes an explicitly changed, successfully loaded selection', /* 当前回调处理用户交互或异步状态变化。 */ () => {
expect(shouldSaveNotificationBindings(true, true)).toBe(true);
});
});
@@ -0,0 +1,2 @@
// shouldSaveNotificationBindings 判断通知绑定是否需要保存。
export const shouldSaveNotificationBindings = (loaded: boolean, dirty: boolean): boolean => loaded && dirty;
+324 -30
View File
@@ -1,31 +1,325 @@
// 账号 feature 只通过本适配层访问账号相关网络接口,页面不再直接依赖共享 API 文件。
export {
cancelPasswordLogin,
checkPasswordLoginStatus,
checkQRLoginStatus,
completeQRVerification,
deleteAccount,
generateQRLogin,
getAccountAISettings,
getAccountBindings,
getAccountDetails,
getAccountRuntimeStatuses,
getAllAISettings,
getLongLoginSettings,
getNotificationChannels,
passwordLogin,
refreshAccountProfile,
setLongLoginSettings,
updateAccountAISettings,
updateAccountPauseDuration,
updateAccountSettings,
updateAccountStatus,
} from '../../../services/api';
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';
// Accounts
// addAccount 新增账号。
export const addAccount = async (id: string, value: string, loginMethod?: string): Promise<OperationResponse> => {
return post('/api/v1/accounts', { id, value, login_method: loginMethod });
};
// 账号 feature 重新导出接口返回类型,保持页面与网络契约的依赖方向稳定。
export type {
AccountRuntimeStatus,
LongLoginSettings,
PasswordLoginStartResponse,
PasswordLoginStatusResponse,
} from '../../../services/api';
// accountAvatarURL 生成账号头像地址。
const accountAvatarURL = (item: AccountSummaryResponse, version: string): string => {
// raw 原始值,用于当前 API 处理流程。
const raw = item.avatar_url || '';
if (!raw) return '';
try {
// url 解析后的地址,用于当前 API 处理流程。
const url = new URL(raw, window.location.origin);
if (url.hostname.endsWith('alicdn.com')) {
url.searchParams.set('_v', version);
}
return url.toString();
} catch {
return raw;
}
};
// getAccountDetails 读取账号详情。
export const getAccountDetails = async (options?: RequestControlOptions): Promise<AccountDetail[]> => {
// data 数据,用于当前 API 处理流程。
const response = await get<unknown>('/api/v1/accounts/details', undefined, options);
// data 是兼容数组、null 和历史 data 包裹后的账号摘要列表。
const data = collectionFrom<AccountSummaryResponse>(response, ['data', 'accounts', 'details']);
// avatarVersion 头像缓存版本,用于当前 API 处理流程。
const avatarVersion = Date.now().toString();
return data.map(/* 当前回调用于处理集合元素或接口响应。 */ item => ({
id: item.id,
cookie_configured: item.has_cookie === true,
enabled: item.enabled,
auto_confirm: item.auto_confirm,
remark: item.remark,
pause_duration: item.pause_duration,
paused_until: Number(item.paused_until || 0),
paused: item.paused === true,
username: item.username || '',
login_password_configured: undefined,
show_browser: item.show_browser === true || item.show_browser === 1 || item.show_browser === '1' || item.show_browser === 'true',
nickname: item.nickname || item.remark || `账号 ${item.id.substring(0,6)}`,
avatar_url: accountAvatarURL(item, avatarVersion),
profile_error: item.profile_error || '',
ai_enabled: false,
auto_rate_enabled: item.auto_rate_enabled,
rate_content: item.rate_content || '不错的买家,交易愉快',
auto_polish_enabled: item.auto_polish_enabled,
polish_time: item.polish_time || '03:00',
last_rate_scan_at: Number(item.last_rate_scan_at || 0),
last_polish_date: item.last_polish_date || '',
last_polish_at: Number(item.last_polish_at || 0),
}));
};
// getAccountTaskSettings 读取账号计划任务设置。
export const getAccountTaskSettings = async (id: string, options?: RequestControlOptions): Promise<AccountTaskSettingsResponse> =>
get(`/api/v1/account-tasks/${id}`, undefined, options);
// updateAccountTaskSettings 更新账号计划任务设置。
export const updateAccountTaskSettings = async (id: string, settings: AccountTaskSettings, options?: RequestControlOptions): Promise<AccountTaskSettingsResponse> =>
put(`/api/v1/account-tasks/${id}`, settings, options);
// runAccountTask 立即执行账号计划任务。
export const runAccountTask = async (id: string, taskType: 'auto_rate' | 'auto_polish', options?: RequestControlOptions): Promise<AccountTaskRunResponseEnvelope> =>
post(`/api/v1/account-tasks/${id}/run`, { task_type: taskType }, { timeoutMs: 120_000, ...options });
export interface AccountRuntimeStatus {
/** state 表示状态。 */ state: NonNullable<AccountDetail['runtime_state']>;
/** message 表示消息数据。 */ message?: string;
/** connected 表示连接状态。 */ connected: boolean;
/** failures 表示失败次数。 */ failures: number;
/** updated_at 表示最后更新时间。 */ updated_at: string;
}
// getAccountRuntimeStatuses 读取账号运行状态。
export const getAccountRuntimeStatuses = async (options?: RequestControlOptions): Promise<Record<string, AccountRuntimeStatus>> => {
const response = await get<unknown>('/api/v1/accounts/runtime-status', undefined, options);
// statuses 是兼容直接映射、statuses 包裹和 null 的运行状态索引。
const statuses = objectFrom<Record<string, AccountRuntimeStatus>>(response, ['statuses', 'data', 'result']);
return statuses || {};
};
// generateQRLogin 生成二维码登录会话。
export const generateQRLogin = async (options?: RequestControlOptions): Promise<QRLoginGenerateResponse> => {
// 风控后匿名 token 接口可能超过通用的 30 秒请求窗口;后端总生成窗口为 2 分钟。
return post('/api/v1/qr-login/generate', undefined, { ...options, timeoutMs: options?.timeoutMs ?? 130_000 });
};
// checkQRLoginStatus 查询二维码登录状态。
export const checkQRLoginStatus = async (sessionId: string, signal?: AbortSignal): Promise<QRLoginStatusResponse> => {
return get(`/api/v1/qr-login/check/${sessionId}`, undefined, { signal, timeoutMs: 10_000 });
};
// completeQRVerification 完成二维码登录验证。
export const completeQRVerification = async (
sessionId: string,
targetAccountId?: string,
): Promise<QRLoginVerificationResponse> => {
return post(`/api/v1/qr-login/complete-verification/${sessionId}`, {
target_account_id: targetAccountId || '',
});
};
// updateAccountStatus 更新账号状态。
export const updateAccountStatus = async (id: string, enabled: boolean): Promise<OperationResponse> => {
return put(`/api/v1/accounts/${id}/status`, { enabled });
};
// deleteAccount 删除账号。
export const deleteAccount = async (id: string): Promise<OperationResponse> => {
return del(`/api/v1/accounts/${id}`);
};
// updateAccountRemark 更新账号备注。
export const updateAccountRemark = async (id: string, remark: string): Promise<OperationResponse> => {
return put(`/api/v1/accounts/${id}/remark`, { remark });
};
// updateAccountAutoConfirm 更新账号自动确认设置。
export const updateAccountAutoConfirm = async (id: string, autoConfirm: boolean): Promise<OperationResponse> => {
return put(`/api/v1/accounts/${id}/auto-confirm`, { auto_confirm: autoConfirm });
};
// updateAccountPauseDuration 更新账号暂停时长。
export const updateAccountPauseDuration = async (id: string, pauseDuration: number, options?: RequestControlOptions): Promise<CookieSettingsResponse> => {
return put(`/api/v1/accounts/${id}/pause-duration`, { pause_duration: pauseDuration }, options);
};
// updateAccountCookie 更新账号登录凭证。
export const updateAccountCookie = async (id: string, value: string, loginMethod?: string): Promise<OperationResponse> => {
return put(`/api/v1/accounts/${id}`, { id, value, login_method: loginMethod });
};
export interface AccountSettingsUpdate {
/** cookie 表示登录凭证。 */ cookie?: string;
/** remark 表示备注。 */ remark?: string;
/** auto_confirm 表示自动确认状态。 */ auto_confirm?: boolean;
/** pause_duration 表示暂停时长。 */ pause_duration?: number;
/** username 表示用户名。 */ username?: string;
/** login_password 表示登录密码。 */ login_password?: string;
/** clear_password 表示是否清理登录密码。 */ clear_password?: boolean;
/** show_browser 表示是否显示浏览器。 */ show_browser?: boolean;
/** channel_ids 表示通知渠道标识列表。 */ channel_ids?: number[];
}
// updateAccountSettings 更新账号设置。
export const updateAccountSettings = async (id: string, data: AccountSettingsUpdate, options?: RequestControlOptions): Promise<CookieSettingsResponse> => {
return put(`/api/v1/accounts/${id}/settings`, data, options);
};
export interface LongLoginSettings {
/** can_open_long_login 表示是否允许开启长期登录。 */ can_open_long_login: boolean;
/** enabled 表示启用状态。 */ enabled: boolean;
}
// getLongLoginSettings 读取长期登录设置。
export const getLongLoginSettings = async (id: string, options?: RequestControlOptions): Promise<LongLoginSettings> => {
return get(`/api/v1/accounts/${id}/long-login`, undefined, options);
};
// setLongLoginSettings 设置长期登录开关。
export const setLongLoginSettings = async (id: string, enabled: boolean, options?: RequestControlOptions): Promise<LongLoginSettings> => {
return put(`/api/v1/accounts/${id}/long-login`, { enabled }, options);
};
export interface PasswordLoginStartResponse {
/** success 表示是否成功。 */ success: boolean;
/** session_id 表示会话标识。 */ session_id?: string;
/** status 表示状态值。 */ status?: 'processing' | 'failed';
/** message 表示消息数据。 */ message?: string;
}
export interface PasswordLoginStatusResponse {
/** status 表示状态值。 */ status: 'processing' | 'success' | 'failed' | 'verification_required' | 'not_found' | 'error';
/** message 表示消息数据。 */ message?: string;
/** account_id 表示账号标识。 */ account_id?: string;
/** is_new_account 表示是否为新账号。 */ is_new_account?: boolean;
/** cookie_count 表示登录凭证数量。 */ cookie_count?: number;
/** verification_url 表示验证地址。 */ verification_url?: string;
/** screenshot_path 表示验证截图路径。 */ screenshot_path?: string;
/** qr_code_url 表示二维码地址。 */ qr_code_url?: string;
/** error 表示错误信息。 */ error?: string;
/** reason 表示失败原因。 */ reason?: string;
}
// passwordLogin 执行密码登录。
export const passwordLogin = async (data: {
/** account_id 表示账号标识。 */ account_id: string;
/** account 表示账号。 */ account: string;
/** password 表示密码。 */ password: string;
/** show_browser 表示是否显示浏览器。 */ show_browser?: boolean;
}, options?: RequestControlOptions): Promise<PasswordLoginStartResponse> => {
return post('/api/v1/password-login', data, options);
};
// checkPasswordLoginStatus 查询密码登录状态。
export const checkPasswordLoginStatus = async (sessionId: string, signal?: AbortSignal): Promise<PasswordLoginStatusResponse> => {
return get(`/api/v1/password-login/check/${sessionId}`, undefined, { signal, timeoutMs: 10_000 });
};
// cancelPasswordLogin 取消密码登录。
export const cancelPasswordLogin = async (sessionId: string, options?: RequestControlOptions): Promise<OperationResponse> => {
return del(`/api/v1/password-login/cancel/${sessionId}`, undefined, options);
};
// refreshAccountProfile 刷新账号资料。
export const refreshAccountProfile = async (id: string): Promise<CookieProfileResponse> => {
return post(`/api/v1/accounts/${id}/refresh-profile`, {});
};
// updateAccountLoginInfo 更新账号登录信息。
export const updateAccountLoginInfo = async (id: string, data: {
/** username 表示用户名。 */ username?: string;
/** login_password 表示登录密码。 */ login_password?: string;
/** clear_password 表示是否清理登录密码。 */ clear_password?: boolean;
/** show_browser 表示是否显示浏览器。 */ show_browser?: boolean;
}): Promise<OperationResponse> => {
return put(`/api/v1/accounts/${id}/login-info`, data);
};
// getAllAISettings 读取全部人工智能设置。
export const getAllAISettings = async (options?: RequestControlOptions): Promise<Record<string, AIReplySettings>> => {
const response = await get<unknown>('/api/v1/settings/ai-reply', undefined, options);
// settings 是兼容直接映射、data 包裹和 null 的账号 AI 设置索引。
return objectFrom<Record<string, AIReplySettings>>(response, ['settings', 'data', 'result']) || {};
};
// getAccountAISettings 读取账号人工智能设置。
export const getAccountAISettings = async (cookieId: string, options?: RequestControlOptions): Promise<AIReplySettingsResponse> => {
return get(`/api/v1/settings/ai-reply/${cookieId}`, undefined, options);
}
// updateAccountAISettings 更新账号人工智能设置。
export const updateAccountAISettings = async (cookieId: string, settings: Partial<AIReplySettings>, options?: RequestControlOptions): Promise<OperationResponse> => {
// payload 请求载荷,用于当前 API 处理流程。
const payload = {
ai_enabled: settings.ai_enabled ?? false,
max_discount_percent: settings.max_discount_percent ?? 10,
max_discount_amount: settings.max_discount_amount ?? 100,
max_bargain_rounds: settings.max_bargain_rounds ?? 3,
custom_prompts: settings.custom_prompts ?? ''
};
return put(`/api/v1/settings/ai-reply/${cookieId}`, payload, options);
}
// parseNotificationEventTypes 解析通知事件类型。
const parseNotificationEventTypes = (raw: unknown): NotificationEventType[] => {
if (Array.isArray(raw)) return raw.filter(Boolean) as NotificationEventType[];
if (typeof raw !== 'string' || !raw.trim()) return [];
try {
// parsed 转换后的数值,用于当前 API 处理流程。
const parsed = JSON.parse(raw);
if (Array.isArray(parsed)) return parsed.filter(Boolean) as NotificationEventType[];
} catch {
// fall back to legacy comma/semicolon separated values
}
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 处理流程。
const result = await get<unknown>('/api/v1/notifications/channels', undefined, options);
// channels 通知渠道列表,用于当前 API 处理流程。
const channels = collectionFrom<NotificationChannelResponse>(result, ['data', 'channels', 'items']).map(/* 当前回调用于处理集合元素或接口响应。 */ (item: NotificationChannelResponse) => {
// parsedConfig 解析后的通知配置,用于当前 API 处理流程。
let parsedConfig;
try {
parsedConfig = typeof item.config === 'string' ? JSON.parse(item.config) : item.config;
} catch {
parsedConfig = {};
}
// normalizedType 是兼容旧渠道别名后的前端渠道类型。
const normalizedType = (item.type === 'ding_talk' ? 'dingtalk' : (item.type === 'lark' ? 'feishu' : item.type)) as NotificationChannel['type'];
return {
id: String(item.id),
name: item.name,
type: normalizedType,
config: parsedConfig,
event_types: parseNotificationEventTypes(item.event_types),
enabled: item.enabled,
created_at: item.created_at,
updated_at: item.updated_at,
};
});
return { success: true, data: channels };
}
// 账号 ↔ 渠道 绑定(覆盖式)
export const getAccountBindings = async (cookieId: string, options?: RequestControlOptions): Promise<number[]> => {
// response 是兼容直接绑定对象、data 包裹和 null 的通知绑定响应。
const response = await get<unknown>(`/api/v1/notifications/accounts/${cookieId}/bindings`, undefined, options);
// result 是去除历史包裹后的账号通知绑定对象。
const result = objectFrom<Partial<AccountBindingsResponse>>(response, ['data', 'result']) || {};
return Array.isArray(result.channel_ids) ? result.channel_ids : [];
}
@@ -1,7 +1,7 @@
import React from 'react';
import { createPortal } from 'react-dom';
import { Bot, Loader2, Save, Settings, X } from 'lucide-react';
import type { AccountDetail, AIReplySettings } from '../../../../types';
import type { AccountDetail, AIReplySettings } from '../../../../shared/api-contract';
// AccountAISettingsModalProps 描述账号 AI 设置弹窗需要的状态和回调。
export interface AccountAISettingsModalProps {
@@ -0,0 +1,115 @@
import React from 'react';
import { CalendarClock, Loader2, MessageSquareQuote, Play, Save, Sparkles, X } from 'lucide-react';
import { AccountDetail, AccountTaskSettings } from '../../../../shared/api-contract';
import { useAccountAutomation } from '../accountAutomationHooks';
interface Props {
/** account 表示账号。 */ account: AccountDetail;
/** onClose 表示关闭弹窗的回调。 */ onClose: () => void;
/** onSaved 表示保存完成后的回调。 */ onSaved: (settings: AccountTaskSettings) => void;
}
// Toggle 渲染可复用的开关控件。
const Toggle: React.FC<{/** checked 表示开关当前是否选中。 */ checked: boolean; /** onChange 表示开关状态变化的回调。 */ onChange: () => void; /** label 表示控件的无障碍名称。 */ label: string}> = ({ checked, onChange, label }) => (
<button type="button" aria-label={label} aria-pressed={checked} onClick={onChange}
className={`relative h-8 w-14 shrink-0 rounded-full transition-colors ${checked ? 'bg-sky-500' : 'bg-slate-300'}`}>
<span className={`absolute left-1 top-1 h-6 w-6 rounded-full bg-white shadow-sm transition-transform ${checked ? 'translate-x-6' : ''}`} />
</button>
);
// AccountAutomationModal 渲染账号自动化设置弹窗。
const AccountAutomationModal: React.FC<Props> = ({ account, onClose, onSaved }) => {
// automationState 是账号任务 feature Hook 提供的表单和动作状态。
const { form, loading, saving, running, error, summary, retryAvailable, setForm, save, run, retry } = useAccountAutomation({ account, onSaved });
return (
<div className="modal-overlay-centered">
<div className="modal-container" style={{ maxWidth: '640px' }} role="dialog" aria-modal="true" aria-labelledby="account-task-title">
<div className="modal-header">
<div>
<h3 id="account-task-title" className="text-2xl font-extrabold text-slate-950">账号自动任务</h3>
<p className="mt-1 text-sm text-slate-500">{account.nickname || account.remark || account.id}</p>
</div>
<button type="button" onClick={onClose} className="rounded-xl p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700" aria-label="关闭">
<X className="h-5 w-5" />
</button>
</div>
<div className="modal-body space-y-5">
{loading && <div className="rounded-xl bg-slate-50 px-4 py-3 text-sm text-slate-500">正在读取任务设置...</div>}
<section className="rounded-2xl border border-slate-200 bg-white p-5">
<div className="flex items-start gap-4">
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-emerald-50 text-emerald-600"><MessageSquareQuote className="h-5 w-5" /></div>
<div className="min-w-0 flex-1">
<div className="flex items-center justify-between gap-4">
<div>
<h4 className="font-black text-slate-900">自动评价</h4>
<p className="mt-1 text-xs leading-5 text-slate-500">持续扫描待评价订单,按订单执行;不是每日任务。</p>
</div>
<Toggle checked={form.auto_rate_enabled} onChange={/* 当前回调处理用户交互或异步状态变化。 */ () => setForm(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, auto_rate_enabled: !current.auto_rate_enabled }))} label="自动评价" />
</div>
<label className="mt-4 block text-xs font-extrabold text-slate-600">统一好评文案</label>
<textarea aria-label="统一好评文案" value={form.rate_content} maxLength={500} onChange={/* 当前回调处理用户交互或异步状态变化。 */ event => setForm(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, rate_content: event.target.value }))}
className="mt-2 h-24 w-full resize-none rounded-xl border border-slate-200 bg-slate-50 px-3 py-2.5 text-sm leading-6 text-slate-800 placeholder:text-slate-400 outline-none focus:border-sky-400 focus:ring-2 focus:ring-sky-100" />
<div className="mt-3 flex items-center justify-between gap-3">
<span className="text-xs text-slate-400">最近扫描:{form.last_rate_scan_at ? new Date(form.last_rate_scan_at * 1000).toLocaleString('zh-CN') : '尚未执行'}</span>
<button type="button" disabled={running !== '' || !account.enabled} onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void run('auto_rate')}
className="flex items-center gap-2 rounded-xl bg-emerald-50 px-3 py-2 text-xs font-extrabold text-emerald-700 hover:bg-emerald-100 disabled:opacity-50">
{running === 'auto_rate' ? <Loader2 className="h-4 w-4 animate-spin" /> : <Play className="h-4 w-4" />}立即评价
</button>
</div>
</div>
</div>
</section>
<section className="rounded-2xl border border-slate-200 bg-white p-5">
<div className="flex items-start gap-4">
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-amber-50 text-amber-600"><Sparkles className="h-5 w-5" /></div>
<div className="min-w-0 flex-1">
<div className="flex items-center justify-between gap-4">
<div>
<h4 className="font-black text-slate-900">每日自动擦亮</h4>
<p className="mt-1 text-xs leading-5 text-slate-500">每个账号每天最多执行一次,按北京时间判断。</p>
</div>
<Toggle checked={form.auto_polish_enabled} onChange={/* 当前回调处理用户交互或异步状态变化。 */ () => setForm(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, auto_polish_enabled: !current.auto_polish_enabled }))} label="每日自动擦亮" />
</div>
<div className="mt-4 flex items-end justify-between gap-4">
<label className="block">
<span className="text-xs font-extrabold text-slate-600">每日执行时间</span>
<input type="time" value={form.polish_time} onChange={/* 当前回调处理用户交互或异步状态变化。 */ event => setForm(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, polish_time: event.target.value }))}
className="mt-2 block rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm font-bold text-slate-800 outline-none focus:border-sky-400" />
</label>
<button type="button" disabled={running !== '' || !account.enabled} onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void run('auto_polish')}
className="flex items-center gap-2 rounded-xl bg-amber-50 px-3 py-2 text-xs font-extrabold text-amber-700 hover:bg-amber-100 disabled:opacity-50">
{running === 'auto_polish' ? <Loader2 className="h-4 w-4 animate-spin" /> : <CalendarClock className="h-4 w-4" />}立即擦亮
</button>
</div>
<div className="mt-3 text-xs text-slate-400">上次完成:{form.last_polish_at ? new Date(form.last_polish_at * 1000).toLocaleString('zh-CN') : '尚未执行'}</div>
</div>
</div>
</section>
{summary && (
<div className="rounded-xl border border-sky-100 bg-sky-50 px-4 py-3 text-sm text-sky-900">
本次发现 {summary.found} 项,成功 {summary.success},失败 {summary.failed},跳过 {summary.skipped}。{summary.message || ''}
</div>
)}
{error && <div className="flex items-center justify-between gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm font-medium text-red-700"><span>{error}</span>{retryAvailable && <button type="button" className="font-bold underline" onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void retry()}>重试</button>}</div>}
</div>
<div className="modal-footer">
<div className="flex w-full gap-3">
<button type="button" onClick={onClose} disabled={saving || running !== ''}
className="flex-1 rounded-xl bg-gray-100 px-6 py-3 font-bold text-gray-700 transition-colors hover:bg-gray-200 disabled:opacity-50">关闭</button>
<button type="button" onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void save()} disabled={saving || running !== '' || (form.auto_rate_enabled && !form.rate_content.trim())}
className="ios-btn-primary flex flex-1 items-center justify-center gap-2 rounded-xl px-6 py-3 font-bold disabled:opacity-50">
{saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}保存
</button>
</div>
</div>
</div>
</div>
);
};
export default AccountAutomationModal;
@@ -1,6 +1,6 @@
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 '../../../../types';
import type { AccountDetail } from '../../../../shared/api-contract';
import { accountRuntimePresentation } from '../runtime';
// AccountCardProps 描述账号卡片展示所需的数据和动作。
@@ -1,7 +1,7 @@
import React from 'react';
import { createPortal } from 'react-dom';
import { AlertCircle, Loader2, Trash2, X } from 'lucide-react';
import type { AccountDetail } from '../../../../types';
import type { AccountDetail } from '../../../../shared/api-contract';
// AccountDeleteDialogProps 描述账号删除确认框需要的状态和回调。
export interface AccountDeleteDialogProps {
@@ -1,8 +1,8 @@
import React from 'react';
import { createPortal } from 'react-dom';
import { Bell, Check, Clock, Eye, EyeOff, Key, Loader2, X } from 'lucide-react';
import { SquareQRCode } from '../../../../components/SquareQRCode';
import type { NotificationChannel } from '../../../../types';
import { SquareQRCode } from './SquareQRCode';
import type { NotificationChannel } from '../../../../shared/api-contract';
import type { AccountEditForm, AccountEditModalProps } from '../types';
// AccountEditModal 负责账号备注、暂停、登录信息和通知绑定的编辑界面。
@@ -1,9 +1,9 @@
import React from 'react';
import { createPortal } from 'react-dom';
import { Check, Loader2, X } from 'lucide-react';
import type { AccountDetail } from '../../../../types';
import { RiskVerificationPanel } from '../../../../components/RiskVerificationPanel';
import { SquareQRCode } from '../../../../components/SquareQRCode';
import type { AccountDetail } from '../../../../shared/api-contract';
import { RiskVerificationPanel } from './RiskVerificationPanel';
import { SquareQRCode } from './SquareQRCode';
// AccountQRCodeModalProps 描述二维码登录弹窗的展示状态和关闭回调。
export interface AccountQRCodeModalProps {
@@ -0,0 +1,17 @@
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import { RiskVerificationPanel } from './RiskVerificationPanel';
test('risk verification panel explains automatic refresh without manual controls', /* 当前回调处理用户交互或异步状态变化。 */ () => {
// html 渲染后的 HTML。
const html = renderToStaticMarkup(
<RiskVerificationPanel faceQrUrl="data:image/png;base64,abc" />,
);
expect(html).toContain('需要完成安全风控验证');
expect(html).toContain('系统会自动检测并刷新登录状态');
expect(html).toContain('max-h-[min(64vh,28rem)]');
expect(html).not.toContain('<button');
expect(html).not.toContain('我已');
expect(html).not.toContain('重试');
});
@@ -0,0 +1,42 @@
import React from 'react';
import { AlertTriangle, Loader2 } from 'lucide-react';
interface RiskVerificationPanelProps {
/** faceQrUrl 表示人脸验证二维码地址。 */ faceQrUrl?: string;
/** verificationScreenshot 表示验证失败截图地址。 */ verificationScreenshot?: string;
}
// RiskVerificationPanel 渲染风控验证面板。
export const RiskVerificationPanel: React.FC<RiskVerificationPanelProps> = ({
faceQrUrl,
verificationScreenshot,
}) => (
<div className="w-full min-w-0 max-h-[min(64vh,28rem)] overflow-y-auto overscroll-contain px-1 py-2 text-center">
<div className="mx-auto mb-2 flex h-10 w-10 items-center justify-center rounded-full bg-amber-100 text-amber-700">
<AlertTriangle className="h-5 w-5" aria-hidden="true" />
</div>
<h4 className="break-words text-base font-extrabold leading-6 text-amber-900">
需要完成安全风控验证
</h4>
<p className="mx-auto mt-1 max-w-[15rem] break-words text-xs leading-5 text-amber-800">
当前账号触发了闲鱼平台风控。请使用手机闲鱼 App 扫描下方二维码,并按 App 提示完成人脸识别。
</p>
<div className="mx-auto mt-3 flex min-h-36 w-full max-w-[12rem] items-center justify-center overflow-hidden rounded-xl border border-amber-200 bg-white p-2 shadow-sm">
{faceQrUrl ? (
<img src={faceQrUrl} alt="闲鱼安全风控验证二维码" className="block max-h-44 w-full object-contain" />
) : verificationScreenshot ? (
<img src={verificationScreenshot} alt="闲鱼风控验证页面" className="block max-h-44 w-full object-contain" />
) : (
<div className="flex flex-col items-center gap-2 text-amber-700">
<Loader2 className="h-6 w-6 animate-spin" aria-hidden="true" />
<span className="text-xs font-bold">正在准备风控二维码…</span>
</div>
)}
</div>
<p className="mx-auto mt-2 max-w-[15rem] break-words text-[11px] leading-4 text-gray-500">
请勿在浏览器中打开验证链接。完成验证后系统会自动检测并刷新登录状态,无需手动确认。
</p>
</div>
);
@@ -0,0 +1,13 @@
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import { SquareQRCode } from './SquareQRCode';
test('login QR code preserves a square aspect ratio without stretching', /* 当前回调处理用户交互或异步状态变化。 */ () => {
// html 渲染后的 HTML。
const html = renderToStaticMarkup(<SquareQRCode src="data:image/png;base64,abc" alt="登录二维码" className="p-2" />);
expect(html).toContain('aspect-square');
expect(html).toContain('h-auto');
expect(html).toContain('object-contain');
expect(html).toContain('p-2');
});
@@ -0,0 +1,16 @@
import React from 'react';
interface SquareQRCodeProps {
/** src 表示二维码图片地址。 */ src: string;
/** alt 表示二维码的替代文本。 */ alt: string;
/** className 表示附加的 CSS 类名。 */ className?: string;
}
// SquareQRCode 渲染方形二维码图片。
export const SquareQRCode: React.FC<SquareQRCodeProps> = ({ src, alt, className = '' }) => (
<img
src={src}
alt={alt}
className={`block aspect-square h-auto w-full object-contain ${className}`.trim()}
/>
);
@@ -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 '../../../../types';
import type { AccountDetail, AIReplySettings } from '../../../../shared/api-contract';
import { AccountAISettingsModal } from './AccountAISettingsModal';
import { AccountCard } from './AccountCard';
import { AccountDeleteDialog } from './AccountDeleteDialog';
@@ -2,7 +2,7 @@
import { renderHook, waitFor } from '@testing-library/react';
import { act } from 'react';
import { beforeEach, describe, expect, test, vi } from 'vitest';
import type { AccountDetail } from '../../../types';
import type { AccountDetail } from '../../../shared/api-contract';
import { getAccountDetails, getAccountRuntimeStatuses, getAllAISettings } from './api';
import { useAccountsData } from './hooks';
+1 -1
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 '../../../types';
import type { AccountDetail } from '../../../shared/api-contract';
import { mergeAccountRuntimeStatuses } from './runtime';
import type { AccountAISettingsState } from './types';
@@ -0,0 +1,219 @@
// @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 { AccountDetail } from '../../../../shared/api-contract';
// accountListMocks 保存 AccountList 页面测试使用的 API、Hook 和轮询替身。
const accountListMocks = vi.hoisted(/* accountListMockFactory 创建页面测试共享替身。 */ () => ({
accounts: [
{ id: 'account-1', nickname: 'Alpha', remark: '主账号', enabled: true, runtime_message: '在线' },
{ id: 'account-2', nickname: 'Beta', remark: '备用账号', enabled: false, runtime_message: '已停用' },
] as AccountDetail[],
setAccounts: vi.fn(),
loadAccounts: vi.fn(),
updateAccountStatus: vi.fn(),
deleteAccount: vi.fn(),
generateQRLogin: vi.fn(),
checkQRLoginStatus: vi.fn(),
completeQRVerification: vi.fn(),
refreshAccountProfile: vi.fn(),
pollerStart: vi.fn(),
pollerStop: vi.fn(),
requestNext: vi.fn(),
requestIsCurrent: vi.fn(),
requestCancel: vi.fn(),
pollCallbacks: null as Record<string, (...args: any[]) => void> | null,
}));
vi.mock('../hooks', /* accountsHookMockFactory 提供账号列表数据 Hook 替身。 */ () => ({
useAccountsData: /* useAccountsDataMock 返回固定账号列表和刷新操作。 */ () => ({
accounts: accountListMocks.accounts,
setAccounts: accountListMocks.setAccounts,
loading: false,
loadAccounts: accountListMocks.loadAccounts,
}),
}));
vi.mock('../submoduleHooks', /* submoduleHookMockFactory 提供账号弹窗状态 Hook 替身。 */ () => ({
useAccountSubmodules: /* useAccountSubmodulesMock 返回不阻断页面渲染的子模块状态。 */ () => ({
longLogin: false,
notifChannels: [],
selectedChannelIds: [],
bindingsLoaded: true,
bindingsLoading: false,
bindingsLoadError: '',
aiSettings: {},
saving: false,
passwordLoginView: { status: 'idle', message: '' },
setAiSettings: vi.fn(),
setBindingsDirty: vi.fn(),
openEditModal: vi.fn(),
closeEditModal: vi.fn(),
openAIModal: vi.fn(),
closeAIModal: vi.fn(),
loadNotificationBindings: vi.fn(),
toggleNotificationChannel: vi.fn(),
handleLongLoginToggle: vi.fn(),
handleSaveAISettings: vi.fn(),
handleSaveEdit: vi.fn(),
handleRestartPause: vi.fn(),
handlePasswordLogin: vi.fn(),
handleCancelPasswordLogin: vi.fn(),
}),
}));
vi.mock('../api', /* accountApiMockFactory 提供账号页面 API 替身。 */ () => ({
updateAccountStatus: accountListMocks.updateAccountStatus,
deleteAccount: accountListMocks.deleteAccount,
generateQRLogin: accountListMocks.generateQRLogin,
checkQRLoginStatus: accountListMocks.checkQRLoginStatus,
completeQRVerification: accountListMocks.completeQRVerification,
refreshAccountProfile: accountListMocks.refreshAccountProfile,
}));
vi.mock('../qrPolling', /* qrPollingMockFactory 提供二维码轮询器替身。 */ () => ({
createLatestRequestGate: /* requestGateFactory 创建二维码请求代次门禁。 */ () => ({
next: accountListMocks.requestNext,
isCurrent: accountListMocks.requestIsCurrent,
cancel: accountListMocks.requestCancel,
}),
createQRLoginPoller: /* qrPollerFactory 创建二维码轮询控制器。 */ () => ({
start: accountListMocks.pollerStart,
stop: accountListMocks.pollerStop,
}),
}));
vi.mock('../components/AccountCard', /* accountCardMockFactory 提供账号卡片交互替身。 */ () => {
// AccountCardMock 渲染页面测试需要的账号操作入口。
const AccountCardMock: React.FC<any> = (props /* props 表示账号卡片及其事件回调。 */) => (
<div data-testid={`account-card-${props.account.id}`}>
<span>{props.account.nickname}</span>
<button onClick={/* deleteAction 触发账号删除确认。 */ () => props.onDelete(props.account)}>删除</button>
<button onClick={/* toggleAction 切换账号启用状态。 */ () => props.onToggle(props.account.id, props.account.enabled)}>切换</button>
<button onClick={/* refreshAction 刷新账号资料。 */ () => props.onRefreshProfile(props.account)}>刷新资料</button>
<button onClick={/* reauthorizeAction 启动账号二维码重新授权。 */ () => props.onReauthorize(props.account)}>重新授权</button>
</div>
);
return { AccountCard: AccountCardMock };
});
vi.mock('../components/AccountDeleteDialog', /* deleteDialogMockFactory 提供删除确认弹窗替身。 */ () => {
// AccountDeleteDialogMock 展示删除错误并暴露确认/关闭操作。
const AccountDeleteDialogMock: React.FC<any> = (props /* props 表示删除弹窗及其操作回调。 */) => (
<div data-testid="delete-dialog">
<span>{props.error}</span>
<button onClick={/* confirmAction 确认删除当前账号。 */ () => props.onConfirm()}>确认删除</button>
<button onClick={/* closeAction 关闭删除确认弹窗。 */ () => props.onClose()}>取消</button>
</div>
);
return { AccountDeleteDialog: AccountDeleteDialogMock };
});
vi.mock('../components/AccountQRCodeModal', /* qrModalMockFactory 提供二维码弹窗替身。 */ () => {
// AccountQRCodeModalMock 展示二维码状态并暴露关闭操作。
const AccountQRCodeModalMock: React.FC<any> = (props /* props 表示二维码弹窗及其操作回调。 */) => (
<div data-testid="qr-modal">
<span>{props.status}</span>
<button onClick={/* closeAction 关闭二维码登录弹窗。 */ () => props.onClose()}>关闭二维码</button>
</div>
);
return { AccountQRCodeModal: AccountQRCodeModalMock };
});
vi.mock('../components/AccountEditModal', /* editModalMockFactory 提供账号编辑弹窗替身。 */ () => ({
AccountEditModal: /* AccountEditModalMock 表示账号编辑弹窗替身。 */ () => null,
}));
vi.mock('../components/AccountAISettingsModal', /* aiModalMockFactory 提供 AI 设置弹窗替身。 */ () => ({
AccountAISettingsModal: /* AccountAISettingsModalMock 表示 AI 设置弹窗替身。 */ () => null,
}));
vi.mock('../components/AccountAutomationModal', /* automationModalMockFactory 提供账号任务弹窗替身。 */ () => ({
default: /* AccountAutomationModalMock 表示账号自动化弹窗替身。 */ () => null,
}));
import AccountList from './AccountList';
describe('AccountList 页面组合行为', /* 当前回调验证账号列表页面的搜索、删除、资料和二维码流程。 */ () => {
beforeEach(/* 当前回调重置账号页面 API、请求门禁和浏览器提示替身。 */ () => {
vi.clearAllMocks();
accountListMocks.requestNext.mockReturnValue(1);
accountListMocks.requestIsCurrent.mockReturnValue(true);
accountListMocks.generateQRLogin.mockResolvedValue({ success: true, qr_code_url: 'qr-url', session_id: 'session-1' });
accountListMocks.completeQRVerification.mockResolvedValue({ success: true, account_id: 'account-1' });
accountListMocks.updateAccountStatus.mockResolvedValue({ success: true });
accountListMocks.deleteAccount.mockResolvedValue({ success: true });
accountListMocks.refreshAccountProfile.mockResolvedValue({ success: true });
vi.spyOn(window, 'alert').mockImplementation(/* alertImplementation 屏蔽页面资料刷新提示。 */ () => undefined);
accountListMocks.pollerStart.mockImplementation(/* pollerStartImplementation 保存二维码轮询回调。 */ (_sessionId: string, _check: unknown, callbacks: Record<string, (...args: any[]) => void>) => {
accountListMocks.pollCallbacks = callbacks;
});
});
afterEach(/* 当前回调清理页面 DOM 和浏览器提示替身。 */ () => {
cleanup();
vi.restoreAllMocks();
});
test('搜索只展示匹配账号并保留总数提示', /* 当前回调验证账号搜索过滤行为。 */ () => {
render(<AccountList />);
expect(screen.getByTestId('account-card-account-1')).toBeTruthy();
expect(screen.getByTestId('account-card-account-2')).toBeTruthy();
fireEvent.change(screen.getByPlaceholderText('搜索昵称 / 备注 / 账号ID'), { target: { value: 'Alpha' } });
expect(screen.getByTestId('account-card-account-1')).toBeTruthy();
expect(screen.queryByTestId('account-card-account-2')).toBeNull();
expect(screen.getByText('当前显示 1 / 2 个账号')).toBeTruthy();
});
test('删除确认成功后调用 API 并移除目标账号', /* 当前回调验证删除确认和本地列表更新边界。 */ async () => {
render(<AccountList />);
fireEvent.click(screen.getAllByText('删除')[0]);
expect(screen.getByTestId('delete-dialog')).toBeTruthy();
fireEvent.click(screen.getByText('确认删除'));
await waitFor(/* deleteAssertion 等待删除请求完成。 */ () => expect(accountListMocks.deleteAccount).toHaveBeenCalledWith('account-1'));
expect(accountListMocks.setAccounts).toHaveBeenCalledTimes(1);
// nextAccounts 是页面删除逻辑提交给状态 Setter 的过滤函数结果。
const nextAccounts = accountListMocks.setAccounts.mock.calls[0][0](accountListMocks.accounts);
expect(nextAccounts).toEqual([accountListMocks.accounts[1]]);
});
test('账号卡片操作分别触发状态切换和资料刷新', /* 当前回调验证账号卡片向页面协调器转发操作。 */ async () => {
render(<AccountList />);
fireEvent.click(screen.getAllByText('切换')[0]);
await waitFor(/* toggleAssertion 等待账号状态更新请求完成。 */ () => expect(accountListMocks.updateAccountStatus).toHaveBeenCalledWith('account-1', false));
expect(accountListMocks.loadAccounts).toHaveBeenCalled();
fireEvent.click(screen.getAllByText('刷新资料')[0]);
await waitFor(/* refreshAssertion 等待资料刷新请求完成。 */ () => expect(accountListMocks.refreshAccountProfile).toHaveBeenCalledWith('account-1'));
expect(accountListMocks.loadAccounts).toHaveBeenCalledTimes(2);
});
test('二维码授权启动轮询并在成功后保存会话结果', /* 当前回调验证二维码生成、轮询成功和延迟收束流程。 */ async () => {
render(<AccountList />);
fireEvent.click(screen.getByText('扫码添加新账号'));
expect(await screen.findByTestId('qr-modal')).toBeTruthy();
await waitFor(/* pollerAssertion 等待二维码轮询器启动。 */ () => expect(accountListMocks.pollerStart).toHaveBeenCalledWith('session-1', accountListMocks.checkQRLoginStatus, expect.anything()));
expect(screen.getByText('waiting')).toBeTruthy();
await accountListMocks.pollCallbacks?.onSuccess();
expect(accountListMocks.completeQRVerification).toHaveBeenCalledWith('session-1', undefined);
await waitFor(/* successAssertion 等待二维码成功状态渲染。 */ () => expect(screen.getByText('success')).toBeTruthy());
await waitFor(/* reloadAssertion 等待成功后的账号列表刷新。 */ () => expect(accountListMocks.loadAccounts).toHaveBeenCalled(), { timeout: 2_000 });
});
test('关闭二维码弹窗会停止轮询并取消请求', /* 当前回调验证页面卸载前的二维码资源收束。 */ async () => {
// view 是关闭二维码资源后用于卸载页面的渲染结果。
const view = render(<AccountList />);
fireEvent.click(screen.getByText('扫码添加新账号'));
expect(await screen.findByTestId('qr-modal')).toBeTruthy();
fireEvent.click(screen.getByText('关闭二维码'));
expect(accountListMocks.pollerStop).toHaveBeenCalled();
expect(accountListMocks.requestCancel).toHaveBeenCalled();
view.unmount();
});
});
@@ -0,0 +1,326 @@
import React, { useState } from 'react';
import { createPortal } from 'react-dom';
import { AccountDetail } from '../../../../shared/api-contract';
import {
updateAccountStatus,
deleteAccount,
refreshAccountProfile,
} 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 { AccountCard } from '../components/AccountCard';
import { AccountDeleteDialog } from '../components/AccountDeleteDialog';
import { AccountQRCodeModal } from '../components/AccountQRCodeModal';
import { useAccountsData } from '../hooks';
import { useAccountQRCodeLogin } from '../qrLogin';
import { useAccountSubmodules, type AccountModalType } from '../submoduleHooks';
import type { AccountEditForm } from '../types';
// AccountList 渲染账号列表组件。
const AccountList: React.FC = () => {
// accountData 保存账号列表及其加载控制器。
const { accounts, setAccounts, loading, loadAccounts } = useAccountsData();
// accountSearch 保存列表过滤关键词。
const [accountSearch, setAccountSearch] = useState('');
// refreshingProfileId 保存正在刷新资料的账号 ID。
const [refreshingProfileId, setRefreshingProfileId] = useState<string>('');
// deletingAccountId 保存正在删除的账号 ID。
const [deletingAccountId, setDeletingAccountId] = useState<string>('');
// deleteDialogAccount 保存待确认删除的账号。
const [deleteDialogAccount, setDeleteDialogAccount] = useState<AccountDetail | null>(null);
// deleteError 保存删除失败提示。
const [deleteError, setDeleteError] = useState('');
// activeModal 保存当前打开的账号配置弹窗。
const [activeModal, setActiveModal] = useState<AccountModalType>(null);
// editingAccount 保存当前编辑账号。
const [editingAccount, setEditingAccount] = useState<AccountDetail | null>(null);
// taskAccount 保存当前打开自动化任务弹窗的账号。
const [taskAccount, setTaskAccount] = useState<AccountDetail | null>(null);
// 编辑表单状态。
// editForm 保存编辑弹窗中的账号草稿。
const [editForm, setEditForm] = useState<AccountEditForm>({
remark: '',
cookie: '',
auto_confirm: false,
pause_duration: 0,
username: '',
login_password: '',
show_browser: false,
showLoginPassword: false,
clear_password: false,
});
// accountSubmodules 集中管理编辑弹窗的长登录、通知绑定、AI 和密码登录状态。
const accountSubmodules = useAccountSubmodules({
editingAccount,
setEditingAccount,
setActiveModal,
editForm,
setEditForm,
loadAccounts,
});
// submoduleHandlers 保存编辑弹窗子模块的状态和事件处理函数。
const {
longLogin,
notifChannels,
selectedChannelIds,
bindingsLoaded,
bindingsLoading,
bindingsLoadError,
aiSettings,
saving,
passwordLoginView,
setAiSettings,
setBindingsDirty,
openEditModal,
closeEditModal,
openAIModal,
closeAIModal,
loadNotificationBindings,
toggleNotificationChannel,
handleLongLoginToggle,
handleSaveAISettings,
handleSaveEdit,
handleRestartPause,
handlePasswordLogin,
handleCancelPasswordLogin,
} = accountSubmodules;
// qrLogin 集中管理二维码弹窗状态、轮询、风控验证和异步资源收束。
const qrLogin = useAccountQRCodeLogin({ onLoginSuccess: loadAccounts });
// qrViewState 解构二维码弹窗向页面展示和触发操作所需的最小状态。
const {
showQRModal,
qrCodeUrl,
qrStatus,
qrErrorMessage,
verificationScreenshot,
faceQrUrl,
qrReauthTarget,
startQRLogin,
closeQRModal,
} = qrLogin;
// handleToggle 切换账号启用状态。
const handleToggle = async (id: string, currentStatus: boolean) => {
await updateAccountStatus(id, !currentStatus);
loadAccounts();
};
// openDeleteDialog 打开账号删除确认框。
const openDeleteDialog = (account: AccountDetail) => {
if (deletingAccountId) return;
setDeleteError('');
setDeleteDialogAccount(account);
};
// closeDeleteDialog 关闭账号删除确认框。
const closeDeleteDialog = () => {
if (deletingAccountId) return;
setDeleteError('');
setDeleteDialogAccount(null);
};
// confirmDeleteAccount 执行账号删除并刷新列表状态。
const confirmDeleteAccount = async () => {
// account 保存当前确认删除的账号。
const account = deleteDialogAccount;
if (!account || deletingAccountId) return;
setDeletingAccountId(account.id);
setDeleteError('');
try {
await deleteAccount(account.id);
setAccounts(/* 当前回调处理集合中的单个元素。 */ current => current.filter(/* 当前回调处理集合中的单个元素。 */ item => item.id !== account.id));
setDeleteDialogAccount(null);
} catch (/* error 表示错误。 */ error: any) {
console.error('删除账号失败:', error);
setDeleteError(error?.message || '删除账号失败,请稍后重试');
} finally {
setDeletingAccountId('');
}
};
// handleRefreshProfile 刷新账号资料并同步列表。
const handleRefreshProfile = async (account: AccountDetail) => {
setRefreshingProfileId(account.id);
try {
// res 保存资料刷新接口返回值。
const res = await refreshAccountProfile(account.id);
if (res?.profile_error) {
alert('资料刷新失败:' + res.profile_error);
}
await loadAccounts();
} catch (/* error 表示错误。 */ error: any) {
console.error('刷新账号资料失败:', error);
alert(error?.message || '刷新账号资料失败,请先重新授权该账号');
} finally {
setRefreshingProfileId('');
}
};
if (loading) return <div className="p-20 flex justify-center"><Loader2 className="w-8 h-8 text-brand animate-spin"/></div>;
// filteredAccounts 过滤后的账号列表,负责当前功能中的对应处理。
const filteredAccounts = accounts.filter(/* 当前回调处理集合中的单个元素。 */ account => {
// keyword 搜索关键词。
const keyword = accountSearch.trim().toLowerCase();
if (!keyword) return true;
return [
account.id,
account.nickname,
account.remark,
account.username,
account.runtime_message,
].some(/* 当前回调处理用户交互或异步状态变化。 */ value => (value || '').toLowerCase().includes(keyword));
});
return (
<div className="space-y-8 animate-fade-in relative">
<div className="flex flex-col xl:flex-row xl:justify-between xl:items-end gap-4">
<div>
<h2 className="text-4xl font-extrabold text-gray-900 tracking-tight">账号管理</h2>
<p className="text-gray-500 mt-2 font-medium">管理您的闲鱼授权账号及设置。建议给账号填写备注,便于多账号区分。</p>
</div>
<div className="flex flex-col sm:flex-row gap-3">
<input
value={accountSearch}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ event => setAccountSearch(event.target.value)}
placeholder="搜索昵称 / 备注 / 账号ID"
className="ios-input px-4 py-3 rounded-2xl text-sm w-full sm:w-72"
/>
<button
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => startQRLogin()}
className="ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95"
>
<QrCode className="w-5 h-5" />
扫码添加新账号
</button>
</div>
</div>
<div className="rounded-2xl border border-blue-100 bg-blue-50 px-5 py-4 text-sm text-blue-900 flex flex-col md:flex-row md:items-center md:justify-between gap-2">
<div className="font-bold">当前显示 {filteredAccounts.length} / {accounts.length} 个账号</div>
<div className="text-blue-700">如果某个账号只显示 ID,点该账号右侧“刷新资料”;若刷新失败,先点二维码重新授权。</div>
</div>
{/* Account Grid */}
<div className="grid grid-cols-1 gap-6">
{filteredAccounts.map(/* 当前回调处理集合中的单个元素。 */ account => (
<AccountCard
key={account.id}
account={account}
refreshing={refreshingProfileId === account.id}
deleting={deletingAccountId === account.id}
onRefreshProfile={handleRefreshProfile}
onReauthorize={startQRLogin}
onEdit={openEditModal}
onAI={openAIModal}
onTasks={setTaskAccount}
onToggle={handleToggle}
onDelete={openDeleteDialog}
/>
))}
{accounts.length === 0 && (
<div className="ios-card p-12 text-center">
<div className="w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
<User className="w-10 h-10 text-gray-400" />
</div>
<h3 className="text-lg font-bold text-gray-900">暂无账号</h3>
<p className="text-gray-500 mt-1">请点击右上角扫码添加您的闲鱼账号</p>
</div>
)}
{accounts.length > 0 && filteredAccounts.length === 0 && (
<div className="ios-card p-12 text-center">
<h3 className="text-lg font-bold text-gray-900">没有匹配的账号</h3>
<p className="text-gray-500 mt-1">换一个关键词搜索昵称、备注或账号ID。</p>
</div>
)}
</div>
{taskAccount && createPortal(
<AccountAutomationModal
account={taskAccount}
onClose={/* 当前回调处理用户交互或异步状态变化。 */ () => setTaskAccount(null)}
onSaved={/* 当前回调处理集合中的单个元素。 */ settings => {
setAccounts(/* 当前回调处理集合中的单个元素。 */ current => current.map(/* 当前回调处理集合中的单个元素。 */ account => account.id === taskAccount.id ? {
...account,
auto_rate_enabled: settings.auto_rate_enabled,
rate_content: settings.rate_content,
auto_polish_enabled: settings.auto_polish_enabled,
polish_time: settings.polish_time,
last_rate_scan_at: settings.last_rate_scan_at,
last_polish_date: settings.last_polish_date,
last_polish_at: settings.last_polish_at,
} : account));
}}
/>,
document.body
)}
{deleteDialogAccount && (
<AccountDeleteDialog
account={deleteDialogAccount}
deleting={deletingAccountId === deleteDialogAccount.id}
error={deleteError}
onClose={closeDeleteDialog}
onConfirm={confirmDeleteAccount}
/>
)}
{showQRModal && (
<AccountQRCodeModal
target={qrReauthTarget}
status={qrStatus}
codeUrl={qrCodeUrl}
errorMessage={qrErrorMessage}
faceQrUrl={faceQrUrl}
verificationScreenshot={verificationScreenshot}
onClose={closeQRModal}
/>
)}
{/* 编辑账号弹窗由 accounts feature 组件负责渲染和表单交互。 */}
{activeModal === 'edit' && editingAccount && (
<AccountEditModal
account={editingAccount}
editForm={editForm}
setEditForm={setEditForm}
saving={saving}
onClose={closeEditModal}
onSave={handleSaveEdit}
onRestartPause={handleRestartPause}
longLogin={longLogin}
onToggleLongLogin={handleLongLoginToggle}
passwordLoginView={passwordLoginView}
onPasswordLogin={handlePasswordLogin}
onCancelPasswordLogin={handleCancelPasswordLogin}
notifChannels={notifChannels}
selectedChannelIds={selectedChannelIds}
bindingsLoaded={bindingsLoaded}
bindingsLoading={bindingsLoading}
bindingsLoadError={bindingsLoadError}
onRetryBindings={/* 当前回调处理用户交互或异步状态变化。 */ () => loadNotificationBindings(editingAccount.id)}
onToggleChannel={toggleNotificationChannel}
onSettingsDirty={/* 当前回调处理用户交互或异步状态变化。 */ () => setBindingsDirty(true)}
/>
)}
{activeModal === 'ai-settings' && editingAccount && (
<AccountAISettingsModal
account={editingAccount}
settings={aiSettings}
saving={saving}
onChange={setAiSettings}
onClose={closeAIModal}
onSave={handleSaveAISettings}
/>
)}
</div>
);
};
export default 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 '../../../types';
import type { AccountDetail } from '../../../shared/api-contract';
// qrLoginMocks 保存二维码登录协调器测试使用的接口替身。
const qrLoginMocks = vi.hoisted(/* qrLoginMockFactory 创建二维码登录 API 替身。 */ () => ({
+1 -1
View File
@@ -1,5 +1,5 @@
import { useEffect, useRef, useState } from 'react';
import type { AccountDetail } from '../../../types';
import type { AccountDetail } from '../../../shared/api-contract';
import { checkQRLoginStatus, completeQRVerification, generateQRLogin } from './api';
import { createLatestRequestGate, createQRLoginPoller } from './qrPolling';
@@ -0,0 +1,174 @@
import { afterEach, expect, test, vi } from 'vitest';
import { createLatestRequestGate, createQRLoginPoller } from './qrPolling';
afterEach(/* 当前回调处理用户交互或异步状态变化。 */ () => {
vi.useRealTimers();
});
// flushMicrotasks 刷新微任务队列。
const flushMicrotasks = async () => {
await Promise.resolve();
await Promise.resolve();
};
test('QR poller clears the previous interval before starting another session', /* 当前回调处理用户交互或异步状态变化。 */ () => {
vi.useFakeTimers();
// checkStatus check状态,负责当前功能中的对应处理。
const checkStatus = vi.fn().mockResolvedValue({ status: 'waiting' });
// handlers 处理当前用户操作(rs)。
const handlers = {
onSuccess: vi.fn(),
onTerminalError: vi.fn(),
onPollError: vi.fn(),
};
// poller poller,负责当前功能中的对应处理。
const poller = createQRLoginPoller();
poller.start('sid-1', checkStatus, handlers);
poller.start('sid-2', checkStatus, handlers);
vi.advanceTimersByTime(2000);
expect(checkStatus).toHaveBeenCalledTimes(1);
expect(checkStatus).toHaveBeenCalledWith('sid-2', expect.any(AbortSignal));
});
test('QR poller stops on success and terminal errors', /* 当前回调处理用户交互或异步状态变化。 */ async () => {
vi.useFakeTimers();
// checkStatus check状态,负责当前功能中的对应处理。
const checkStatus = vi.fn()
.mockResolvedValueOnce({ status: 'success', cookies: 'a=b', unb: 'acc1' })
.mockResolvedValueOnce({ status: 'expired' });
// onSuccess 响应当前用户操作(Success)。
const onSuccess = vi.fn();
// onTerminalError 响应当前用户操作(Terminal错误)。
const onTerminalError = vi.fn();
// poller poller,负责当前功能中的对应处理。
const poller = createQRLoginPoller();
poller.start('sid-1', checkStatus, {
onSuccess,
onTerminalError,
onPollError: vi.fn(),
});
await vi.advanceTimersByTimeAsync(2000);
await flushMicrotasks();
expect(onSuccess).toHaveBeenCalledWith({ status: 'success', cookies: 'a=b', unb: 'acc1' });
expect(poller.isActive()).toBe(false);
await vi.advanceTimersByTimeAsync(4000);
expect(checkStatus).toHaveBeenCalledTimes(1);
poller.start('sid-2', checkStatus, {
onSuccess,
onTerminalError,
onPollError: vi.fn(),
});
await vi.advanceTimersByTimeAsync(2000);
await flushMicrotasks();
expect(onTerminalError).toHaveBeenCalledWith({ status: 'expired' });
expect(poller.isActive()).toBe(false);
});
test('QR poller keeps polling during verification and stops on thrown errors', /* 当前回调处理用户交互或异步状态变化。 */ async () => {
vi.useFakeTimers();
// checkStatus check状态,负责当前功能中的对应处理。
const checkStatus = vi.fn()
.mockResolvedValueOnce({
status: 'verification_required',
verification_url: 'https://verify.example',
face_qr_url: 'https://face.example',
})
.mockRejectedValueOnce(new Error('network down'));
// onVerificationRequired 响应当前用户操作(VerificationRequired)。
const onVerificationRequired = vi.fn();
// onPollError 响应当前用户操作(轮询函数错误)。
const onPollError = vi.fn();
// poller poller,负责当前功能中的对应处理。
const poller = createQRLoginPoller();
poller.start('sid-1', checkStatus, {
onSuccess: vi.fn(),
onTerminalError: vi.fn(),
onPollError,
onVerificationRequired,
});
await vi.advanceTimersByTimeAsync(2000);
await flushMicrotasks();
expect(onVerificationRequired).toHaveBeenCalledWith(expect.objectContaining({
status: 'verification_required',
face_qr_url: 'https://face.example',
}));
expect(poller.isActive()).toBe(true);
await vi.advanceTimersByTimeAsync(2000);
await flushMicrotasks();
expect(onPollError).toHaveBeenCalledWith(expect.any(Error));
expect(poller.isActive()).toBe(false);
});
test('QR poller never overlaps slow status requests', /* 当前回调处理用户交互或异步状态变化。 */ async () => {
vi.useFakeTimers();
// resolveStatus resolve状态,负责当前功能中的对应处理。
let resolveStatus: ((value: { /** status 表示状态。 */ status: string }) => void) | undefined;
// checkStatus check状态,负责当前功能中的对应处理。
const checkStatus = vi.fn(/* 当前回调处理用户交互或异步状态变化。 */ () => new Promise<{ /** status 表示状态。 */ status: string }>(/* 当前回调处理用户交互或异步状态变化。 */ resolve => {
resolveStatus = resolve;
}));
// poller poller,负责当前功能中的对应处理。
const poller = createQRLoginPoller();
poller.start('slow-session', checkStatus, {
onSuccess: vi.fn(),
onTerminalError: vi.fn(),
onPollError: vi.fn(),
});
await vi.advanceTimersByTimeAsync(6000);
expect(checkStatus).toHaveBeenCalledTimes(1);
resolveStatus?.({ status: 'waiting' });
await flushMicrotasks();
await vi.advanceTimersByTimeAsync(2000);
expect(checkStatus).toHaveBeenCalledTimes(2);
poller.stop();
});
test('latest request gate rejects stale generation after switch or cancel', /* 当前回调处理用户交互或异步状态变化。 */ () => {
// gate gate,负责当前功能中的对应处理。
const gate = createLatestRequestGate();
// first 首项。
const first = gate.next();
// second second,负责当前功能中的对应处理。
const second = gate.next();
expect(gate.isCurrent(first)).toBe(false);
expect(gate.isCurrent(second)).toBe(true);
gate.cancel();
expect(gate.isCurrent(second)).toBe(false);
});
test('stopping QR polling aborts the in-flight status request without reporting an error', /* 当前回调处理用户交互或异步状态变化。 */ async () => {
vi.useFakeTimers();
// onPollError 响应当前用户操作(轮询函数错误)。
const onPollError = vi.fn();
// observedSignal observedSignal,负责当前功能中的对应处理。
let observedSignal: AbortSignal | undefined;
// checkStatus check状态,负责当前功能中的对应处理。
const checkStatus = vi.fn(/* 当前回调处理用户交互或异步状态变化。 */ (_sessionId: string, signal?: AbortSignal) => {
observedSignal = signal;
return new Promise<{ /** status 表示状态。 */ status: string }>(/* 当前回调处理用户交互或异步状态变化。 */ (_resolve, reject) => {
signal?.addEventListener('abort', /* 当前回调处理用户交互或异步状态变化。 */ () => reject(new DOMException('aborted', 'AbortError')), { once: true });
});
});
// poller poller,负责当前功能中的对应处理。
const poller = createQRLoginPoller();
poller.start('sid', checkStatus, { onSuccess: vi.fn(), onTerminalError: vi.fn(), onPollError });
await vi.advanceTimersByTimeAsync(2000);
poller.stop();
await flushMicrotasks();
expect(observedSignal?.aborted).toBe(true);
expect(onPollError).not.toHaveBeenCalled();
});
@@ -1,11 +1,10 @@
import { describe, expect, test } from 'vitest';
import type { AccountDetail } from '../../../types';
import type { AccountDetail } from '../../../shared/api-contract';
import { accountRuntimePresentation, isOlderStatus, mergeAccountRuntimeStatuses } from './runtime';
// account 创建运行状态测试使用的最小账号对象。
const account = (overrides: Partial<AccountDetail> = {}): AccountDetail => ({
id: 'account-1',
value: 'cookie',
enabled: true,
auto_confirm: false,
...overrides,
+1 -1
View File
@@ -1,5 +1,5 @@
import type { AccountRuntimeStatus } from './api';
import type { AccountDetail } from '../../../types';
import type { AccountDetail } from '../../../shared/api-contract';
import type { AccountRuntimePresentation } from './types';
// isOlderStatus 判断传入的运行时快照是否早于账号当前已展示的快照。
+1 -1
View File
@@ -1,5 +1,5 @@
import { expect, test } from 'vitest';
import type { AccountDetail } from '../../../types';
import type { AccountDetail } from '../../../shared/api-contract';
import {
buildAccountLoginInfoUpdate,
isCurrentAccountRequest,
+1 -1
View File
@@ -1,4 +1,4 @@
import type { AccountDetail } from '../../../types';
import type { AccountDetail } from '../../../shared/api-contract';
import type { PasswordLoginStatusResponse } from './api';
import type { AccountEditForm, PasswordLoginView } from './types';
@@ -2,7 +2,7 @@
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 '../../../types';
import type { AccountDetail, AIReplySettings } from '../../../shared/api-contract';
import {
cancelPasswordLogin,
checkPasswordLoginStatus,
@@ -101,6 +101,7 @@ describe('useAccountSubmodules', /* 当前回调处理账号编辑、AI、通知
expect(hook.result.current.longLogin.canOpen).toBe(true);
expect(hook.result.current.notifChannels).toHaveLength(1);
expect(hook.result.current.selectedChannelIds).toEqual([1]);
expect(setEditForm).toHaveBeenCalledWith(expect.objectContaining({ cookie: '', login_password: '' }));
await act(
// toggleAction 切换通知渠道绑定。
() => hook.result.current.toggleNotificationChannel(2),
@@ -1,9 +1,9 @@
import { useCallback, useEffect, useRef, useState, type Dispatch, type SetStateAction } from 'react';
import type { AccountDetail, AIReplySettings, NotificationChannel } from '../../../types';
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 { shouldSaveNotificationBindings } from '../../../components/accountBindings';
import { shouldSaveNotificationBindings } from './accountBindings';
/** AccountList 当前编辑弹窗类型。 */
export type AccountModalType = 'edit' | 'ai-settings' | null;
@@ -124,7 +124,8 @@ export const useAccountSubmodules = ({ editingAccount, setEditingAccount, setAct
clearPasswordTimer();
setPasswordLoginView({ sessionId: '', status: 'idle', message: '', qrCodeUrl: '' });
setEditingAccount(account);
setEditForm({ remark: account.remark || '', cookie: account.value || '', auto_confirm: account.auto_confirm || false, pause_duration: account.pause_duration || 0, username: account.username || '', login_password: account.login_password || '', show_browser: account.show_browser || false, showLoginPassword: false, clear_password: false });
// 摘要接口不会返回 Cookie 或密码明文;编辑表单只接收本次用户主动输入的秘密。
setEditForm({ remark: account.remark || '', cookie: '', auto_confirm: account.auto_confirm || false, pause_duration: account.pause_duration || 0, username: account.username || '', login_password: '', show_browser: account.show_browser || false, showLoginPassword: false, clear_password: false });
setActiveModal('edit');
setLongLogin({ loading: true, saving: false, canOpen: false, enabled: false, error: '' });
// longLoginResult 保存长登录设置读取结果。
@@ -200,7 +201,8 @@ export const useAccountSubmodules = ({ editingAccount, setEditingAccount, setAct
// payload 保存需要提交的账号编辑补丁。
const payload: Parameters<typeof updateAccountSettings>[1] = {};
if (editForm.remark !== (editingAccount.remark || '')) payload.remark = editForm.remark;
if (editForm.cookie && editForm.cookie !== (editingAccount.value || '')) payload.cookie = editForm.cookie;
// 编辑表单中的 Cookie 只有用户本次输入时才会提交,避免从账号摘要读取或回填明文。
if (editForm.cookie) payload.cookie = editForm.cookie;
if (editForm.auto_confirm !== editingAccount.auto_confirm) payload.auto_confirm = editForm.auto_confirm;
if (shouldUpdateAccountPause(editForm.pause_duration, editingAccount)) payload.pause_duration = editForm.pause_duration;
// loginInfo 保存登录字段变更补丁。
+1 -1
View File
@@ -1,5 +1,5 @@
import type { Dispatch, SetStateAction } from 'react';
import type { AccountDetail, AIReplySettings, NotificationChannel } from '../../../types';
import type { AccountDetail, AIReplySettings, NotificationChannel } from '../../../shared/api-contract';
// AccountEditForm 描述账号编辑弹窗中的可编辑字段。
export interface AccountEditForm {
File diff suppressed because it is too large. Load diff
+77 -11
View File
@@ -1,12 +1,78 @@
// 卡密 feature 只通过本适配层访问库存和批量接口,页面不直接依赖共享 API 文件。
export {
appendCardData,
batchCreateCards,
createCard,
deleteCard,
getCards,
updateCard,
} from '../../../services/api';
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';
// Cards
// normalizeCard 归一化卡密数据。
const normalizeCard = (item: any): Card => {
// apiConfig 卡密接口配置,用于当前 API 处理流程。
let apiConfig = item.api_config;
if (typeof apiConfig === 'string' && apiConfig.trim()) {
try {
apiConfig = JSON.parse(apiConfig);
} catch {
apiConfig = undefined;
}
}
return {...item, api_config: apiConfig || undefined} as Card;
};
// 卡密 feature 重新导出接口响应类型,保持批量结果契约稳定。
export type { CardAppendResponse, CardBatchResponse } from '../../../types';
// cardPayload 卡密请求载荷,用于当前 API 处理流程。
const cardPayload = (data: Partial<Card>): Record<string, unknown> => ({
...data,
api_config: data.api_config ? JSON.stringify(data.api_config) : '',
});
// getCards 读取卡密列表。
export const getCards = async (options?: RequestControlOptions): Promise<Card[]> => {
// res 接口响应结果,用于当前 API 处理流程。
const res = await get<unknown>('/api/v1/cards', undefined, options);
// cards 卡密列表,用于当前 API 处理流程。
const cards = collectionFrom<Card>(res, ['cards', 'data', 'items']);
return cards.map(normalizeCard);
};
// createCard 创建卡密组。
export const createCard = async (data: Partial<Card>): Promise<MutationIDResponse> => {
return post('/api/v1/cards', cardPayload(data));
};
// updateCard 更新卡密组。
export const updateCard = async (cardId: string | number, data: Partial<Card>): Promise<OperationResponse> => {
return put(`/api/v1/cards/${cardId}`, cardPayload(data));
};
// deleteCard 删除卡密组。
export const deleteCard = async (cardId: string | number): Promise<OperationResponse> => {
return del(`/api/v1/cards/${cardId}`);
};
// getCardDetails 读取卡密组详情。
export const getCardDetails = async (cardId: string | number): Promise<Card> => {
// card 卡密详情,用于当前 API 处理流程。
const card = await get<Card>(`/api/v1/cards/${cardId}/details`);
return normalizeCard(card);
};
// 批量创建卡密组(上传表格)
export const batchCreateCards = async (file: File, options?: RequestControlOptions): Promise<CardBatchResponse> => {
// 批量创建接口返回总行数、成功数、失败数和逐行结果。
// CardBatchResponse 保留旧字段名称,调用方无需转换统计字段。
// rows 中的 id 只在创建成功时返回。
// rows 中的 error 只在对应行失败时返回。
// 表单上传方式和接口路径保持不变。
// 此处只收紧 TypeScript 响应契约。
const body = new FormData();
body.append('file', file);
return postForm('/api/v1/cards/batch', body, options);
};
// 往 data 类型卡密组批量追加卡密号
export const appendCardData = async (cardId: string | number, content: string, options?: RequestControlOptions): Promise<CardAppendResponse> => {
return post(`/api/v1/cards/${cardId}/append-data`, { content }, options);
};
@@ -1,5 +1,5 @@
import { expect, test } from 'vitest';
import type { Card } from '../../../types';
import type { Card } from '../../../shared/api-contract';
import { canSubmitAppend, filterCards, isCurrentCardRequest, previewAppendContent } from './batchState';
// cards 是卡密筛选测试使用的最小卡密组列表。
+1 -1
View File
@@ -1,4 +1,4 @@
import type { Card } from '../../../types';
import type { Card } from '../../../shared/api-contract';
// filterCards 按类型和名称筛选卡密组,两个条件同时满足才保留。
export const filterCards = (
@@ -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 { Card } from '../../../types';
import type { Card } from '../../../shared/api-contract';
import { createCard, deleteCard, updateCard } from './api';
import { useCardActions } from './cardActions';
+1 -1
View File
@@ -1,5 +1,5 @@
import { useCallback, useMemo, useState, type Dispatch, type SetStateAction } from 'react';
import type { Card } from '../../../types';
import type { Card } from '../../../shared/api-contract';
import { createCard, deleteCard, updateCard } from './api';
import { filterCards } from './batchState';
import type { AddCardForm, EditCardForm } from './types';
@@ -1,7 +1,7 @@
import React from 'react';
import { createPortal } from 'react-dom';
import { FileDown, ListPlus, Loader2, Plus, Upload, X } from 'lucide-react';
import type { Card } from '../../../../types';
import type { Card } from '../../../../shared/api-contract';
import type { CardBatchModalProps } from '../types';
// BatchCardImportModal 负责卡密批量创建和单组库存追加的交互界面。
@@ -1,6 +1,6 @@
import React from 'react';
import { Code, CreditCard, FileText, Image as ImageIcon } from 'lucide-react';
import type { Card } from '../../../../types';
import type { Card } from '../../../../shared/api-contract';
// CardIconProps 描述库存图标所需的卡密类型参数。
interface CardIconProps {
+32 -1
View File
@@ -1,7 +1,7 @@
// @vitest-environment jsdom
import { act, renderHook, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, test, vi } from 'vitest';
import type { Card } from '../../../types';
import type { Card } from '../../../shared/api-contract';
import { appendCardData, batchCreateCards, getCards } from './api';
import { useCardBatchActions, useCardsData } from './hooks';
@@ -212,4 +212,35 @@ describe('useCardsData 与 useCardBatchActions', /* 当前回调处理卡密库
expect(hook.result.current.cards).toEqual([]);
hook.unmount();
});
test('批量创建在卸载时取消未完成请求', /* 当前回调验证批量表单卸载后不再允许晚到上传响应更新状态。 */ async () => {
// uploadSignal 保存批量创建接口收到的取消信号。
let uploadSignal: AbortSignal | undefined;
batchCreateMock.mockImplementation(
// pendingCreate 保持上传请求未完成,以便验证 Hook 卸载时主动取消。
(_file, requestOptions) => {
uploadSignal = requestOptions?.signal;
return new Promise(/* pendingCreateExecutor 故意不完成上传 Promise,直到 Hook 卸载取消请求。 */ () => undefined);
},
);
// hook 是带有上传文件的批量创建 Hook。
const hook = renderHook(
// batchHookFactory 创建批量操作 Hook。
() => useCardBatchActions({ dataCards: [cardFixture], loadCards: loadCardsFixture }),
);
await act(
// fileAction 写入将要上传的卡密文件。
() => hook.result.current.setBatchFile(new File(['name'], 'cards.csv')),
);
await act(
// createAction 发起尚未完成的上传但不等待其结束。
() => { void hook.result.current.handleBatchCreate(); },
);
await waitFor(
// uploadStartedAssertion 等待上传请求拿到取消信号。
() => expect(uploadSignal).toBeDefined(),
);
hook.unmount();
expect(uploadSignal?.aborted).toBe(true);
});
});
+13 -1
View File
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useMemo, useRef, useState, type Dispatch, type SetStateAction } from 'react';
import { appendCardData, batchCreateCards, getCards } from './api';
import type { Card } from '../../../types';
import type { Card } from '../../../shared/api-contract';
import { canSubmitAppend, isCurrentCardRequest, previewAppendContent } from './batchState';
import type { CardBatchState } from './types';
@@ -110,6 +110,18 @@ export const useCardBatchActions = (options: CardBatchOptions): CardBatchState =
// lastAppendTarget 保存最近一次提交追加的目标 ID,供失败重试使用。
const lastAppendTarget = useRef('');
useEffect(
// 批量操作生命周期副作用在弹窗页面卸载时使未完成请求失效,防止晚到响应写入已销毁的表单状态。
() => (
// batchRequestCleanup 取消创建或追加请求,并推进代次屏蔽不响应 AbortSignal 的旧响应。
() => {
requestGeneration.current += 1;
requestAbort.current?.abort();
}
),
[],
);
// appendPreview 按行派生追加预览,不重复存储派生状态。
const appendPreview = useMemo(
// 追加预览回调根据当前文本派生有效卡密行。
@@ -0,0 +1,139 @@
// @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';
// cardListMocks 保存卡密页面测试使用的 Hook、API 和批量弹窗替身。
const cardListMocks = vi.hoisted(/* cardListMockFactory 创建卡密页面共享替身。 */ () => ({
cards: [] as Card[],
loadCards: vi.fn(),
openBatchModal: vi.fn(),
createCard: vi.fn(),
deleteCard: vi.fn(),
updateCard: vi.fn(),
}));
vi.mock('../hooks', /* cardsHooksMockFactory 提供卡密库存和批量 Hook 替身。 */ () => ({
useCardsData: /* useCardsDataMock 返回固定卡密库存。 */ () => ({
cards: cardListMocks.cards,
setCards: vi.fn(),
loading: false,
loadCards: cardListMocks.loadCards,
}),
useCardBatchActions: /* useCardBatchActionsMock 返回批量弹窗状态。 */ () => ({
showBatchModal: false,
setShowBatchModal: vi.fn(),
batchTab: 'create',
setBatchTab: vi.fn(),
batchFile: null,
setBatchFile: vi.fn(),
batchResult: null,
batchBusy: false,
appendTargetId: '',
setAppendTargetId: vi.fn(),
appendContent: '',
setAppendContent: vi.fn(),
appendResult: null,
appendError: '',
appendPreview: [],
openBatchModal: cardListMocks.openBatchModal,
closeBatchModal: vi.fn(),
handleBatchCreate: vi.fn(),
handleBatchAppend: vi.fn(),
handleRetryBatchCreate: vi.fn(),
handleRetryBatchAppend: vi.fn(),
}),
}));
vi.mock('../api', /* cardsApiMockFactory 提供卡密页面动作 API 替身。 */ () => ({
createCard: cardListMocks.createCard,
deleteCard: cardListMocks.deleteCard,
updateCard: cardListMocks.updateCard,
}));
vi.mock('../components/BatchCardImportModal', /* batchModalMockFactory 提供批量弹窗替身。 */ () => ({
BatchCardImportModal: /* BatchCardImportModalMock 表示批量导入弹窗替身。 */ () => null,
}));
import CardList from './CardList';
// cardFixture 表示卡密页面中的 data 类型库存。
const cardFixture: Card = {
id: 1,
name: '库存一',
type: 'data',
data_content: 'A\nB',
description: '测试库存',
enabled: true,
delay_seconds: 0,
created_at: '2026-08-15T00:00:00Z',
updated_at: '2026-08-15T00:00:00Z',
};
// textCardFixture 表示卡密页面中的文本类型卡密组。
const textCardFixture: Card = {
...cardFixture,
id: 2,
name: '文案二',
type: 'text',
data_content: undefined,
text_content: '感谢购买',
};
describe('CardList 页面组合行为', /* 当前回调验证卡密筛选、批量入口、新增、编辑、启停和删除流程。 */ () => {
beforeEach(/* 当前回调重置卡密页面 API、库存和浏览器提示替身。 */ () => {
vi.clearAllMocks();
cardListMocks.cards = [cardFixture, textCardFixture];
cardListMocks.loadCards.mockResolvedValue(undefined);
cardListMocks.createCard.mockResolvedValue({ success: true, id: 3 });
cardListMocks.deleteCard.mockResolvedValue({ success: true });
cardListMocks.updateCard.mockResolvedValue({ success: true });
vi.spyOn(window, 'alert').mockImplementation(/* alertImplementation 屏蔽卡密页面提示。 */ () => undefined);
vi.spyOn(window, 'confirm').mockReturnValue(true);
});
afterEach(/* 当前回调清理卡密页面 DOM 和浏览器提示替身。 */ () => {
cleanup();
vi.restoreAllMocks();
});
test('筛选卡密并打开批量导入入口', /* 当前回调验证卡密列表筛选和批量操作转发。 */ () => {
render(<CardList />);
expect(screen.getByText('显示 2 / 2 组')).toBeTruthy();
fireEvent.change(screen.getByLabelText('按卡密类型筛选'), { target: { value: 'data' } });
expect(screen.getByText('显示 1 / 2 组')).toBeTruthy();
fireEvent.change(screen.getByLabelText('按卡密名称搜索'), { target: { value: '库存' } });
expect(screen.getByText('显示 1 / 2 组')).toBeTruthy();
fireEvent.click(screen.getByText('批量导入'));
expect(cardListMocks.openBatchModal).toHaveBeenCalledTimes(1);
});
test('新增和编辑卡密会映射表单字段并刷新库存', /* 当前回调验证卡密新增与编辑页面行为。 */ async () => {
render(<CardList />);
fireEvent.click(screen.getByText('添加新卡密'));
fireEvent.change(screen.getByPlaceholderText('例如:VIP会员卡密'), { target: { value: '新文案' } });
fireEvent.click(screen.getByRole('button', { name: '文本' }));
fireEvent.change(screen.getByPlaceholderText('请输入每次发货时发送的固定文字'), { target: { value: '欢迎购买' } });
fireEvent.click(screen.getByText('添加卡密'));
await waitFor(/* addAssertion 等待卡密创建请求完成。 */ () => expect(cardListMocks.createCard).toHaveBeenCalledWith(expect.objectContaining({ name: '新文案', type: 'text', text_content: '欢迎购买' })));
expect(cardListMocks.loadCards).toHaveBeenCalledTimes(1);
fireEvent.click(screen.getAllByTitle('编辑')[0]);
fireEvent.change(screen.getByDisplayValue('库存一'), { target: { value: '库存更新' } });
fireEvent.click(screen.getByText('保存更改'));
await waitFor(/* editAssertion 等待卡密更新请求完成。 */ () => expect(cardListMocks.updateCard).toHaveBeenCalledWith(1, expect.objectContaining({ name: '库存更新', data_content: 'A\nB' })));
expect(cardListMocks.loadCards).toHaveBeenCalledTimes(2);
});
test('启停、复制和删除按钮调用对应页面动作', /* 当前回调验证卡密行级动作边界。 */ async () => {
render(<CardList />);
fireEvent.click(screen.getByRole('button', { name: '切换卡密 库存一 状态' }));
await waitFor(/* toggleAssertion 等待卡密启停请求完成。 */ () => expect(cardListMocks.updateCard).toHaveBeenCalledWith(1, expect.objectContaining({ enabled: false })));
Object.assign(navigator, { clipboard: { writeText: vi.fn().mockResolvedValue(undefined) } });
fireEvent.click(screen.getAllByTitle('复制卡密组ID,用于批量铺货表格')[0]);
fireEvent.click(screen.getByRole('button', { name: '删除卡密 库存一' }));
await waitFor(/* deleteAssertion 等待卡密删除请求完成。 */ () => expect(cardListMocks.deleteCard).toHaveBeenCalledWith(1));
expect(cardListMocks.loadCards).toHaveBeenCalledTimes(2);
});
});
@@ -0,0 +1,632 @@
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 { BatchCardImportModal } from '../components/BatchCardImportModal';
import { CardIcon } from '../components/CardIcon';
import { useCardBatchActions, useCardsData } from '../hooks';
import { useCardActions } from '../cardActions';
// CardList 渲染卡密列表组件。
const CardList: React.FC = () => {
// { 解构得到当前 Hook 返回的状态和操作函数。
const { cards, loadCards } = useCardsData();
// cardActions 集中管理卡密编辑、新增、删除、筛选和模板动作。
const cardActions = useCardActions({ cards, loadCards });
// actionState 解构得到卡密页面动作协调器状态和方法。
const {
dataCards,
filteredCards,
typeFilter,
setTypeFilter,
nameSearch,
setNameSearch,
showEditModal,
setShowEditModal,
showAddModal,
setShowAddModal,
selectedCard,
editForm,
setEditForm,
addForm,
setAddForm,
handleEdit,
handleSaveEdit,
handleDelete,
handleAddCard,
toggleCardStatus,
copyCardID,
downloadCardTemplate,
} = cardActions;
// batchState 批量发布状态。
const batchState = useCardBatchActions({ dataCards, loadCards });
return (
<div className="space-y-6 animate-fade-in">
<div className="flex flex-col md:flex-row justify-between md:items-end gap-4">
<div>
<h2 className="text-4xl font-extrabold text-gray-900 tracking-tight">卡密库存</h2>
<p className="text-gray-500 mt-2 font-medium">管理自动发货的卡密、链接或图片资源。</p>
</div>
<div className="flex items-center gap-3">
<button
onClick={batchState.openBatchModal}
className="px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors"
>
<Upload className="w-5 h-5" />
批量导入
</button>
<button
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setShowAddModal(true)}
className="ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95"
>
<Plus className="w-5 h-5" />
添加新卡密
</button>
</div>
</div>
<div className="ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white">
<div className="flex flex-col gap-3 border-b border-gray-50 bg-surface-muted p-4 sm:flex-row sm:items-center sm:justify-between">
<div className="flex flex-1 flex-col gap-3 sm:flex-row">
<div className="relative sm:w-48">
<SlidersHorizontal className="pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
<select
aria-label="按卡密类型筛选"
value={typeFilter}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ event => setTypeFilter(event.target.value as Card['type'] | '')}
className="ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm"
>
<option value="">全部类型</option>
<option value="data">批量卡密</option>
<option value="text">文本</option>
<option value="api">API</option>
<option value="image">图片</option>
</select>
</div>
<div className="relative w-full sm:max-w-sm">
<Search className="pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
<input
type="search"
aria-label="按卡密名称搜索"
placeholder="搜索卡密名称..."
value={nameSearch}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ event => setNameSearch(event.target.value)}
className="ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"
/>
</div>
</div>
<div className="whitespace-nowrap px-1 text-xs font-bold text-gray-400">
显示 {filteredCards.length} / {cards.length} 组
</div>
</div>
<div className="overflow-x-auto">
<table className="w-full table-fixed text-left border-collapse">
<thead>
<tr className="bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50">
<th className="w-[23%] px-5 py-5">卡密名称</th>
<th className="w-[8%] px-3 py-5">卡密组ID</th>
<th className="w-[7%] px-2 py-5">类型</th>
<th className="w-[27%] px-5 py-5">内容/库存</th>
<th className="w-[19%] px-5 py-5">描述</th>
<th className="w-[7%] px-2 py-5">状态</th>
<th className="w-[9%] px-3 py-5 text-right">操作</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-50">
{filteredCards.map(/* 当前回调处理集合中的单个元素。 */ (card) => {
// 计算库存或内容预览
let stockInfo = '';
if (card.type === 'data' && card.data_content) {
// lines 文本行列表。
const lines = card.data_content.split('\n').filter(/* 当前回调处理集合中的单个元素。 */ line => line.trim());
stockInfo = `库存: ${lines.length} 条`;
} else if (card.type === 'text' && card.text_content) {
stockInfo = card.text_content;
} else if (card.type === 'api' && card.api_config) {
stockInfo = card.api_config.url;
} else if (card.type === 'image' && card.image_url) {
stockInfo = '图片链接';
}
return (
<tr key={card.id} className="hover:bg-warning-50/50 transition-colors group">
<td className="px-5 py-5 align-middle">
<div className="flex items-center gap-2.5">
<div className="shrink-0 rounded-xl bg-gray-50 p-2 transition-colors group-hover:bg-white">
<CardIcon type={card.type} />
</div>
<span className="line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900" title={card.name}>{card.name}</span>
</div>
</td>
<td className="px-3 py-5">
<button
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => copyCardID(card.id)}
className="inline-flex max-w-full items-center gap-1 rounded-lg bg-gray-100 px-2 py-1.5 font-mono text-[11px] font-extrabold text-gray-700 transition-colors hover:bg-gray-200"
title="复制卡密组ID,用于批量铺货表格"
>
<span className="truncate">{card.id}</span>
<Copy className="h-3 w-3 shrink-0" />
</button>
</td>
<td className="px-2 py-5">
<span className={`inline-flex rounded-md px-2 py-1 text-[11px] font-bold ${
card.type === 'text' ? 'bg-blue-50 text-blue-600' :
card.type === 'data' ? 'bg-purple-50 text-purple-600' :
card.type === 'api' ? 'bg-blue-50 text-blue-600' :
'bg-pink-50 text-pink-600'
}`}>
{card.type === 'text' ? '文本' :
card.type === 'data' ? '批量' :
card.type === 'api' ? 'API' : '图片'}
</span>
</td>
<td className="px-5 py-5">
<span className="line-clamp-3 break-all font-mono text-sm leading-5 text-gray-600" title={stockInfo}>
{stockInfo}
</span>
</td>
<td className="px-5 py-5">
<span
className="block truncate text-sm text-gray-500"
title={card.description || '-'}
>
{card.description || '-'}
</span>
</td>
<td className="px-2 py-5">
<button
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => toggleCardStatus(card)}
aria-label={`切换卡密 ${card.name} 状态`}
className={`w-12 h-8 rounded-full relative transition-colors ${
card.enabled ? 'bg-green-500' : 'bg-gray-300'
}`}
>
<div className={`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${
card.enabled ? 'left-5' : 'left-1'
}`}></div>
</button>
</td>
<td className="px-3 py-5">
<div className="flex items-center justify-end gap-0.5">
<button
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => handleEdit(card)}
className="rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black"
title="编辑"
>
<Edit className="w-4 h-4" />
</button>
<button
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => handleDelete(card.id)}
aria-label={`删除卡密 ${card.name}`}
className="rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500"
>
<Trash2 className="h-4 w-4" />
</button>
</div>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
{filteredCards.length === 0 && (
<div className="py-20 text-center text-gray-400">
<Package className="w-12 h-12 mx-auto mb-4 opacity-30" />
<p>{cards.length === 0 ? '暂无卡密配置,请点击右上角添加。' : '没有符合当前筛选条件的卡密组。'}</p>
</div>
)}
</div>
{/* 编辑卡密弹窗 - 使用 Portal */}
{showEditModal && selectedCard && createPortal(
<div className="modal-overlay-centered">
<div className="modal-container">
<div className="modal-header">
<h3 className="text-2xl font-extrabold text-gray-900">编辑卡密</h3>
<button
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setShowEditModal(false)}
className="p-2 rounded-xl hover:bg-gray-100 transition-colors"
>
<X className="w-5 h-5 text-gray-500" />
</button>
</div>
<div className="modal-body">
<div className="space-y-5">
{/* 基本信息 */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label className="block text-sm font-bold text-gray-700 mb-2">卡密名称 <span className="text-red-500">*</span></label>
<input
type="text"
value={editForm.name || ''}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditForm({ ...editForm, name: e.target.value })}
className="w-full ios-input px-4 py-3 rounded-xl"
placeholder="例如:游戏点卡、会员卡等"
/>
</div>
<div>
<label className="block text-sm font-bold text-gray-700 mb-2">卡券类型</label>
<select
value={editForm.type || 'text'}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditForm({ ...editForm, type: e.target.value as any })}
className="w-full ios-input px-4 py-3 rounded-xl"
>
<option value="">请选择类型</option>
<option value="text">固定文字</option>
<option value="data">批量数据</option>
{selectedCard?.type === 'api' && <option value="api">API接口(仅保留现有配置)</option>}
<option value="image">图片</option>
</select>
</div>
</div>
{/* API 配置 */}
{editForm.type === 'api' && (
<div className="border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50">
<h3 className="font-bold text-gray-900">API 配置</h3>
<div>
<label className="block text-sm font-bold text-gray-700 mb-2">API 地址</label>
<input
type="url"
value={editForm.api_url || ''}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditForm({ ...editForm, api_url: e.target.value })}
className="w-full ios-input px-4 py-3 rounded-xl font-mono text-sm"
placeholder="https://api.example.com/get-card"
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-bold text-gray-700 mb-2">请求方法</label>
<select
value={editForm.api_method || 'GET'}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditForm({ ...editForm, api_method: e.target.value as 'GET' | 'POST' })}
className="w-full ios-input px-4 py-3 rounded-xl"
>
<option value="GET">GET</option>
<option value="POST">POST</option>
</select>
</div>
<div>
<label className="block text-sm font-bold text-gray-700 mb-2">超时时间(秒)</label>
<input
type="number"
value={editForm.api_timeout || 10}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditForm({ ...editForm, api_timeout: parseInt(e.target.value) || 10 })}
className="w-full ios-input px-4 py-3 rounded-xl"
min="1"
max="60"
/>
</div>
</div>
<div>
<label className="block text-sm font-bold text-gray-700 mb-2">请求头(JSON 格式)</label>
<textarea
value={editForm.api_headers || ''}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditForm({ ...editForm, api_headers: e.target.value })}
className="w-full ios-input px-4 py-3 rounded-xl h-20 resize-none font-mono text-sm"
placeholder='{"Authorization": "Bearer token"}'
/>
</div>
<div>
<label className="block text-sm font-bold text-gray-700 mb-2">请求参数(JSON 格式)</label>
<textarea
value={editForm.api_params || ''}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditForm({ ...editForm, api_params: e.target.value })}
className="w-full ios-input px-4 py-3 rounded-xl h-20 resize-none font-mono text-sm"
placeholder='{"type": "card", "count": 1}'
/>
</div>
</div>
)}
{/* 固定文字配置 */}
{editForm.type === 'text' && (
<div className="border border-gray-200 rounded-xl p-4 bg-gray-50">
<h3 className="font-bold text-gray-900 mb-3">固定文字配置</h3>
<div>
<label className="block text-sm font-bold text-gray-700 mb-2">文字内容</label>
<textarea
value={editForm.text_content || ''}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditForm({ ...editForm, text_content: e.target.value })}
className="w-full ios-input px-4 py-3 rounded-xl h-32 resize-none"
placeholder="请输入要发送的固定文字内容..."
/>
</div>
</div>
)}
{/* 批量数据配置 */}
{editForm.type === 'data' && (
<div className="border border-gray-200 rounded-xl p-4 bg-gray-50">
<h3 className="font-bold text-gray-900 mb-3">批量数据配置</h3>
<div>
<label className="block text-sm font-bold text-gray-700 mb-2">数据内容(一行一个)</label>
<textarea
value={editForm.data_content || ''}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditForm({ ...editForm, data_content: e.target.value })}
className="w-full ios-input px-4 py-3 rounded-xl h-80 resize-none font-mono text-sm"
placeholder="请输入数据,每行一个:&#10;卡号1:密码1&#10;卡号2:密码2&#10;或者&#10;兑换码1&#10;兑换码2"
/>
<p className="text-xs text-gray-500 mt-2">支持格式:卡号:密码 或 单独的兑换码</p>
<p className="text-xs text-gray-500">当前库存:<span className="font-bold text-blue-600">
{editForm.data_content ? editForm.data_content.split('\n').filter(/* 当前回调处理集合中的单个元素。 */ line => line.trim()).length : 0}
</span> 条</p>
</div>
</div>
)}
{/* 图片配置 */}
{editForm.type === 'image' && (
<div className="border border-gray-200 rounded-xl p-4 bg-gray-50">
<h3 className="font-bold text-gray-900 mb-3">图片配置</h3>
<div>
<label className="block text-sm font-bold text-gray-700 mb-2">图片 URL</label>
<input
type="url"
value={editForm.image_url || ''}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditForm({ ...editForm, image_url: e.target.value })}
className="w-full ios-input px-4 py-3 rounded-xl font-mono text-sm"
placeholder="https://example.com/image.png"
/>
<p className="text-xs text-gray-500 mt-2">输入图片卡密的 URL 地址</p>
</div>
{editForm.image_url && (
<div className="mt-3">
<label className="block text-sm font-bold text-gray-700 mb-2">图片预览</label>
<img
src={editForm.image_url}
alt="预览"
className="max-w-full max-h-48 rounded-xl border border-gray-200"
onError={/* 当前回调处理用户交互或异步状态变化。 */ (e) => { e.currentTarget.src = 'https://via.placeholder.com/400x200?text=图片加载失败'; }}
/>
</div>
)}
</div>
)}
{/* 延时发货时间 */}
<div>
<label className="block text-sm font-bold text-gray-700 mb-2">延时发货时间(秒)</label>
<div className="flex items-center gap-2">
<input
type="number"
value={editForm.delay_seconds || 0}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditForm({ ...editForm, delay_seconds: parseInt(e.target.value) || 0 })}
className="flex-1 ios-input px-4 py-3 rounded-xl"
min="0"
max="3600"
placeholder="0"
/>
<span className="text-sm text-gray-500 whitespace-nowrap">秒</span>
</div>
<p className="text-xs text-gray-500 mt-1">0表示立即发货,最大3600秒(1小时)</p>
</div>
{/* 备注信息 */}
<div>
<label className="block text-sm font-bold text-gray-700 mb-2">备注信息</label>
<textarea
value={editForm.description || ''}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditForm({ ...editForm, description: e.target.value })}
className="w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"
placeholder="可选的备注信息"
/>
</div>
{/* 启用状态 */}
<div className="flex items-center justify-between p-4 bg-gray-50 rounded-xl">
<span className="font-bold text-gray-900">启用状态</span>
<button
type="button"
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setEditForm({ ...editForm, enabled: !editForm.enabled })}
className={`w-14 h-8 rounded-full transition-colors duration-300 relative ${
editForm.enabled ? 'bg-brand' : 'bg-gray-300'
}`}
>
<span
className={`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${
editForm.enabled ? 'translate-x-7' : 'translate-x-1'
}`}
/>
</button>
</div>
</div>
</div>
<div className="modal-footer">
<div className="flex gap-3 w-full">
<button
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setShowEditModal(false)}
className="flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors"
>
取消
</button>
<button
onClick={handleSaveEdit}
className="flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2"
>
<Save className="w-4 h-4" />
保存更改
</button>
</div>
</div>
</div>
</div>,
document.body
)}
{/* 添加新卡密弹窗 - 使用 Portal */}
{showAddModal && createPortal(
<div className="modal-overlay-centered">
<div className="modal-container" style={{maxWidth: '780px'}}>
<div className="modal-header flex items-center justify-between gap-4">
<div>
<h3 className="text-2xl font-extrabold text-gray-900">添加新卡密</h3>
<p className="text-sm text-gray-500 mt-1">选择交付方式并录入自动发货内容</p>
</div>
<button
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setShowAddModal(false)}
className="p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0"
title="关闭"
>
<X className="w-5 h-5 text-gray-500" />
</button>
</div>
<div className="modal-body">
<div className="space-y-6">
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700 mb-2">卡密名称</label>
<input
type="text"
value={addForm.name}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setAddForm({ ...addForm, name: e.target.value })}
placeholder="例如:VIP会员卡密"
className="w-full ios-input px-4 py-3 rounded-xl"
/>
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700 mb-2">类型</label>
<div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
<button
type="button"
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setAddForm({ ...addForm, type: 'data', content: '' })}
className={`p-3 rounded-xl font-bold transition-all ${addForm.type === 'data' ? 'bg-brand text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}
>
<CreditCard className="w-5 h-5 mx-auto mb-1" />
批量库存
</button>
<button
type="button"
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setAddForm({ ...addForm, type: 'text', content: '' })}
className={`p-3 rounded-xl font-bold transition-all ${addForm.type === 'text' ? 'bg-brand text-white' : 'bg-gray-100 text-gray-600'}`}
>
<FileText className="w-5 h-5 mx-auto mb-1" />
文本
</button>
<button
type="button"
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setAddForm({ ...addForm, type: 'image', content: '' })}
className={`p-3 rounded-xl font-bold transition-all ${addForm.type === 'image' ? 'bg-brand text-white' : 'bg-gray-100 text-gray-600'}`}
>
<ImageIcon className="w-5 h-5 mx-auto mb-1" />
图片
</button>
</div>
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700 mb-2">
{addForm.type === 'data' ? '库存内容(一行一个)' : addForm.type === 'text' ? '固定回复内容' : addForm.type === 'image' ? '图片 URL' : 'API 地址'}
</label>
{addForm.type === 'api' ? (
<input
type="url"
value={addForm.content}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setAddForm({ ...addForm, content: e.target.value })}
placeholder="https://api.example.com/get-code"
className="w-full ios-input px-4 py-3 rounded-xl"
/>
) : addForm.type === 'image' ? (
<input
type="url"
value={addForm.content}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setAddForm({ ...addForm, content: e.target.value })}
className="w-full ios-input px-4 py-3 rounded-xl"
placeholder="https://example.com/card.png"
/>
) : (
<textarea
value={addForm.content}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setAddForm({ ...addForm, content: e.target.value })}
className={`w-full ios-input px-4 py-3 rounded-xl resize-none text-sm ${addForm.type === 'data' ? 'h-48 font-mono' : 'h-32'}`}
placeholder={addForm.type === 'data' ? 'CODE-123456\nCODE-789012\n...' : '请输入每次发货时发送的固定文字'}
/>
)}
{addForm.type === 'data' && (
<p className="text-xs text-gray-500">当前库存:<span className="font-bold text-brand">{addForm.content.split('\n').filter(/* 当前回调处理集合中的单个元素。 */ line => line.trim()).length}</span> 条</p>
)}
</div>
{addForm.type === 'api' && (
<div className="border-t border-gray-100 pt-5 space-y-4">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">请求方法</label>
<select value={addForm.api_method} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setAddForm({...addForm, api_method: e.target.value as 'GET' | 'POST'})} className="w-full ios-input px-4 py-3 rounded-xl">
<option value="GET">GET</option>
<option value="POST">POST</option>
</select>
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">超时时间(秒)</label>
<input type="number" min="1" max="60" value={addForm.api_timeout} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setAddForm({...addForm, api_timeout: parseInt(e.target.value) || 10})} className="w-full ios-input px-4 py-3 rounded-xl" />
</div>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">请求头(JSON)</label>
<textarea value={addForm.api_headers} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setAddForm({...addForm, api_headers: e.target.value})} className="w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs" placeholder='{"Authorization":"Bearer token"}' />
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">请求参数(JSON)</label>
<textarea value={addForm.api_params} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setAddForm({...addForm, api_params: e.target.value})} className="w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs" placeholder='{"order_id":"{order_id}"}' />
</div>
</div>
</div>
)}
<div className="grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4">
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">描述</label>
<input value={addForm.description} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setAddForm({...addForm, description: e.target.value})} placeholder="卡密用途描述(可选)" className="w-full ios-input px-4 py-3 rounded-xl" />
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">延时发货(秒)</label>
<input type="number" value={addForm.delay_seconds} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setAddForm({...addForm, delay_seconds: parseInt(e.target.value) || 0})} className="w-full ios-input px-4 py-3 rounded-xl" min="0" max="3600" />
</div>
</div>
</div>
</div>
<div className="modal-footer">
<div className="flex gap-3 w-full">
<button
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setShowAddModal(false)}
className="flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors"
>
取消
</button>
<button
onClick={handleAddCard}
className="flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2"
>
<Plus className="w-4 h-4" />
添加卡密
</button>
</div>
</div>
</div>
</div>,
document.body
)}
{/* 批量导入弹窗由 cards feature 组件负责渲染和请求边界。 */}
<BatchCardImportModal
dataCards={dataCards}
downloadCardTemplate={downloadCardTemplate}
{...batchState}
/>
</div>
);
};
export default CardList;
+1 -1
View File
@@ -1,5 +1,5 @@
import type { Dispatch, SetStateAction } from 'react';
import type { Card, CardAppendResponse, CardBatchResponse } from '../../../types';
import type { Card, CardAppendResponse, CardBatchResponse } from '../../../shared/api-contract';
// AddCardForm 描述新增卡密组弹窗中的可编辑字段。
export interface AddCardForm {
+73 -12
View File
@@ -1,12 +1,73 @@
/** Chat feature 使用的会话、消息和账号运行状态 API。 */
export {
getAccountDetails,
getAccountRuntimeStatuses,
getChatMessagePage,
getChatMessages,
getChatSessionPage,
getChatSessions,
markChatRead,
sendChatImage,
sendChatMessage,
} from '../../../services/api';
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';
/** 聊天账号选择器读取非敏感账号摘要。 */
export const getAccountDetails = async (options?: RequestControlOptions): Promise<AccountDetail[]> => get('/api/v1/accounts/details', undefined, options);
/** 聊天运行提示读取账号连接状态索引。 */
export const getAccountRuntimeStatuses = async (options?: RequestControlOptions): Promise<Record<string, { /** 当前连接状态。 */ state: NonNullable<AccountDetail['runtime_state']>; /** 状态说明。 */ message?: string; /** 是否已连接。 */ connected: boolean; /** 连续失败次数。 */ failures: number; /** 最近更新时间。 */ updated_at: string }>> => get('/api/v1/accounts/runtime-status', undefined, options);
export interface ChatSessionPage { /** sessions 表示聊天会话列表。 */ sessions: ChatSession[]; /** has_more 表示是否存在更多数据。 */ has_more: boolean; /** next_cursor 表示下一页游标。 */ next_cursor?: number }
// getChatSessionPage 分页读取聊天会话。
export const getChatSessionPage = async (accountId: string, cursor?: number, options?: RequestControlOptions, refresh = false): Promise<ChatSessionPage> => {
// result 接口响应结果,用于当前 API 处理流程。
const response = await get<unknown>('/api/v1/chat/sessions', { account_id: accountId, cursor, refresh: refresh ? 1 : undefined },
refresh ? { timeoutMs: 60_000, ...options } : options);
// result 是兼容直接分页对象和 data 包裹后的聊天会话分页。
const result = objectFrom<Partial<ChatSessionPage>>(response, ['data', 'result']) || {};
return { sessions: result.sessions || [], has_more: result.has_more === true, next_cursor: result.next_cursor };
};
// getChatSessions 读取聊天会话列表。
export const getChatSessions = async (accountId: string, options?: RequestControlOptions): Promise<ChatSession[]> =>
(await getChatSessionPage(accountId, undefined, options)).sessions;
export interface ChatMessagePage {
/** messages 表示聊天消息列表。 */ messages: ChatMessage[];
/** has_more 表示是否存在更多数据。 */ has_more: boolean;
/** next_cursor 表示下一页游标。 */ next_cursor?: number;
/** session 表示会话。 */ session?: ChatSession;
}
// getChatMessagePage 分页读取聊天消息。
export const getChatMessagePage = async (accountId: string, chatId: string, cursor?: number, beforeId?: number, options?: RequestControlOptions): Promise<ChatMessagePage> => {
// result 接口响应结果,用于当前 API 处理流程。
const response = await get<unknown>('/api/v1/chat/messages', {
account_id: accountId, chat_id: chatId, cursor, before_id: beforeId,
}, options);
// result 是兼容直接分页对象和 data 包裹后的聊天消息分页。
const result = objectFrom<Partial<ChatMessagePage>>(response, ['data', 'result']) || {};
return { messages: result.messages || [], has_more: result.has_more === true, next_cursor: result.next_cursor, session: result.session };
};
// getChatMessages 读取聊天消息列表。
export const getChatMessages = async (accountId: string, chatId: string, beforeId?: number, options?: RequestControlOptions): Promise<ChatMessage[]> =>
(await getChatMessagePage(accountId, chatId, undefined, beforeId, options)).messages;
// sendChatMessage 发送聊天文本消息。
export const sendChatMessage = async (input: {
/** account_id 表示账号标识。 */ account_id: string; /** chat_id 表示聊天标识。 */ chat_id: string; /** buyer_id 表示买家标识。 */ buyer_id: string; /** buyer_name 表示买家名称。 */ buyer_name?: string;
/** item_id 表示商品标识。 */ item_id?: string; /** item_title 表示商品标题。 */ item_title?: string; /** text 表示文本。 */ text: string;
}, options?: RequestControlOptions): Promise<{/** message 表示消息数据。 */ message: ChatMessage}> => post('/api/v1/chat/messages', input, options);
// sendChatImage 发送聊天图片消息。
export const sendChatImage = async (input: {
/** account_id 表示账号标识。 */ account_id: string; /** chat_id 表示聊天标识。 */ chat_id: string; /** buyer_id 表示买家标识。 */ buyer_id: string; /** buyer_name 表示买家名称。 */ buyer_name?: string;
/** buyer_avatar_url 表示买家头像地址。 */ buyer_avatar_url?: string; /** item_id 表示商品标识。 */ item_id?: string; /** item_title 表示商品标题。 */ item_title?: string; /** image 表示图片数据。 */ image: File;
}, options?: RequestControlOptions): Promise<{/** message 表示消息数据。 */ message: ChatMessage}> => {
// form 消息表单,用于当前 API 处理流程。
const form = new FormData();
Object.entries(input).forEach(/* 当前回调用于处理集合元素或接口响应。 */ ([key, value]) => form.append(key, value));
return postForm('/api/v1/chat/images', form, { timeoutMs: 120_000, ...options });
};
// markChatRead 标记聊天消息已读。
export const markChatRead = async (accountId: string, chatId: string, options?: RequestControlOptions): Promise<OperationResponse> =>
post('/api/v1/chat/read', { account_id: accountId, chat_id: chatId }, options);
+40 -1
View File
@@ -1,7 +1,7 @@
// @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 '../../../types';
import type { AccountDetail, ChatMessage, ChatSession } from '../../../shared/api-contract';
import { getAccountDetails, getAccountRuntimeStatuses, getChatMessagePage, getChatSessionPage, markChatRead, sendChatImage, sendChatMessage } from './api';
import { useChat } from './hooks';
@@ -429,4 +429,43 @@ describe('useChat', /* 当前回调处理聊天加载、分页、发送和实时
expect(latestSocket?.close).toHaveBeenCalled();
hook.unmount();
});
test('切换或清空会话时取消未完成的历史消息分页', /* 当前回调验证历史分页不会在会话上下文失效后写入新会话状态。 */ async () => {
// historySignal 保存历史分页接口收到的取消信号。
let historySignal: AbortSignal | undefined;
// hook 是已加载默认账号和会话的聊天 Hook。
const hook = renderHook(
// chatHookFactory 创建聊天 Hook。
() => useChat(),
);
await waitFor(
// activeChatAssertion 等待默认会话成为当前选择。
() => expect(hook.result.current.activeChatID).toBe('chat-1'),
);
await waitFor(
// messagesLoadedAssertion 等待首次消息分页完成并允许继续加载历史消息。
() => expect(hook.result.current.messagesLoading).toBe(false),
);
getMessagePageMock.mockImplementationOnce(
// pendingHistory 保持历史分页未完成,以便验证会话切换时主动取消。
(_accountID, _chatID, _cursor, _oldestID, requestOptions) => {
historySignal = requestOptions?.signal;
return new Promise(/* pendingHistoryExecutor 故意不完成历史分页 Promise,直到会话切换取消请求。 */ () => undefined);
},
);
await act(
// olderMessagesAction 触发需要保持未完成的历史消息分页。
() => { void hook.result.current.loadOlderMessages(); },
);
await waitFor(
// historyStartedAssertion 等待历史分页请求建立取消信号。
() => expect(historySignal).toBeDefined(),
);
await act(
// clearChatAction 清空当前会话,使历史分页上下文立即失效。
() => hook.result.current.setActiveChatID(''),
);
expect(historySignal?.aborted).toBe(true);
hook.unmount();
});
});
+29 -5
View File
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import type React from 'react';
import type { AccountDetail, ChatMessage, ChatSession } from '../../../types';
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 { filterChatSessions, formatClock, isChatAbortError, isCurrentChatRequest, mergeLiveMessage, mergeOlderMessages, messageTime } from './state';
@@ -128,6 +128,10 @@ export const useChat = (): UseChatResult => {
const messageSequence = useRef(0);
// messageController 保存当前消息请求控制器。
const messageController = useRef<AbortController | null>(null);
// olderSequence 隔离同一会话中被关闭、切换或替换的历史消息分页请求。
const olderSequence = useRef(0);
// olderController 保存当前历史消息分页请求,切换会话或卸载时必须由本 Hook 取消。
const olderController = useRef<AbortController | null>(null);
// contactSequence 隔离联系人分页产生的旧响应。
const contactSequence = useRef(0);
// contactController 保存当前联系人分页控制器。
@@ -252,6 +256,11 @@ export const useChat = (): UseChatResult => {
useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => {
if (!activeAccountID || !activeChatID) {
// 无有效会话时也推进消息与历史分页代次,避免晚到响应恢复已清空的消息列表。
messageSequence.current += 1;
olderSequence.current += 1;
olderController.current?.abort();
skipNextMessageScrollRef.current = false;
setMessages([]);
return;
}
@@ -290,9 +299,18 @@ export const useChat = (): UseChatResult => {
sendSequence.current += 1;
}, [activeAccountID, activeChatID]);
useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => {
// 会话切换时取消历史分页;新的消息加载拥有独立控制器,不能复用这个低优先级请求。
olderSequence.current += 1;
olderController.current?.abort();
skipNextMessageScrollRef.current = false;
}, [activeAccountID, activeChatID]);
useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => /* 当前回调同步 React 副作用和资源生命周期。 */ () => {
sessionController.current?.abort();
messageController.current?.abort();
olderSequence.current += 1;
olderController.current?.abort();
contactController.current?.abort();
sendController.current?.abort();
}, []);
@@ -306,8 +324,12 @@ export const useChat = (): UseChatResult => {
const previousHeight = container?.scrollHeight || 0;
// sequence 请求序号。
const sequence = messageSequence.current;
// controller 请求取消控制器。
// olderRequestSequence 标识本次历史分页,连续翻页、切换会话或卸载后旧分页不能写入状态。
const olderRequestSequence = ++olderSequence.current;
olderController.current?.abort();
// controller 取消当前历史消息请求。
const controller = new AbortController();
olderController.current = controller;
skipNextMessageScrollRef.current = true;
setOlderLoading(true);
setError('');
@@ -316,18 +338,20 @@ export const useChat = (): UseChatResult => {
const oldestID = messages[0]?.id;
// page 页码。
const page = await getChatMessagePage(activeAccountID, activeChatID, historyCursor, oldestID, { signal: controller.signal });
if (!isCurrentChatRequest(messageSequence.current, sequence, controller.signal)) return;
if (!isCurrentChatRequest(messageSequence.current, sequence, controller.signal) || olderRequestSequence !== olderSequence.current) return;
setMessages(/* 当前回调处理用户交互或异步状态变化。 */ current => mergeOlderMessages(current, page.messages));
setHasOlder(page.has_more);
setHistoryCursor(page.next_cursor);
requestAnimationFrame(/* 当前回调处理用户交互或异步状态变化。 */ () => {
if (container) container.scrollTop += container.scrollHeight - previousHeight;
if (olderRequestSequence === olderSequence.current && !controller.signal.aborted && container) {
container.scrollTop += container.scrollHeight - previousHeight;
}
});
} catch (/* loadError 表示加载错误。 */ loadError) {
skipNextMessageScrollRef.current = false;
if (!isChatAbortError(loadError)) setError(loadError instanceof Error ? loadError.message : '加载历史消息失败');
} finally {
setOlderLoading(false);
if (olderRequestSequence === olderSequence.current) setOlderLoading(false);
}
}, [activeAccountID, activeChatID, hasOlder, historyCursor, messages, olderLoading]);
+214
View File
@@ -0,0 +1,214 @@
import React from 'react';
import {
AlertCircle, Check, CheckCheck, ImagePlus, Loader2, MessageCircleMore, RefreshCw,
Search, Send, Smile, UserRound, Wifi, WifiOff,
} from 'lucide-react';
import { useChat } from '../hooks';
// Chat 展示实时会话、消息分页和消息发送界面。
const Chat: React.FC = () => {
// chatState 是 Chat feature Hook 提供的状态、引用和交互动作。
const {
accounts, activeAccountID, activeChatID, activeAccount, selectedSession, filteredSessions,
messages, search, unreadOnly, draft, loading, messagesLoading, olderLoading, hasOlder, contactsLoading,
hasMoreContacts, emojiOpen, sending, error, liveState, scrollRef, imageInputRef, setActiveAccountID,
setActiveChatID, setSearch, setUnreadOnly, setDraft, setEmojiOpen, reloadSessions, loadMoreContacts,
loadOlderMessages, handleMessageScroll, handleSend, handleImage, retrySend, retryAvailable,
unreadForAccount, emojiURL, xianyuEmojis, renderXianyuText, formatClock, messageTime,
} = useChat();
if (loading) return <div className="flex h-[calc(100vh-4rem)] items-center justify-center"><Loader2 className="h-8 w-8 animate-spin text-sky-500" /></div>;
return (
<section className="flex h-[calc(100vh-4rem)] min-h-[560px] flex-col overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-chat">
<header className="border-b border-slate-200 bg-slate-50/70 px-5 pt-4">
<div className="mb-3 flex items-center justify-between gap-4">
<div>
<h2 className="text-xl font-black tracking-tight text-slate-950">在线聊天</h2>
<p className="mt-0.5 text-xs font-medium text-slate-500">复用账号实时连接,消息按账号完全隔离</p>
</div>
<div className={`flex items-center gap-2 rounded-full px-3 py-1.5 text-xs font-bold ${liveState === 'online' ? 'bg-emerald-50 text-emerald-700' : liveState === 'connecting' ? 'bg-amber-50 text-amber-700' : 'bg-red-50 text-red-700'}`}>
{liveState === 'online' ? <Wifi className="h-3.5 w-3.5" /> : <WifiOff className="h-3.5 w-3.5" />}
{liveState === 'online' ? '实时同步中' : liveState === 'connecting' ? '正在连接' : '连接已断开'}
</div>
</div>
<div className="flex gap-1 overflow-x-auto pb-0" role="tablist" aria-label="聊天账号">
{accounts.map(/* 当前回调处理集合中的单个元素。 */ account => {
// active 当前状态。
const active = account.id === activeAccountID;
// unread unread,负责当前功能中的对应处理。
const unread = unreadForAccount(account.id);
// online 响应当前用户操作(line)。
const online = account.runtime_state === 'online';
return (
<button key={account.id} type="button" role="tab" aria-selected={active} onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setActiveAccountID(account.id)}
className={`relative flex h-11 shrink-0 items-center gap-2 border-b-2 px-3 text-sm font-extrabold transition-colors ${active ? 'border-sky-500 text-sky-700' : 'border-transparent text-slate-500 hover:text-slate-900'}`}>
<span className={`h-2 w-2 rounded-full ${online ? 'bg-emerald-500' : 'bg-slate-300'}`} />
<span className="max-w-36 truncate">{account.nickname || account.remark || account.id}</span>
{unread > 0 && <span className="min-w-5 rounded-full bg-red-500 px-1.5 py-0.5 text-[10px] text-white">{unread > 99 ? '99+' : unread}</span>}
</button>
);
})}
</div>
</header>
{accounts.length === 0 ? (
<div className="flex flex-1 flex-col items-center justify-center text-center">
<MessageCircleMore className="h-12 w-12 text-slate-300" />
<h3 className="mt-4 font-black text-slate-800">暂无启用账号</h3>
<p className="mt-1 text-sm text-slate-500">先在账号管理中启用账号,聊天会话会自动出现。</p>
</div>
) : (
<div className="grid min-h-0 flex-1 overflow-hidden grid-cols-[320px_minmax(0,1fr)]">
<aside className="flex min-h-0 flex-col border-r border-slate-200 bg-slate-50/40">
<div className="space-y-3 border-b border-slate-200 p-3">
<div className="relative">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
<input value={search} onChange={/* 当前回调处理用户交互或异步状态变化。 */ event => setSearch(event.target.value)} placeholder="搜索用户、商品或消息"
className="h-10 w-full rounded-xl border border-slate-200 bg-white pl-9 pr-3 text-sm outline-none transition focus:border-sky-400 focus:ring-2 focus:ring-sky-100" />
</div>
<div className="flex items-center justify-between">
<button type="button" onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setUnreadOnly(/* 当前回调处理用户交互或异步状态变化。 */ value => !value)}
className={`rounded-lg px-2.5 py-1.5 text-xs font-bold ${unreadOnly ? 'bg-sky-100 text-sky-700' : 'text-slate-500 hover:bg-slate-100'}`}>
{unreadOnly ? '只看未读' : '全部会话'}
</button>
<button type="button" title="刷新会话" onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void reloadSessions(activeAccountID)} className="rounded-lg p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700">
<RefreshCw className="h-4 w-4" />
</button>
</div>
</div>
<div className="min-h-0 flex-1 overflow-y-auto">
{filteredSessions.map(/* 当前回调处理集合中的单个元素。 */ session => (
<button key={session.chat_id} type="button" onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setActiveChatID(session.chat_id)}
className={`flex w-full gap-3 border-b border-slate-100 p-4 text-left transition-colors ${session.chat_id === activeChatID ? 'bg-white shadow-chat-active' : 'hover:bg-white/80'}`}>
<div className="flex h-10 w-10 shrink-0 items-center justify-center overflow-hidden rounded-full bg-slate-200 text-slate-500">
{session.buyer_avatar_url ? <img src={session.buyer_avatar_url} alt="" className="h-full w-full object-cover" /> : <UserRound className="h-5 w-5" />}
</div>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="truncate text-sm font-extrabold text-slate-900">{session.buyer_name || `用户 ${session.buyer_id}`}</span>
<span className="ml-auto shrink-0 text-[10px] font-medium text-slate-400">{formatClock(session.last_message_at)}</span>
</div>
<div className="mt-1 flex items-center gap-2">
<span className="truncate text-xs text-slate-500">{session.last_message || '暂无消息'}</span>
{session.unread_count > 0 && <span className="ml-auto min-w-5 shrink-0 rounded-full bg-red-500 px-1.5 py-0.5 text-center text-[10px] font-bold text-white">{session.unread_count}</span>}
</div>
{session.item_title && <div className="mt-1.5 truncate text-[10px] font-medium text-sky-700">商品 · {session.item_title}</div>}
</div>
</button>
))}
{filteredSessions.length === 0 && <div className="px-6 py-16 text-center text-sm text-slate-400">当前账号暂无匹配会话</div>}
{hasMoreContacts && !search && !unreadOnly && <div className="flex justify-center p-4">
<button type="button" onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void loadMoreContacts()} disabled={contactsLoading}
className="flex items-center gap-2 rounded-full border border-slate-200 bg-white px-4 py-2 text-xs font-bold text-slate-500 shadow-sm hover:border-sky-200 hover:text-sky-600 disabled:opacity-50">
{contactsLoading && <Loader2 className="h-3.5 w-3.5 animate-spin" />}{contactsLoading ? '正在加载' : '加载更多历史联系人'}
</button>
</div>}
</div>
</aside>
<main className="flex min-h-0 min-w-0 flex-col overflow-hidden bg-surface-subtle">
{selectedSession ? (
<>
<div className="flex h-16 shrink-0 items-center border-b border-slate-200 bg-white px-5">
<div className="min-w-0">
<div className="truncate text-sm font-black text-slate-950">{selectedSession.buyer_name || selectedSession.buyer_id}</div>
<div className="mt-0.5 truncate text-xs text-slate-500">用户 ID:{selectedSession.buyer_id}</div>
</div>
<span className={`ml-auto rounded-full px-2.5 py-1 text-[10px] font-bold ${activeAccount?.runtime_state === 'online' ? 'bg-emerald-50 text-emerald-700' : 'bg-slate-100 text-slate-500'}`}>
{activeAccount?.runtime_state === 'online' ? '账号在线' : '账号离线'}
</span>
</div>
<div ref={scrollRef} onScroll={handleMessageScroll} className="min-h-0 flex-1 space-y-5 overflow-y-auto px-6 py-5">
{messagesLoading ? <div className="flex justify-center py-12"><Loader2 className="h-6 w-6 animate-spin text-sky-500" /></div> : <>
{hasOlder && <div className="flex justify-center pb-1">
<button type="button" onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void loadOlderMessages()} disabled={olderLoading}
className="flex items-center gap-2 rounded-full border border-slate-200 bg-white px-4 py-1.5 text-xs font-bold text-slate-500 shadow-sm transition hover:border-sky-200 hover:text-sky-600 disabled:opacity-50">
{olderLoading && <Loader2 className="h-3.5 w-3.5 animate-spin" />}{olderLoading ? '正在加载' : '加载更早消息'}
</button>
</div>}
{messages.map(/* 当前回调处理集合中的单个元素。 */ message => {
// outgoing 是否为发送方消息。
const outgoing = message.direction === 'outgoing';
// system 系统。
const system = message.message_type === 'system';
if (system) {
return (
<div key={message.message_key} className="flex justify-center py-1">
<div className="max-w-[82%] rounded-xl border border-slate-200 bg-slate-100 px-4 py-2 text-center text-xs leading-5 text-slate-500">
{renderXianyuText(message.content)}
<div className="mt-1 text-[10px] text-slate-400">{messageTime(message.sent_at)}</div>
</div>
</div>
);
}
return (
<div key={message.message_key} className={`flex items-end gap-2.5 ${outgoing ? 'justify-end' : 'justify-start'}`}>
{!outgoing && <div className="h-9 w-9 shrink-0 overflow-hidden rounded-full bg-slate-200 ring-2 ring-white">
{selectedSession.buyer_avatar_url ? <img src={selectedSession.buyer_avatar_url} alt={selectedSession.buyer_name || '用户'} className="h-full w-full object-cover" /> : <UserRound className="m-2 h-5 w-5 text-slate-500" />}
</div>}
<div className={`max-w-[72%] ${outgoing ? 'items-end' : 'items-start'} flex flex-col`}>
<div className="mb-1 px-1 text-[10px] font-semibold text-slate-400">{outgoing ? (activeAccount?.nickname || activeAccount?.remark || '我') : (selectedSession.buyer_name || message.sender_name || selectedSession.buyer_id)}</div>
{message.message_type === 'image' ? (
<a href={message.content} target="_blank" rel="noreferrer" className={`block overflow-hidden rounded-2xl border bg-white p-1 shadow-sm ${outgoing ? 'rounded-br-md border-sky-200' : 'rounded-bl-md border-slate-200'}`}>
<img src={message.content} alt="聊天图片" className="max-h-80 max-w-full rounded-xl object-contain" />
</a>
) : message.message_type === 'video' ? (
<video src={message.content} controls preload="metadata" className="max-h-80 max-w-full rounded-2xl bg-black" />
) : (
<div className={`rounded-2xl px-4 py-2.5 text-sm leading-6 shadow-sm ${outgoing ? 'rounded-br-md bg-sky-500 text-white' : 'rounded-bl-md border border-slate-200 bg-white text-slate-800'}`}>{renderXianyuText(message.content)}</div>
)}
<div className="mt-1 flex items-center gap-1 text-[10px] text-slate-400">
{messageTime(message.sent_at)}
{outgoing && (message.status === 'failed' ? <AlertCircle className="h-3 w-3 text-red-500" /> : message.status === 'sent' ? <CheckCheck className="h-3 w-3 text-sky-500" /> : <Check className="h-3 w-3" />)}
</div>
</div>
{outgoing && <div className="h-9 w-9 shrink-0 overflow-hidden rounded-full bg-sky-100 ring-2 ring-white">
{activeAccount?.avatar_url ? <img src={activeAccount.avatar_url} alt="我" className="h-full w-full object-cover" /> : <UserRound className="m-2 h-5 w-5 text-sky-600" />}
</div>}
</div>
);
})}
</>}
</div>
{error && <div className="flex items-center justify-between gap-3 border-t border-red-100 bg-red-50 px-5 py-2 text-xs font-medium text-red-700"><span>{error}</span>{retryAvailable && <button type="button" className="font-bold underline" onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void retrySend()}>重试发送</button>}</div>}
<div className="relative z-10 shrink-0 border-t border-slate-200 bg-white p-4 shadow-chat-input">
<div className="mb-2 flex items-center gap-1">
<div className="relative">
<button type="button" onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setEmojiOpen(/* 当前回调处理用户交互或异步状态变化。 */ value => !value)} disabled={sending || activeAccount?.runtime_state !== 'online'} className="rounded-lg p-2 text-slate-500 hover:bg-sky-50 hover:text-sky-600 disabled:opacity-40" title="闲鱼表情"><Smile className="h-5 w-5" /></button>
{emojiOpen && <div className="absolute bottom-11 left-0 z-30 w-[360px] rounded-2xl border border-slate-200 bg-white p-3 shadow-2xl">
<div className="mb-2 text-xs font-bold text-slate-500">全部表情</div>
<div className="grid max-h-72 grid-cols-8 gap-1 overflow-y-auto">
{xianyuEmojis.map(/* 当前回调处理集合中的单个元素。 */ ([name, file]) => <button key={name} type="button" title={`[${name}]`} onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => { setDraft(/* 当前回调处理用户交互或异步状态变化。 */ value => value + `[${name}]`); setEmojiOpen(false); }} className="flex h-10 w-10 items-center justify-center rounded-lg hover:bg-slate-100"><img src={emojiURL(file)} alt={`[${name}]`} className="h-8 w-8 object-contain" /></button>)}
</div>
</div>}
</div>
<input ref={imageInputRef} type="file" accept="image/*" className="hidden" onChange={/* 当前回调处理用户交互或异步状态变化。 */ event => void handleImage(event.target.files?.[0])} />
<button type="button" onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => imageInputRef.current?.click()} disabled={sending || activeAccount?.runtime_state !== 'online'} className="rounded-lg p-2 text-slate-500 transition hover:bg-sky-50 hover:text-sky-600 disabled:opacity-40" title="发送图片(最大 10MB)"><ImagePlus className="h-5 w-5" /></button>
</div>
<div className="flex items-end gap-3 rounded-2xl border border-slate-200 bg-slate-50 p-2 transition focus-within:border-sky-400 focus-within:ring-2 focus-within:ring-sky-100">
<textarea value={draft} onChange={/* 当前回调处理用户交互或异步状态变化。 */ event => setDraft(event.target.value)} rows={2} maxLength={2000}
onKeyDown={/* 当前回调处理用户交互或异步状态变化。 */ event => { if (event.key === 'Enter' && !event.shiftKey) { event.preventDefault(); void handleSend(); } }}
disabled={activeAccount?.runtime_state !== 'online'} placeholder={activeAccount?.runtime_state === 'online' ? '输入消息,Enter 发送,Shift + Enter 换行' : '账号离线,暂时无法发送'}
className="max-h-32 min-h-12 flex-1 resize-none bg-transparent px-2 py-2 text-sm leading-6 outline-none disabled:cursor-not-allowed" />
<button type="button" onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void handleSend()} disabled={!draft.trim() || sending || activeAccount?.runtime_state !== 'online'} className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-sky-500 text-white shadow-md shadow-sky-100 transition hover:bg-sky-600 disabled:cursor-not-allowed disabled:bg-slate-300 disabled:shadow-none" aria-label="发送消息">
{sending ? <Loader2 className="h-4 w-4 animate-spin" /> : <Send className="h-4 w-4" />}
</button>
</div>
</div>
</>
) : (
<div className="flex flex-1 flex-col items-center justify-center text-center">
<MessageCircleMore className="h-12 w-12 text-slate-300" />
<h3 className="mt-4 font-black text-slate-700">选择一个用户开始聊天</h3>
<p className="mt-1 text-sm text-slate-400">该账号的新消息会实时出现在左侧列表。</p>
</div>
)}
</main>
</div>
)}
</section>
);
};
export default Chat;
+1 -1
View File
@@ -1,5 +1,5 @@
import { expect, test } from 'vitest';
import type { ChatMessage, ChatSession } from '../../../types';
import type { ChatMessage, ChatSession } from '../../../shared/api-contract';
import { filterChatSessions, formatClock, isChatAbortError, isCurrentChatRequest, mergeLiveMessage, mergeOlderMessages, messageTime } from './state';
// sessionFixture 是覆盖搜索、未读筛选和联系人隔离的最小会话数据。
+1 -1
View File
@@ -1,4 +1,4 @@
import type { ChatMessage, ChatSession } from '../../../types';
import type { ChatMessage, ChatSession } from '../../../shared/api-contract';
/** 按搜索条件筛选会话列表。 */
export const filterChatSessions = (sessions: ChatSession[], search: string, unreadOnly: boolean): ChatSession[] => {
+1 -1
View File
@@ -1,4 +1,4 @@
import type { AccountDetail, ChatMessage, ChatSession } from '../../../types';
import type { AccountDetail, ChatMessage, ChatSession } from '../../../shared/api-contract';
/** 按账号保存会话列表。 */
export type SessionsByAccount = Record<string, ChatSession[]>;
+64 -2
View File
@@ -1,2 +1,64 @@
/** Dashboard 数据接口集中导出,避免页面组件直接依赖通用 API 模块。 */
export { getDashboardStats, getItems, getOrderAnalytics, getValidOrders } from '../../../services/api';
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';
/** 仪表盘订单明细接口转换后的分页结果。 */
export interface ValidOrdersResult {
/** 当前时间范围的订单明细。 */
orders: Order[];
/** 服务端匹配到的订单总数。 */
total: number;
/** 是否存在未返回的后续订单。 */
truncated: boolean;
}
/** 将服务端订单状态映射为仪表盘可稳定展示的状态集合。 */
const normalizeOrderStatus = (value: unknown): OrderStatus => {
// status 是服务端返回的原始或历史订单状态。
const status = String(value || '');
if (status === 'paid') return 'pending_ship';
return ['processing', 'pending_ship', 'shipped', 'completed', 'cancelled', 'refunding'].includes(status) ? status as OrderStatus : 'unknown';
};
/** 读取仪表盘概览统计。 */
export const getDashboardStats = async (options?: RequestControlOptions): Promise<DashboardStatsResponse> => get('/api/v1/analytics/dashboard', undefined, options);
/** 读取仪表盘商品索引,兼容历史 items 包装。 */
export const getItems = async (accountID?: string, options?: RequestControlOptions): Promise<Item[]> => {
// response 是商品列表的原始 transport 响应。
const response = await get<Item[] | ItemListEnvelope>('/api/v1/items', accountID ? { cookie_id: accountID } : undefined, options);
// items 是从直接数组或历史包装中取出的商品集合。
const items = collectionFrom<Item>(response, ['items', 'data', 'results']);
return items.map(/* item 是当前需要兼容布尔标记的商品传输记录。 */ item => ({ ...item, id: item.id || `${item.cookie_id}-${item.item_id}`, is_multi_spec: item.is_multi_spec === true || item.is_multi_spec === 1, multi_quantity_delivery: item.multi_quantity_delivery === true || item.multi_quantity_delivery === 1 }));
};
/** 读取指定自然日范围的订单统计,并显式传递浏览器时区偏移。 */
export const getOrderAnalytics = async (range: number | { /** 统计起始日期。 */ start_date: string; /** 统计结束日期。 */ end_date: string } = 7, options?: RequestControlOptions): Promise<OrderAnalyticsResponse> => {
// dateRange 是标准化后的统计日期范围。
let dateRange: { /** 统计起始日期。 */ start_date: string; /** 统计结束日期。 */ end_date: string };
if (typeof range === 'number') {
// endDate 是计算默认区间使用的当前本地日期。
const endDate = new Date();
// startDate 是向前回溯指定天数后的本地日期。
const startDate = new Date();
startDate.setDate(startDate.getDate() - range);
dateRange = { start_date: formatLocalDate(startDate), end_date: formatLocalDate(endDate) };
} else {
dateRange = range;
}
return get('/api/v1/analytics/orders', { ...dateRange, timezone_offset_minutes: -new Date().getTimezoneOffset() }, options);
};
/** 读取可参与仪表盘统计的订单并适配历史响应形状。 */
export const getValidOrders = async (dateRange: { /** 统计起始日期。 */ start_date: string; /** 统计结束日期。 */ end_date: string }, options?: RequestControlOptions): Promise<ValidOrdersResult> => {
// response 是有效订单接口的未知兼容响应。
const response = await get<unknown>('/api/v1/analytics/orders/valid', { ...dateRange, timezone_offset_minutes: -new Date().getTimezoneOffset() }, options);
// page 是移除历史 transport 包装后的分页元数据。
const page = objectFrom<Partial<ValidOrdersResponse>>(response, ['data', 'result']) || {};
// rows 是直接数组或历史 orders 包装中的原始订单。
const rows = collectionFrom<ValidOrderResponse>(response, ['orders', 'data', 'items']);
// orders 是转换状态、数量和稳定标识后的仪表盘订单模型。
const orders = rows.map(/* row 是当前需要归一化状态与数量的有效订单 DTO。 */ row => ({ ...row, id: row.order_id, status: normalizeOrderStatus(row.status || row.order_status), order_status: normalizeOrderStatus(row.order_status), quantity: Number(row.quantity || 1) }));
return { orders, total: Number(page.total ?? orders.length), truncated: page.truncated === true };
};
+30 -1
View File
@@ -1,7 +1,7 @@
// @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 '../../../types';
import type { DashboardStats, Item, OrderAnalyticsResponse } from '../../../shared/api-contract';
import { getDashboardStats, getItems, getOrderAnalytics, getValidOrders } from './api';
import { useDashboard } from './hooks';
import type { UseDashboardOptions } from './hooks';
@@ -142,4 +142,33 @@ describe('useDashboard', /* 当前回调处理仪表盘并行请求和派生数
expect(hook.result.current.status.range).toBe('success');
hook.unmount();
});
test('刷新期间丢弃忽略取消信号的旧概览响应', /* 当前回调验证概览请求即使底层实现没有响应取消,也不能覆盖刷新后的统计数据。 */ async () => {
// resolveFirstStats 是首次概览统计请求的完成控制器。
let resolveFirstStats: (value: DashboardStats) => void = () => undefined;
// firstStatsRequest 是故意忽略 AbortSignal 的旧统计请求。
const firstStatsRequest = new Promise<DashboardStats>(/* firstStatsExecutor 保存旧统计请求的完成函数。 */ resolve => { resolveFirstStats = resolve; });
// refreshedStats 是刷新后应保留在页面中的权威概览数据。
const refreshedStats = { ...statsFixture, total_orders: 99 };
getStatsMock.mockReset();
getStatsMock.mockReturnValueOnce(firstStatsRequest);
getStatsMock.mockResolvedValueOnce(refreshedStats);
// hook 是概览刷新竞态场景的 Hook 渲染结果。
const hook = renderHook(renderDashboardHook);
await act(
// refreshAction 发起第二次概览加载并使首个请求过期。
() => hook.result.current.refresh(),
);
await waitFor(
// refreshedOverviewAssertion 等待新概览统计写入页面状态。
() => expect(hook.result.current.data?.stats).toEqual(refreshedStats),
);
resolveFirstStats(statsFixture);
await act(
// staleOverviewResolveAction 完成被取消但仍返回的旧统计请求。
async () => { await firstStatsRequest; },
);
expect(hook.result.current.data?.stats).toEqual(refreshedStats);
hook.unmount();
});
});
+6 -2
View File
@@ -42,6 +42,8 @@ export const useDashboard = (options: UseDashboardOptions): UseDashboardResult =
const [refreshKey, setRefreshKey] = useState(0);
// requestSequence 请求请求序号,负责当前功能中的对应处理。
const requestSequence = useRef(0);
// overviewSequence 隔离刷新后仍然完成的旧概览响应,避免忽略取消信号的底层实现覆盖新数据。
const overviewSequence = useRef(0);
// rangeSelection 范围选择,负责当前功能中的对应处理。
const rangeSelection = useMemo(
// selection 是当前时间范围的不可变快照。
@@ -57,6 +59,8 @@ export const useDashboard = (options: UseDashboardOptions): UseDashboardResult =
);
useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => {
// sequence 标识本轮概览请求,刷新或卸载后旧请求不得写入状态。
const sequence = ++overviewSequence.current;
// controller 请求取消控制器。
const controller = new AbortController();
setStatus(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, overview: 'loading', error: '' }));
@@ -64,11 +68,11 @@ export const useDashboard = (options: UseDashboardOptions): UseDashboardResult =
getDashboardStats({ signal: controller.signal }),
getItems(undefined, { signal: controller.signal }),
]).then(/* 当前回调处理用户交互或异步状态变化。 */ ([stats, items]) => {
if (controller.signal.aborted) return;
if (!isCurrentDashboardRequest(overviewSequence.current, sequence, controller.signal)) return;
setOverview({ stats, items, itemNames: buildItemNameMap(items) });
setStatus(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, overview: 'success' }));
}).catch(/* 当前回调处理用户交互或异步状态变化。 */ error => {
if (controller.signal.aborted || isAbortError(error)) return;
if (!isCurrentDashboardRequest(overviewSequence.current, sequence, controller.signal) || isAbortError(error)) return;
setStatus(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, overview: 'error', error: errorMessage(error, '概览加载失败') }));
});
return /* 当前回调处理用户交互或异步状态变化。 */ () => controller.abort();
@@ -0,0 +1,48 @@
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 { StatusBadge } from './Dashboard';
// dashboardSource 仪表盘测试数据源。
const dashboardSource = readFileSync(resolve(__dirname, 'Dashboard.tsx'), 'utf8');
// trendChartSource 趋势图测试数据源。
const trendChartSource = readFileSync(resolve(__dirname, '../DashboardTrendChart.tsx'), 'utf8');
// globalStyles 测试用全局样式。
const globalStyles = readFileSync(resolve(__dirname, '../../../../index.css'), 'utf8');
describe('Dashboard presentation safeguards', /* 当前回调处理用户交互或异步状态变化。 */ () => {
test('keeps order status badges on one line', /* 当前回调处理用户交互或异步状态变化。 */ () => {
// html 渲染后的 HTML。
const html = renderToStaticMarkup(<StatusBadge status="shipped" />);
expect(html).toContain('已发货');
expect(html).toContain('inline-flex');
expect(html).toContain('whitespace-nowrap');
expect(dashboardSource).toContain('min-w-[760px]');
});
test('pie charts use enlarged active sectors without focus rings or external label lines', /* 当前回调处理用户交互或异步状态变化。 */ () => {
expect(dashboardSource.match(/accessibilityLayer=\{false\}/g)).toHaveLength(2);
expect(dashboardSource.match(/activeShape=\{\{/g)).toHaveLength(2);
expect(dashboardSource).toContain('outerRadius: 96');
expect(dashboardSource).toContain('outerRadius: 98');
expect(dashboardSource.match(/stroke: 'none'/g)).toHaveLength(2);
expect(dashboardSource.match(/strokeWidth: 0/g)).toHaveLength(2);
expect(dashboardSource.match(/rootTabIndex=\{-1\}/g)).toHaveLength(2);
expect(dashboardSource.match(/label=\{false\}/g)).toHaveLength(2);
expect(dashboardSource.match(/labelLine=\{false\}/g)).toHaveLength(2);
expect(dashboardSource.match(/wrapperStyle=\{\{ zIndex: 30, outline: 'none' \}\}/g)).toHaveLength(2);
expect(dashboardSource.match(/absolute inset-0 z-10/g)).toHaveLength(2);
expect(globalStyles).toContain('.dashboard-pie-chart .recharts-sector:focus');
expect(trendChartSource).toContain('dashboard-revenue-chart h-[350px] w-full');
expect(trendChartSource).toContain('activeBar={false}');
expect(trendChartSource).not.toMatch(/#[0-9A-Fa-f]{3,8}/);
expect(trendChartSource).toContain("fill={cssColor('brand')}");
expect(globalStyles).toContain('.dashboard-revenue-chart .recharts-rectangle:focus');
expect(globalStyles).toContain('.dashboard-revenue-chart .recharts-curve:focus');
expect(globalStyles).toContain('.dashboard-revenue-chart [class*="recharts-zIndex-layer_"]:focus');
expect(globalStyles).toContain('stroke: none !important');
});
});
@@ -0,0 +1,527 @@
import React, { useState } from 'react';
import { OrderStatus } from '../../../../shared/api-contract';
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 { DashboardTrendChart } from '../DashboardTrendChart';
// cssColor 状态颜色样式。
const cssColor = (token: string, alpha?: number) => (
alpha === undefined
? `rgb(var(--color-${token}))`
: `rgb(var(--color-${token}) / ${alpha})`
);
// 状态徽章组件
export const StatusBadge: React.FC<{ /** status 表示状态。 */ status: OrderStatus }> = ({ status }) => {
// styles 样式表。
const styles = {
processing: 'bg-blue-100 text-blue-800',
pending_ship: 'bg-brand text-white',
shipped: 'bg-blue-100 text-blue-700',
completed: 'bg-green-100 text-green-700',
cancelled: 'bg-gray-100 text-gray-500',
refunding: 'bg-red-100 text-red-600',
unknown: 'bg-gray-100 text-gray-500',
};
// labels labels,负责当前功能中的对应处理。
const labels = {
processing: '处理中',
pending_ship: '待发货',
shipped: '已发货',
completed: '已完成',
cancelled: '已取消',
refunding: '退款中',
unknown: '未知',
};
return (
<span className={`inline-flex items-center justify-center whitespace-nowrap px-3 py-1.5 rounded-lg text-xs leading-none font-bold ${styles[status] || styles.cancelled}`}>
{labels[status] || status}
</span>
);
};
// StatCard 渲染统计卡片组件。
const StatCard: React.FC<{ /** title 表示标题。 */ title: string; /** value 表示值。 */ value: string | number; /** icon 表示icon。 */ icon: React.ElementType; /** colorClass 表示颜色Class。 */ colorClass: string; /** trend 表示趋势。 */ trend?: string }> = ({ title, value, icon: Icon, colorClass, trend }) => (
<div className="ios-card p-6 rounded-xl flex flex-col justify-between hover:translate-y-[-4px] transition-all duration-300 h-full relative overflow-hidden group border-0">
<div className={`absolute -right-6 -top-6 w-32 h-32 ${colorClass} opacity-10 rounded-full group-hover:scale-125 transition-transform duration-500 blur-2xl`}></div>
<div className="flex justify-between items-start mb-6">
<div className={`p-4 rounded-2xl ${colorClass} bg-opacity-10 backdrop-blur-sm`}>
<Icon className={`w-6 h-6 ${colorClass.replace('bg-', 'text-')}`} />
</div>
{trend && <span className="text-xs font-bold text-white bg-brand px-3 py-1.5 rounded-full flex items-center gap-1 shadow-sm">
<TrendingUp className="w-3 h-3" /> {trend}
</span>}
</div>
<div className="relative z-10">
<h3 className="text-3xl font-extrabold text-gray-900 tracking-tight font-feature-settings-tnum">{value}</h3>
<p className="text-gray-500 text-sm font-medium mt-1">{title}</p>
</div>
</div>
);
// Dashboard 渲染仪表盘页面组件。
const Dashboard: React.FC = () => {
// [timeRange, 解构得到当前 Hook 返回的状态和操作函数。
const [timeRange, setTimeRange] = useState<TimeRange>('7days');
// [customStartDate, 解构得到当前 Hook 返回的状态和操作函数。
const [customStartDate, setCustomStartDate] = useState('');
// [customEndDate, 解构得到当前 Hook 返回的状态和操作函数。
const [customEndDate, setCustomEndDate] = useState('');
// [searchTerm, 解构得到当前 Hook 返回的状态和操作函数。
const [searchTerm, setSearchTerm] = useState('');
// [customRangeVersion, 解构得到当前 Hook 返回的状态和操作函数。
const [customRangeVersion, setCustomRangeVersion] = useState(0);
// dashboard 仪表盘数据。
const dashboard = useDashboard({ range: timeRange, customStartDate, customEndDate, customRangeVersion });
// { 解构得到当前 Hook 返回的状态和操作函数。
const { data, status, chartData, productSalesData, sourceData: sourceDataData, categoryData: categoryDataData, maxProductSales, trendPercent, selectedRangeLabel, refresh } = dashboard;
// stats 统计概览数据。
const stats = data?.stats || null;
// analytics 统计分析数据。
const analytics = data?.analytics || null;
// previousAnalytics 上一份统计数据。
const previousAnalytics = data?.previousAnalytics || null;
// validOrders 有效订单列表。
const validOrders = data?.validOrders.orders || [];
// validOrdersTotal 有效数据订单列表总数,负责当前功能中的对应处理。
const validOrdersTotal = data?.validOrders.total || 0;
// validOrdersTruncated 有效数据订单列表Truncated,负责当前功能中的对应处理。
const validOrdersTruncated = data?.validOrders.truncated || false;
// ordersLoading 订单加载状态。
const ordersLoading = status.range === 'loading';
// loadError 加载当前数据(错误)。
const loadError = status.error;
// 颜色配置
const COLORS = [
cssColor('brand'),
cssColor('brand-highlight'),
cssColor('success-500'),
cssColor('warning-500'),
cssColor('accent-500'),
];
// formatCurrency 格式化金额函数。
const formatCurrency = (value: number) => `¥${Number(value || 0).toLocaleString('zh-CN', { maximumFractionDigits: 2 })}`;
if (loadError && (!stats || !analytics)) {
return (
<div className="p-8 flex flex-col items-center gap-3 text-red-600">
<AlertCircle className="w-8 h-8" />
<span>{loadError}</span>
<button type="button" className="ios-btn-primary px-4 py-2 rounded-xl" onClick={refresh}>重新加载</button>
</div>
);
}
if (!stats || !analytics) return <div className="p-8 flex justify-center text-gray-400"><Activity className="w-8 h-8 animate-spin text-brand" /></div>;
// totalOrders 总数订单列表,负责当前功能中的对应处理。
const totalOrders = analytics.revenue_stats.total_orders || 0;
// totalAmount 订单总金额。
const totalAmount = analytics.revenue_stats.total_amount || 0;
// timeRangeOptions time范围Options,负责当前功能中的对应处理。
const timeRangeOptions = [
{ key: 'today' as TimeRange, label: '今天' },
{ key: 'yesterday' as TimeRange, label: '昨天' },
{ key: '3days' as TimeRange, label: '三天内' },
{ key: '7days' as TimeRange, label: '7天内' },
{ key: '30days' as TimeRange, label: '一个月内' },
{ key: 'custom' as TimeRange, label: '自定义' },
];
// currentRangeDates 当前统计日期范围。
let currentRangeDates;
try {
currentRangeDates = getDateRange(timeRange, new Date(), customStartDate, customEndDate);
} catch {
currentRangeDates = { startDate: customStartDate, endDate: customEndDate };
}
// normalizedSearchTerm 归一化当前数据(d搜索条件Term)。
const normalizedSearchTerm = searchTerm.trim().toLowerCase();
// filteredValidOrders 过滤后的有效订单列表。
const filteredValidOrders = validOrders.filter(/* 当前回调处理集合中的单个元素。 */ (order) =>
order.order_id?.toLowerCase().includes(normalizedSearchTerm) ||
order.item_id?.toLowerCase().includes(normalizedSearchTerm) ||
order.item_title?.toLowerCase().includes(normalizedSearchTerm) ||
order.buyer_id?.toLowerCase().includes(normalizedSearchTerm)
);
return (
<div className="space-y-8 animate-fade-in">
{loadError && (
<div className="flex items-center justify-between gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm text-red-700">
<span>{loadError}</span>
<button type="button" className="font-bold underline" onClick={refresh}>重试</button>
</div>
)}
<div className="flex flex-col md:flex-row justify-between md:items-end gap-4">
<div>
<h2 className="text-4xl font-extrabold text-gray-900 tracking-tight">运营概览</h2>
<p className="text-gray-500 mt-2 text-base">欢迎回来,以下是闲鱼店铺的实时经营数据。</p>
</div>
<div className="flex items-center gap-3">
<div className="text-sm font-bold text-gray-700 bg-white px-5 py-2.5 rounded-full shadow-sm border border-gray-100 flex items-center gap-2">
<span className="w-2.5 h-2.5 bg-green-500 rounded-full animate-pulse"></span>
系统正常运行
</div>
</div>
</div>
{/* Time Range Selector */}
<div className="flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl">
{timeRangeOptions.map(/* 当前回调处理集合中的单个元素。 */ (option) => (
<button
key={option.key}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setTimeRange(option.key)}
className={`px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${
timeRange === option.key
? 'bg-brand text-white shadow-md'
: 'bg-white text-gray-600 hover:text-black hover:bg-gray-50'
}`}
>
{option.label}
</button>
))}
{timeRange === 'custom' && (
<>
<input
type="date"
value={customStartDate}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setCustomStartDate(e.target.value)}
className="px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-brand"
/>
<span className="self-center text-gray-400">-</span>
<input
type="date"
value={customEndDate}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setCustomEndDate(e.target.value)}
className="px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-brand"
/>
<button
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setCustomRangeVersion(/* 当前回调处理用户交互或异步状态变化。 */ value => value + 1)}
className="px-4 py-2 rounded-xl text-sm font-bold bg-black text-white hover:bg-gray-800 transition-colors"
>
应用
</button>
</>
)}
</div>
{/* Stats Grid */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
<StatCard
title="累计营收 (CNY)"
value={`¥${analytics.revenue_stats.total_amount.toLocaleString('zh-CN', { minimumFractionDigits: 2 })}`}
icon={DollarSign}
colorClass="bg-blue-400"
trend={trendPercent || undefined}
/>
<StatCard
title="活跃账号 / 总数"
value={`${stats.active_cookies} / ${stats.total_cookies}`}
icon={Users}
colorClass="bg-blue-500"
/>
<StatCard
title="订单数"
value={analytics.revenue_stats.total_orders.toLocaleString()}
icon={ShoppingCart}
colorClass="bg-blue-500"
/>
<StatCard
title="库存卡密余量"
value={stats.available_card_stock}
icon={Package}
colorClass="bg-purple-500"
/>
</div>
<DashboardTrendChart chartData={chartData} selectedRangeLabel={selectedRangeLabel} totalAmount={totalAmount} />
{/* 商品销量排行和订单来源分布 */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
{/* 商品销量排行 */}
<div className="ios-card p-6 rounded-xl">
<h3 className="font-bold text-lg text-gray-900 mb-6">商品销量排行</h3>
<div className="h-[280px]">
{productSalesData.length === 0 ? (
<div className="flex items-center justify-center h-full text-gray-400">暂无数据</div>
) : (
<div className="h-full space-y-4 overflow-y-auto pr-2">
{productSalesData.map(/* 当前回调处理集合中的单个元素。 */ (item, index) => (
<div key={`${item.name}-${index}`} className="space-y-2">
<div className="flex items-center justify-between gap-4">
<div className="flex items-center gap-3 min-w-0">
<span className={`w-7 h-7 rounded-xl flex items-center justify-center text-xs font-extrabold ${index < 3 ? 'bg-blue-600 text-white' : 'bg-gray-100 text-gray-500'}`}>
{index + 1}
</span>
<span className="font-bold text-gray-800 text-sm truncate">{item.name}</span>
</div>
<span className="font-mono text-sm font-extrabold text-gray-900">{item.sales} 单</span>
</div>
<div className="h-3 rounded-full bg-gray-100 overflow-hidden">
<div
className="h-full rounded-full bg-brand"
style={{ width: `${Math.max(8, (item.sales / maxProductSales) * 100)}%` }}
/>
</div>
</div>
))}
</div>
)}
</div>
</div>
{/* 商品下单占比 */}
<div className="ios-card p-6 rounded-xl">
<h3 className="font-bold text-lg text-gray-900 mb-6">商品下单占比</h3>
<div
className="dashboard-pie-chart h-[280px] relative"
role="img"
aria-label={`商品下单占比,共 ${totalOrders} 单`}
>
{sourceDataData.length === 0 ? (
<div className="flex items-center justify-center h-full text-gray-400">暂无数据</div>
) : (
<>
<ResponsiveContainer width="100%" height="100%">
<PieChart accessibilityLayer={false}>
<Pie
data={sourceDataData}
cx="50%"
cy="45%"
innerRadius={60}
outerRadius={90}
paddingAngle={2}
dataKey="value"
activeShape={{
outerRadius: 96,
stroke: 'none',
strokeWidth: 0,
}}
rootTabIndex={-1}
label={false}
labelLine={false}
>
{sourceDataData.map(/* 当前回调处理集合中的单个元素。 */ (entry, index) => (
<Cell key={`cell-${index}`} fill={entry.color} />
))}
</Pie>
<Tooltip
formatter={/* 当前回调处理用户交互或异步状态变化。 */ (value) => `${Number(value || 0)} 单`}
wrapperStyle={{ zIndex: 30, outline: 'none' }}
contentStyle={{
backgroundColor: cssColor('white'),
border: `1px solid ${cssColor('neutral-200')}`,
borderRadius: '10px',
boxShadow: 'var(--shadow-md)'
}}
/>
<Legend
verticalAlign="bottom"
height={36}
iconType="circle"
formatter={/* 当前回调处理用户交互或异步状态变化。 */ (value) => <span style={{ color: cssColor('neutral-500'), fontWeight: 500 }}>{value}</span>}
/>
</PieChart>
</ResponsiveContainer>
<div className="pointer-events-none absolute inset-0 z-10 flex flex-col items-center justify-center pb-9">
<span className="text-2xl font-extrabold text-gray-900 tabular-nums">{totalOrders}</span>
<span className="text-xs font-medium text-gray-400 mt-0.5">总订单</span>
</div>
</>
)}
</div>
</div>
</div>
{/* 收支明细和品类营收 */}
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
{/* 参与统计的订单列表 */}
<div className="lg:col-span-2 ios-card p-0 rounded-xl border-0 bg-white overflow-hidden flex flex-col">
<div className="p-6 border-b border-gray-50 flex justify-between items-center bg-surface-muted">
<div>
<h3 className="font-bold text-lg text-gray-900">参与统计的订单</h3>
{validOrdersTruncated && (
<p className="text-xs text-amber-700 mt-1">当前显示最近 {validOrders.length} / {validOrdersTotal} 条,搜索仅覆盖已加载明细。</p>
)}
</div>
<div className="relative">
<input
placeholder="搜索订单号/商品/买家..."
value={searchTerm}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setSearchTerm(e.target.value)}
className="pl-4 pr-4 py-2 rounded-xl bg-white border border-gray-100 text-sm focus:border-blue-400 outline-none w-48"
type="text"
/>
</div>
</div>
<div className="overflow-x-auto flex-1 max-h-[400px]">
{ordersLoading ? (
<div className="flex items-center justify-center py-20 text-gray-400">
<Activity className="w-6 h-6 animate-spin mr-2" />
加载中...
</div>
) : filteredValidOrders.length === 0 ? (
<div className="flex flex-col items-center justify-center py-16 px-8 text-center">
<div className="w-14 h-14 rounded-2xl bg-gray-100 flex items-center justify-center mb-4">
<PackageCheck className="w-7 h-7 text-gray-300" />
</div>
{normalizedSearchTerm ? (
<>
<div className="text-sm font-extrabold text-gray-900">没有匹配的订单</div>
<div className="text-xs text-gray-400 mt-2 max-w-md">
当前共有 {validOrders.length} 单参与统计,但没有订单号、商品、买家匹配“{searchTerm}”。
</div>
</>
) : (
<>
<div className="text-sm font-extrabold text-gray-900">当前范围内没有参与统计的订单</div>
<div className="text-xs text-gray-400 mt-2 max-w-lg leading-6">
日期范围:{currentRangeDates.startDate} 至 {currentRangeDates.endDate};
统计口径:待发货、已发货、已完成,且订单金额不为空。
当前统计卡片订单数:{analytics.revenue_stats.total_orders} 单。
</div>
</>
)}
</div>
) : (
<table className="w-full min-w-[760px] text-left border-collapse">
<thead>
<tr className="bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50">
<th className="px-6 py-4">订单信息</th>
<th className="px-6 py-4">买家信息</th>
<th className="px-6 py-4">金额</th>
<th className="px-6 py-4 whitespace-nowrap">状态</th>
<th className="px-6 py-4 text-right">操作</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-50">
{filteredValidOrders.map(/* 当前回调处理集合中的单个元素。 */ (order) => (
<tr key={order.order_id} className="hover:bg-warning-50/50 transition-colors group">
<td className="px-6 py-4">
<div className="flex items-center gap-3">
<div className="w-12 h-12 rounded-xl bg-gray-100 overflow-hidden shadow-sm border border-gray-100 flex-shrink-0">
<PackageCheck className="w-full h-full text-gray-300 p-2" />
</div>
<div className="min-w-0">
<div className="font-bold text-gray-900 text-sm line-clamp-1">
{order.item_title || order.item_id || '未知商品'}
</div>
<div className="text-xs text-gray-500 mt-1 font-mono">{order.order_id}</div>
<div className="text-xs text-gray-400 mt-0.5">数量: {order.quantity || 1}</div>
</div>
</div>
</td>
<td className="px-6 py-4">
<div className="text-sm font-bold text-gray-800">{order.buyer_id}</div>
{order.created_at && (
<div className="text-xs text-gray-400 mt-1">{formatLocalDateTime(order.created_at)}</div>
)}
</td>
<td className="px-6 py-4 text-base font-extrabold text-gray-900 font-feature-settings-tnum">
¥{order.amount || '0.00'}
</td>
<td className="px-6 py-4 whitespace-nowrap">
<StatusBadge status={order.status || order.order_status || 'unknown'} />
</td>
<td className="px-6 py-4 text-right">
<a
href={`https://www.goofish.com/order-detail?orderId=${order.order_id}&role=seller`}
target="_blank"
rel="noopener noreferrer"
className="inline-flex text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors"
title="查看闲鱼详情"
>
<ExternalLink className="w-4 h-4" />
</a>
</td>
</tr>
))}
</tbody>
</table>
)}
</div>
</div>
{/* 商品金额分析 */}
<div className="ios-card p-6 rounded-xl bg-white">
<h3 className="font-bold text-lg text-gray-900 mb-6">商品金额分析 (TOP5)</h3>
{categoryDataData.length === 0 ? (
<div className="flex items-center justify-center h-[300px] text-gray-400">暂无数据</div>
) : (
<>
<div
className="dashboard-pie-chart h-[280px] relative"
role="img"
aria-label={`商品金额分析,总金额 ${formatCurrency(totalAmount)}`}
>
<ResponsiveContainer width="100%" height="100%">
<PieChart accessibilityLayer={false}>
<Pie
data={categoryDataData}
cx="50%"
cy="50%"
innerRadius={60}
outerRadius={92}
paddingAngle={2}
dataKey="value"
activeShape={{
outerRadius: 98,
stroke: 'none',
strokeWidth: 0,
}}
rootTabIndex={-1}
label={false}
labelLine={false}
>
{categoryDataData.map(/* 当前回调处理集合中的单个元素。 */ (entry, index) => (
<Cell key={`cell-${index}`} fill={entry.color || COLORS[index % COLORS.length]} />
))}
</Pie>
<Tooltip
wrapperStyle={{ zIndex: 30, outline: 'none' }}
contentStyle={{
backgroundColor: cssColor('white'),
border: `1px solid ${cssColor('neutral-200')}`,
borderRadius: '6px',
boxShadow: 'var(--shadow-md)'
}}
formatter={/* 当前回调处理用户交互或异步状态变化。 */ (value) => `¥${Number(value || 0).toLocaleString()}`}
/>
</PieChart>
</ResponsiveContainer>
<div className="pointer-events-none absolute inset-0 z-10 flex flex-col items-center justify-center">
<span className="text-lg font-extrabold text-gray-900 tabular-nums">{formatCurrency(totalAmount)}</span>
<span className="text-xs font-medium text-gray-400 mt-0.5">总金额</span>
</div>
</div>
<div className="space-y-3 mt-4">
{categoryDataData.map(/* 当前回调处理集合中的单个元素。 */ (cat) => (
<div key={cat.name} className="flex justify-between items-center gap-3 text-sm">
<div className="flex items-center gap-2 min-w-0 flex-1">
<div
className="w-3 h-3 rounded-full shrink-0"
style={{ backgroundColor: cat.color || COLORS[categoryDataData.indexOf(cat) % COLORS.length] }}
></div>
<span className="text-gray-600 font-medium truncate" title={cat.name}>{cat.name}</span>
</div>
<div className="flex items-center gap-3 shrink-0 whitespace-nowrap">
<span className="font-bold text-gray-900">¥{cat.value.toLocaleString()}</span>
<span className="text-xs text-gray-500 bg-gray-100 px-2 py-0.5 rounded">{cat.percentage}%</span>
</div>
</div>
))}
</div>
</>
)}
</div>
</div>
</div>
);
};
export default Dashboard;
@@ -1,5 +1,5 @@
import { expect, test } from 'vitest';
import type { OrderAnalytics } from '../../../types';
import type { OrderAnalytics } from '../../../shared/api-contract';
import { buildCategoryData, buildChartData, buildItemNameMap, buildProductSalesData, buildSourceData, getMaxProductSales, getRangeLabel, getTrendPercent, isCurrentDashboardRequest } from './state';
// analyticsFixture 是覆盖趋势、商品排行和零值边界的最小分析数据。
+1 -1
View File
@@ -1,4 +1,4 @@
import type { Item, OrderAnalytics } from '../../../types';
import type { Item, OrderAnalytics } from '../../../shared/api-contract';
import type { DateRange, TimeRange } from '../../../dateRange';
import type { DashboardRangeSelection } from './types';
+1 -1
View File
@@ -1,4 +1,4 @@
import type { Item, Order, OrderAnalytics, DashboardStats } from '../../../types';
import type { Item, Order, OrderAnalytics, DashboardStats } from '../../../shared/api-contract';
import type { DateRange, TimeRange } from '../../../dateRange';
/** Dashboard 请求状态。 */
+164 -21
View File
@@ -1,21 +1,164 @@
// ItemList feature 通过本适配层访问商品、批量任务和发货地 API。
export {
getItems,
getAccountDetails,
syncItemsFromAccount,
createItem,
publishItem,
recommendPublishCategory,
previewItemPublishBatch,
startItemPublishBatch,
getItemPublishBatch,
getItemPublishBatches,
deleteItemPublishBatch,
cancelItemPublishBatch,
retryFailedItemPublishBatch,
updateItem,
deleteItem,
getShippingRules,
} from '../../../services/api';
export type { PublishLocation } from '../../../services/api';
export { getPublishLocations } from '../../../services/amapLocation';
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';
import { getPublishLocations } from '../../../services/amapLocation';
import type { PublishLocation } from '../../../shared/api-contract';
/** 商品账号筛选器读取非敏感账号摘要。 */
export const getAccountDetails = async (options?: RequestControlOptions): Promise<AccountDetail[]> => get('/api/v1/accounts/details', undefined, options);
/** 商品页面读取自动化发货规则的兼容列表。 */
export const getShippingRules = async (): Promise<ShippingRule[]> => get('/api/v1/automation-rules');
export { getPublishLocations };
export type { PublishLocation } from '../../../shared/api-contract';
// Items
// normalizeBooleanFlag 归一化布尔标记。
const normalizeBooleanFlag = (value: unknown): boolean =>
value === true || value === 1 || value === '1';
// getItems 读取商品列表。
export const getItems = async (cookieId?: string, options?: RequestControlOptions): Promise<Item[]> => {
// res 接口响应结果,用于当前 API 处理流程。
const res = await get<unknown>('/api/v1/items', cookieId ? { cookie_id: cookieId } : undefined, options);
// items 商品列表,用于当前 API 处理流程。
const items = collectionFrom<Item>(res, ['items', 'data', 'results']);
return items.map(/* 当前回调用于处理集合元素或接口响应。 */ (item: any) => ({
...item,
id: item.id || `${item.cookie_id}-${item.item_id}`,
is_multi_spec: normalizeBooleanFlag(item.is_multi_spec),
is_multi_qty_ship: normalizeBooleanFlag(item.is_multi_qty_ship ?? item.multi_quantity_delivery),
multi_quantity_delivery: normalizeBooleanFlag(item.multi_quantity_delivery ?? item.is_multi_qty_ship),
}));
}
// syncItemsFromAccount 从账号同步商品。
export const syncItemsFromAccount = async (cookieId: string): Promise<ItemSyncResponse> => {
return post('/api/v1/items/get-all-from-account', { cookie_id: cookieId });
}
// deleteItem 删除商品。
export const deleteItem = async (cookieId: string, itemId: string): Promise<OperationResponse> => {
return del(`/api/v1/items/${cookieId}/${itemId}`);
}
// createItem 创建商品。
export const createItem = async (cookieId: string, data: Partial<Item>): Promise<OperationResponse> => {
return post(`/api/v1/items/${cookieId}`, data);
}
// publishItem 发布商品。
export const publishItem = async (form: {
/** cookie_id 表示登录凭证标识。 */ cookie_id: string;
/** title 表示标题。 */ title: string;
/** description 表示描述。 */ description: string;
/** price 表示售价。 */ price: string;
/** original_price 表示原始售价。 */ original_price?: string;
/** quantity 表示数量。 */ quantity: string | number;
/** postage_mode 表示运费模式。 */ postage_mode: string;
/** postage 表示运费。 */ postage?: string;
/** images 表示图片列表。 */ images: File[];
/** location 表示地址。 */ location?: PublishLocation;
}): Promise<ItemPublishResponse> => {
// body 请求体,用于当前 API 处理流程。
const body = new FormData();
body.set('cookie_id', form.cookie_id);
body.set('title', form.title);
body.set('description', form.description);
body.set('price', form.price);
body.set('original_price', form.original_price || '');
body.set('quantity', String(form.quantity));
body.set('postage_mode', form.postage_mode);
body.set('postage', form.postage || '');
if (form.location) body.set('location', JSON.stringify(form.location));
for (const // file 上传文件,用于当前 API 处理流程。
file of form.images) {
body.append('images', file);
}
return postForm('/api/v1/items/publish', body);
}
// recommendPublishCategory 推荐商品发布分类。
export const recommendPublishCategory = async (cookieId: string, keyword: string): Promise<CategoryRecommendationResponse> => {
// 类目推荐成功响应使用共享 CategoryRecommendationResponse。
// category 字段保留平台类目 ID、名称和频道类目 ID。
// tb_cat_id 继续保持可选,兼容电子资料类目。
// 请求仍携带账号 ID 和关键词。
// 失败响应由共享 HTTP 错误结构处理。
// 该类型收口不改变凭证刷新和错误处理。
// 前端批量发布流程可直接复用 category。
// 旧路径继续由现有 Vite 代理转发。
return post('/api/v1/items/publish-categories/recommend', { cookie_id: cookieId, keyword });
};
// previewItemPublishBatch 预览商品批量发布。
export const previewItemPublishBatch = async (form: {
/** file 表示上传文件。 */ file: File;
/** imagesZip 表示图片压缩包。 */ imagesZip?: File | null;
/** defaultCookieId 表示默认账号凭证标识。 */ defaultCookieId?: string;
/** fallbackCategory 表示备用分类。 */ fallbackCategory: {
/** catId 表示分类标识。 */ catId: string;
/** catName 表示分类名称。 */ catName: string;
/** channelCatId 表示渠道分类标识。 */ channelCatId?: string;
/** tbCatId 表示淘宝分类标识。 */ tbCatId?: string;
};
/** location 表示地址。 */ location?: PublishLocation;
}): Promise<ItemPublishBatchPreviewResponse> => {
// body 请求体,用于当前 API 处理流程。
const body = new FormData();
body.set('file', form.file);
if (form.imagesZip) body.set('images_zip', form.imagesZip);
if (form.defaultCookieId) body.set('default_cookie_id', form.defaultCookieId);
body.set('fallback_category_id', form.fallbackCategory.catId);
body.set('fallback_category_name', form.fallbackCategory.catName);
body.set('fallback_channel_category_id', form.fallbackCategory.channelCatId || '');
body.set('fallback_tb_category_id', form.fallbackCategory.tbCatId || '');
if (form.location) body.set('location', JSON.stringify(form.location));
return postForm('/api/v1/items/publish-batches/preview', body);
}
// startItemPublishBatch 启动商品批量发布。
export const startItemPublishBatch = async (previewId: string): Promise<BatchIDResponse> => {
return post('/api/v1/items/publish-batches', { preview_id: previewId });
}
// getItemPublishBatch 读取商品发布批次。
export const getItemPublishBatch = async (batchId: string): Promise<ItemPublishBatchResponse> => {
return get(`/api/v1/items/publish-batches/${batchId}`);
}
// getItemPublishBatches 读取商品发布批次列表。
export const getItemPublishBatches = async (limit = 20): Promise<ItemPublishBatchResponse[]> => {
// res 接口响应结果,用于当前 API 处理流程。
const res = await get<unknown>('/api/v1/items/publish-batches', { limit });
return collectionFrom<ItemPublishBatchResponse>(res, ['batches', 'data', 'items']);
}
// deleteItemPublishBatch 删除商品发布批次。
export const deleteItemPublishBatch = async (batchId: string): Promise<OperationResponse> => {
return del(`/api/v1/items/publish-batches/${batchId}`);
}
// cancelItemPublishBatch 取消商品发布批次。
export const cancelItemPublishBatch = async (batchId: string): Promise<BatchCancelResponse> => {
return post(`/api/v1/items/publish-batches/${batchId}/cancel`, {});
}
// retryFailedItemPublishBatch 重试失败的商品发布任务。
export const retryFailedItemPublishBatch = async (batchId: string): Promise<BatchIDResponse> => {
return post(`/api/v1/items/publish-batches/${batchId}/retry-failed`, {});
}
// updateItem 更新商品。
export const updateItem = async (cookieId: string, itemId: string, data: Partial<Item>): Promise<OperationResponse> => {
return put(`/api/v1/items/${cookieId}/${itemId}`, data);
}
/** 读取指定账号与商品的详情,用于编辑器恢复表单。 */
export const getItemDetail = async (accountID: string, itemID: string): Promise<ItemDetailResponse> => get(`/api/v1/items/${accountID}/${itemID}`);
+1 -1
View File
@@ -1,7 +1,7 @@
// @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 '../../../types';
import type { BatchCancelResponse, BatchIDResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchResponse } from '../../../shared/api-contract';
import {
cancelItemPublishBatch,
deleteItemPublishBatch,
@@ -2,7 +2,7 @@
import { act, renderHook } from '@testing-library/react';
import { useState } from 'react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import type { Item } from '../../../types';
import type { Item } from '../../../shared/api-contract';
import { createItem, deleteItem, getPublishLocations, publishItem, syncItemsFromAccount, updateItem } from './api';
import { useItemActions, type ItemActionsOptions } from './itemActions';
+1 -1
View File
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useState, type Dispatch, type SetStateAction } from 'react';
import type { Item } from '../../../types';
import type { Item } from '../../../shared/api-contract';
import { createItem, deleteItem, getPublishLocations, publishItem, syncItemsFromAccount, updateItem } from './api';
import type { PublishLocation } from './api';
@@ -0,0 +1,909 @@
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { createPortal } from 'react-dom';
import type { Item } from '../../../../shared/api-contract';
import {
getItems,
getAccountDetails,
getShippingRules,
getItemPublishBatches,
} from '../api';
import type { AccountDetail, ShippingRule } from '../../../../shared/api-contract';
import type { ItemListProps } from '../types';
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';
// formatItemPrice 将商品价格转换为本地化展示文本。
const formatItemPrice = (price?: string) => {
// value 值。
const value = String(price || '').trim();
if (!value) return '-';
return /^[¥¥]/.test(value) ? value : `¥${value}`;
};
// ItemList 渲染商品列表组件。
const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
// [items, 解构得到当前 Hook 返回的状态和操作函数。
const [items, setItems] = useState<Item[]>([]);
// [shippingRules, 解构得到当前 Hook 返回的状态和操作函数。
const [shippingRules, setShippingRules] = useState<ShippingRule[]>([]);
// [accounts, 解构得到当前 Hook 返回的状态和操作函数。
const [accounts, setAccounts] = useState<AccountDetail[]>([]);
// [selectedAccount, 解构得到当前 Hook 返回的状态和操作函数。
const [selectedAccount, setSelectedAccount] = useState<string>('');
// [accountFilter, 解构得到当前 Hook 返回的状态和操作函数。
const [accountFilter, setAccountFilter] = useState<string>('');
// loadItems 刷新商品列表,供普通操作和批量任务完成后复用。
const loadItems = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async () => {
// itemsList 商品列表列表,负责当前功能中的对应处理。
const itemsList = await getItems();
setItems(itemsList);
}, []);
// loadShippingRules 刷新商品关联的自动化规则。
const loadShippingRules = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async () => {
setShippingRules(await getShippingRules());
}, []);
// batchState 是 ItemList feature 提供的批量铺货状态和动作边界。
const batchState = useItemPublishBatch({ selectedAccount, loadItems, loadShippingRules });
// 解构数据 解构得到当前 Hook 返回的状态和操作函数。
const {
showBatchModal,
setShowBatchModal,
batchLoading,
batchPhase,
batchFile,
setBatchFile,
batchImagesZip,
setBatchImagesZip,
batchCategoryKeyword,
setBatchCategoryKeyword,
batchCategoryLoading,
batchFallbackCategory,
setBatchFallbackCategory,
batchPreview,
batchDetail,
recentBatch,
setRecentBatch,
batchLocations,
batchLocation,
setBatchLocations,
setBatchLocation,
openBatchModal,
handleRecommendBatchCategory,
openRecentBatchResult,
handlePreviewBatch,
handleStartBatch,
handleCancelBatch,
abandonBatchPreview,
closeBatchModal,
handleRetryBatchFailed,
} = batchState;
// itemActions 商品 feature 提供普通商品操作、发布表单和定位动作。
const itemActions = useItemActions({
selectedAccount,
setSelectedAccount,
setItems,
loadItems,
loadShippingRules,
onConfigureDelivery,
setBatchLocations,
setBatchLocation,
});
// 解构商品动作,保持页面 JSX 只负责布局和表单字段组合。
const {
loading,
publishing,
showEditModal,
setShowEditModal,
showAddModal,
setShowAddModal,
showPublishModal,
setShowPublishModal,
locationLoading,
publishLocations,
setPublishLocations,
publishLocation,
setPublishLocation,
selectedItem,
editForm,
setEditForm,
addForm,
setAddForm,
publishForm,
setPublishForm,
publishImagePreviews,
handleSync,
handleEdit,
handleSaveEdit,
handleDelete,
handleAddItem,
handlePublishItem,
downloadPublishTemplate,
openAddModal,
openPublishModal,
locateForPublish,
} = itemActions;
useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => {
Promise.all([getAccountDetails(), getItems(), getShippingRules(), getItemPublishBatches(20)])
.then(/* 当前回调处理异步操作结果。 */ ([accountList, itemList, ruleList, batches]) => {
setAccounts(accountList);
setItems(itemList);
setShippingRules(ruleList);
// recoverable 可恢复任务。
const recoverable = batches.find(/* 当前回调处理集合中的单个元素。 */ batch => ['running', 'canceling'].includes(batch.status))
|| batches.find(/* 当前回调处理集合中的单个元素。 */ batch => batch.status !== 'preview');
setRecentBatch(recoverable || null);
})
.catch(/* 当前回调处理异步操作结果。 */ (e) => console.error('加载商品配置失败:', e));
}, []);
// rulesForItem 规则列表For商品,负责当前功能中的对应处理。
const rulesForItem = (item: Item) => shippingRules.filter(/* 当前回调处理集合中的单个元素。 */ rule =>
rule.cookie_id === item.cookie_id && rule.item_id === item.item_id
).length > 0
? shippingRules.filter(/* 当前回调处理集合中的单个元素。 */ rule => rule.cookie_id === item.cookie_id && rule.item_id === item.item_id)
: shippingRules.filter(/* 当前回调处理集合中的单个元素。 */ rule => rule.cookie_id === item.cookie_id && !rule.item_id);
// accountMap 账号索引。
const accountMap = useMemo(
/* 当前回调处理集合中的单个元素。 */ () => new Map(accounts.map(/* 当前回调处理集合中的单个元素。 */ account => [account.id, account])),
[accounts],
);
// visibleItems 可见商品列表。
const visibleItems = useMemo(
/* 当前回调处理集合中的单个元素。 */ () => accountFilter ? items.filter(/* 当前回调处理集合中的单个元素。 */ item => item.cookie_id === accountFilter) : items,
[accountFilter, items],
);
// accountName 账号名称。
const accountName = (cookieId: string) => {
// account 账号。
const account = accountMap.get(cookieId);
// name 名称。
const name = account?.remark || account?.nickname;
return name ? `${name} · ${cookieId.slice(0, 6)}` : `账号 ${cookieId.slice(0, 8)}`;
};
// accountNickname 账号昵称。
const accountNickname = (cookieId: string) => {
// account 账号。
const account = accountMap.get(cookieId);
return account?.remark || account?.nickname || '未命名账号';
};
return (
<div className="space-y-6 animate-fade-in">
<div className="flex flex-col xl:flex-row xl:justify-between xl:items-center gap-4">
<div>
<h2 className="text-3xl font-bold text-gray-900">商品管理</h2>
<p className="text-gray-500 mt-2 text-sm">监控并管理所有账号下的闲鱼商品。</p>
</div>
<div className="flex flex-wrap items-end gap-3">
<div className="flex min-w-[200px] flex-col gap-1.5">
<label htmlFor="item-account-filter" className="px-1 text-[11px] font-extrabold tracking-wide text-gray-500">
商品列表筛选
</label>
<div className="relative">
<Filter className="w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none" />
<select
id="item-account-filter"
aria-label="按账号筛选商品列表"
className="ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm"
value={accountFilter}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ event => setAccountFilter(event.target.value)}
>
<option value="">全部账号</option>
{accounts.map(/* 当前回调处理集合中的单个元素。 */ account => (
<option key={account.id} value={account.id}>{accountName(account.id)}</option>
))}
</select>
</div>
</div>
<div className="flex min-w-[200px] flex-col gap-1.5">
<label htmlFor="item-sync-account" className="px-1 text-[11px] font-extrabold tracking-wide text-gray-500">
同步商品账号
</label>
<div className="relative">
<User className="w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none" />
<select
id="item-sync-account"
aria-label="选择要同步商品的账号"
className="ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm"
value={selectedAccount}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setSelectedAccount(e.target.value)}
>
<option value="">请选择账号</option>
{accounts.map(/* 当前回调处理集合中的单个元素。 */ acc => (
<option key={acc.id} value={acc.id}>{accountName(acc.id)}</option>
))}
</select>
</div>
</div>
<button
onClick={handleSync}
disabled={loading || !selectedAccount}
className="ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50"
>
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
同步商品
</button>
<button
onClick={openAddModal}
className="px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors flex items-center gap-2 shadow-lg"
>
<Plus className="w-4 h-4" />
添加商品
</button>
<button
onClick={openPublishModal}
className="px-5 py-3 rounded-2xl font-bold bg-emerald-500 text-white hover:bg-emerald-600 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100"
>
<PackagePlus className="w-4 h-4" />
发布商品
</button>
<button
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void openBatchModal()}
className="px-5 py-3 rounded-2xl font-bold bg-brand text-white hover:bg-brand-highlight transition-colors flex items-center gap-2 shadow-lg shadow-blue-100"
>
<UploadCloud className="w-4 h-4" />
{recentBatch && ['running', 'canceling'].includes(recentBatch.status) ? '继续批量任务' : '批量铺货'}
</button>
{recentBatch && !['running', 'canceling'].includes(recentBatch.status) && (
<button
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void openRecentBatchResult()}
className="px-4 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors"
>
最近批次结果
</button>
)}
</div>
</div>
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
{visibleItems.map(/* 当前回调处理集合中的单个元素。 */ item => {
// linkedRules 关联规则列表。
const linkedRules = rulesForItem(item);
// hasRule 是否存在规则。
const hasRule = linkedRules.length > 0;
return (
<div key={`${item.cookie_id}-${item.item_id}`} className="ios-card p-3 rounded-2xl hover:shadow-lg transition-all group relative flex flex-col">
<div className="absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity z-10">
<button
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => handleEdit(item)}
className="p-1.5 bg-white/90 backdrop-blur rounded-lg shadow-md text-gray-600 hover:bg-brand hover:text-white transition-colors"
title="编辑"
>
<Edit className="w-3.5 h-3.5" />
</button>
<button
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => handleDelete(item)}
className="p-1.5 bg-white/90 backdrop-blur rounded-lg shadow-md hover:bg-red-100 text-red-500 transition-colors"
title="删除"
>
<Trash2 className="w-3.5 h-3.5" />
</button>
</div>
<div className="aspect-square bg-gray-100 rounded-xl mb-2.5 overflow-hidden relative">
{item.item_image ? (
<img src={item.item_image} alt="" className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500" />
) : (
<div className="w-full h-full flex items-center justify-center text-gray-300">
<Box className="w-8 h-8" />
</div>
)}
<div className="absolute top-1.5 left-1.5 bg-black/50 backdrop-blur-md text-white text-[10px] font-bold px-1.5 py-0.5 rounded-md">
{formatItemPrice(item.item_price)}
</div>
</div>
<h3 className="font-bold text-gray-900 line-clamp-2 text-xs mb-1.5 h-8 leading-4">{item.item_title}</h3>
<div className="mb-2 inline-flex min-w-0 max-w-full items-center gap-1 self-start rounded-md bg-blue-50 px-2 py-1 text-[10px] font-extrabold text-blue-700" title={accountNickname(item.cookie_id)}>
<User className="h-3 w-3 shrink-0" />
<span className="min-w-0 truncate whitespace-nowrap">{accountNickname(item.cookie_id)}</span>
</div>
<div className="flex justify-between items-center text-[10px] text-gray-500 mb-2">
<span className="bg-gray-100 px-1.5 py-0.5 rounded truncate max-w-[80px]">ID: {item.item_id}</span>
<span className={`inline-flex items-center gap-1 font-bold ${hasRule ? 'text-emerald-600' : 'text-amber-600'}`}>
{hasRule ? <CheckCircle2 className="w-3 h-3" /> : <CircleDashed className="w-3 h-3" />}
{hasRule ? `${linkedRules.length} 规则` : '未配置'}
</span>
</div>
<div className="space-y-2 mt-auto">
<button
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => onConfigureDelivery(item)}
className={`w-full flex items-center justify-between gap-1 px-2.5 py-2 rounded-lg text-[11px] font-extrabold transition-all ${hasRule ? 'bg-gray-900 text-white hover:bg-black' : 'bg-brand text-white hover:bg-brand-highlight shadow-md shadow-blue-100'}`}
>
<span className="flex items-center gap-1.5"><Link2 className="w-3.5 h-3.5" />{hasRule ? '查看发货规则' : '关联发货规则'}</span>
<ArrowRight className="w-3.5 h-3.5" />
</button>
</div>
</div>
);
})}
{visibleItems.length === 0 && (
<div className="col-span-full py-20 text-center text-gray-400">
<ShoppingBag className="w-12 h-12 mx-auto mb-4 opacity-30" />
{accountFilter ? '该账号暂无商品数据' : '暂无商品数据,请选择账号进行同步'}
</div>
)}
</div>
{showEditModal && selectedItem && createPortal(
<div className="modal-overlay-centered">
<div className="modal-container" style={{maxWidth: '560px'}}>
<div className="modal-header flex items-center justify-between">
<div>
<h3 className="text-xl font-extrabold text-gray-900">编辑商品</h3>
<p className="text-xs text-gray-500 mt-1">ID: {selectedItem.item_id}</p>
</div>
<button onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setShowEditModal(false)} className="p-2 rounded-xl hover:bg-gray-100 transition-colors">
<X className="w-5 h-5 text-gray-500" />
</button>
</div>
<div className="modal-body space-y-4">
<input className="w-full ios-input px-4 py-3 rounded-xl" placeholder="商品标题" value={editForm.item_title || ''} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setEditForm({...editForm, item_title: e.target.value})} />
<input className="w-full ios-input px-4 py-3 rounded-xl" placeholder="价格" value={editForm.item_price || ''} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setEditForm({...editForm, item_price: e.target.value})} />
<input className="w-full ios-input px-4 py-3 rounded-xl" placeholder="分类" value={editForm.item_category || ''} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setEditForm({...editForm, item_category: e.target.value})} />
<textarea className="w-full ios-input px-4 py-3 rounded-xl h-28 resize-none" placeholder="描述" value={editForm.item_description || ''} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setEditForm({...editForm, item_description: e.target.value})} />
</div>
<div className="modal-footer">
<button onClick={handleSaveEdit} className="w-full ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2">
<Save className="w-4 h-4" />
保存
</button>
</div>
</div>
</div>
, document.body)}
{showAddModal && createPortal(
<div className="modal-overlay-centered">
<div className="modal-container" style={{maxWidth: '720px'}}>
<div className="modal-header flex items-center justify-between">
<div>
<h3 className="text-xl font-extrabold text-gray-900">添加商品</h3>
<p className="text-xs text-gray-500 mt-1">手动建立商品与自动发货规则的关联</p>
</div>
<button onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setShowAddModal(false)} className="p-2 rounded-xl hover:bg-gray-100 transition-colors" title="关闭">
<X className="w-5 h-5 text-gray-500" />
</button>
</div>
<div className="modal-body space-y-5">
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">所属账号</label>
<select className="w-full ios-input px-4 py-3 rounded-xl" value={addForm.cookie_id} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setAddForm({...addForm, cookie_id: e.target.value})}>
<option value="">选择账号</option>
{accounts.map(/* 当前回调处理集合中的单个元素。 */ acc => <option key={acc.id} value={acc.id}>{accountName(acc.id)}</option>)}
</select>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">商品 ID</label>
<input className="w-full ios-input px-4 py-3 rounded-xl" placeholder="输入闲鱼商品 ID" value={addForm.item_id} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setAddForm({...addForm, item_id: e.target.value})} />
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">商品价格</label>
<input className="w-full ios-input px-4 py-3 rounded-xl" placeholder="例如 99.00" value={addForm.item_price} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setAddForm({...addForm, item_price: e.target.value})} />
</div>
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">商品标题</label>
<input className="w-full ios-input px-4 py-3 rounded-xl" placeholder="输入商品标题" value={addForm.item_title} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setAddForm({...addForm, item_title: e.target.value})} />
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">图片 URL</label>
<input className="w-full ios-input px-4 py-3 rounded-xl" placeholder="https://..." value={addForm.item_image} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setAddForm({...addForm, item_image: e.target.value})} />
</div>
</div>
<div className="modal-footer">
<button onClick={handleAddItem} className="w-full ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2">
<Plus className="w-4 h-4" />
添加商品
</button>
</div>
</div>
</div>
, document.body)}
{showPublishModal && createPortal(
<div className="modal-overlay-centered">
<div className="modal-container" style={{maxWidth: '820px'}}>
<div className="modal-header flex items-center justify-between">
<div>
<h3 className="text-xl font-extrabold text-gray-900">发布商品到闲鱼</h3>
<p className="text-xs text-gray-500 mt-1">普通单规格发布;库存数量会写入闲鱼发布参数,用于判断账号库存能力。</p>
</div>
<button onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setShowPublishModal(false)} className="p-2 rounded-xl hover:bg-gray-100 transition-colors" title="关闭">
<X className="w-5 h-5 text-gray-500" />
</button>
</div>
<div className="modal-body space-y-5">
<div className="rounded-2xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-800 leading-6">
发布时必须填写库存。若账号没有库存发布能力,后端会返回明确的“库存权限不足”错误,不会误报为普通发布失败。
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">发布账号</label>
<select className="w-full ios-input px-4 py-3 rounded-xl" value={publishForm.cookie_id} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => {
setPublishForm({...publishForm, cookie_id: e.target.value});
setPublishLocations([]);
setPublishLocation(null);
}}>
<option value="">选择账号</option>
{accounts.map(/* 当前回调处理集合中的单个元素。 */ acc => <option key={acc.id} value={acc.id}>{accountName(acc.id)}</option>)}
</select>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">商品标题</label>
<input className="w-full ios-input px-4 py-3 rounded-xl" placeholder="例如:会员月卡自动发货" value={publishForm.title} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setPublishForm({...publishForm, title: e.target.value})} />
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">库存数量</label>
<input className="w-full ios-input px-4 py-3 rounded-xl" type="number" min="1" placeholder="必须大于 0" value={publishForm.quantity} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setPublishForm({...publishForm, quantity: e.target.value})} />
</div>
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">商品描述</label>
<textarea className="w-full ios-input px-4 py-3 rounded-xl h-28 resize-none" placeholder="描述会用于自动识别类目;留空时使用标题" value={publishForm.description} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setPublishForm({...publishForm, description: e.target.value})} />
</div>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">售价</label>
<input className="w-full ios-input px-4 py-3 rounded-xl" placeholder="99.00" value={publishForm.price} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setPublishForm({...publishForm, price: e.target.value})} />
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">原价(可选)</label>
<input className="w-full ios-input px-4 py-3 rounded-xl" placeholder="129.00" value={publishForm.original_price} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setPublishForm({...publishForm, original_price: e.target.value})} />
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">运费方式</label>
<select className="w-full ios-input px-4 py-3 rounded-xl" value={publishForm.postage_mode} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setPublishForm({...publishForm, postage_mode: e.target.value})}>
<option value="free">包邮</option>
<option value="distance">按距离计费</option>
<option value="fixed">一口价邮费</option>
<option value="none">无需邮寄</option>
</select>
</div>
</div>
{publishForm.postage_mode === 'fixed' && (
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">一口价邮费</label>
<input className="w-full ios-input px-4 py-3 rounded-xl" placeholder="例如 8.00" value={publishForm.postage} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setPublishForm({...publishForm, postage: e.target.value})} />
</div>
)}
<div className="rounded-2xl border border-sky-200 bg-sky-50 p-4 space-y-3">
<div className="flex items-center justify-between gap-3">
<div><div className="text-sm font-extrabold text-gray-900">发货地(可选)</div><p className="mt-1 text-xs text-sky-800">虚拟商品无需发货地;发布失败时可再定位并作为补充信息提交。</p></div>
<button type="button" disabled={locationLoading || !publishForm.cookie_id} onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void locateForPublish(false)} className="ios-btn-primary flex items-center gap-2 rounded-xl px-4 py-2 text-sm font-bold disabled:opacity-50">
<LocateFixed className="h-4 w-4" />{locationLoading ? '定位中...' : '获取当前位置'}
</button>
</div>
{publishLocations.length > 0 && <select className="w-full ios-input rounded-xl bg-white px-4 py-3" value={String(Math.max(0, publishLocations.indexOf(publishLocation!)))} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setPublishLocation(publishLocations[Number(e.target.value)] || null)}>
{publishLocations.map(/* 当前回调处理集合中的单个元素。 */ (item, index) => <option key={`${item.division_id}-${item.poi_id}-${index}`} value={String(index)}>{[item.province, item.city, item.area, item.poi_name].filter(Boolean).join(' ')}</option>)}
</select>}
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">商品图片(1-9 张)</label>
<label className="flex min-h-[120px] cursor-pointer flex-col items-center justify-center rounded-2xl border-2 border-dashed border-gray-200 bg-gray-50 px-4 py-6 text-center hover:border-emerald-300 hover:bg-emerald-50/50 transition-colors">
<UploadCloud className="w-8 h-8 text-emerald-600 mb-2" />
<span className="text-sm font-bold text-gray-800">选择图片</span>
<span className="text-xs text-gray-500 mt-1">{publishForm.images.length ? '已选择 ' + publishForm.images.length + ' 张' : '支持 JPG / PNG / GIF'}</span>
<input
className="hidden"
type="file"
accept="image/*"
multiple
onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setPublishForm({...publishForm, images: Array.from(e.target.files || []).slice(0, 9)})}
/>
</label>
{publishImagePreviews.length > 0 && (
<div className="grid grid-cols-4 sm:grid-cols-6 gap-3">
{publishImagePreviews.map(/* 当前回调处理集合中的单个元素。 */ (preview) => (
<div key={preview.key} className="aspect-square rounded-xl bg-gray-100 overflow-hidden border border-gray-100">
<img src={preview.url} alt="" className="w-full h-full object-cover" />
</div>
))}
</div>
)}
</div>
</div>
<div className="modal-footer">
<button disabled={publishing} onClick={handlePublishItem} className="w-full bg-emerald-500 hover:bg-emerald-600 disabled:opacity-60 text-white px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2">
<PackagePlus className="w-4 h-4" />
{publishing ? '正在发布...' : '发布到闲鱼'}
</button>
</div>
</div>
</div>
, document.body)}
{showBatchModal && createPortal(
<div className="modal-overlay-centered">
<div className="modal-container" style={{maxWidth: '980px'}}>
<div className="modal-header flex items-center justify-between">
<div>
<h3 className="text-xl font-extrabold text-gray-900">批量铺货</h3>
<p className="text-xs text-gray-500 mt-1">上传商品表格和图片 zip,先预检,再逐条发布到闲鱼。</p>
</div>
<button onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void closeBatchModal()} className="p-2 rounded-xl hover:bg-gray-100 transition-colors" title="关闭">
<X className="w-5 h-5 text-gray-500" />
</button>
</div>
<div className="modal-body space-y-5">
<BatchPhaseIndicator phase={batchPhase} />
{batchPhase === 'upload' && (
<div className="space-y-5">
<div className="rounded-2xl border border-blue-100 bg-blue-50 p-4 text-sm text-blue-900 leading-6">
<div className="flex flex-col md:flex-row md:items-center md:justify-between gap-3">
<div>
<div className="font-extrabold">先下载模板,再按字段填写。</div>
<div>图片字段写 zip 内相对路径,多个图片用英文分号分隔,例如 <span className="font-mono font-bold">images/a.jpg;images/b.jpg</span>。也支持直接填写图片 URL。</div>
</div>
<button
type="button"
onClick={downloadPublishTemplate}
className="shrink-0 rounded-xl bg-blue-600 px-4 py-2 text-sm font-extrabold text-white hover:bg-blue-700"
>
下载CSV模板
</button>
</div>
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">默认发布账号</label>
<select
className="w-full ios-input px-4 py-3 rounded-xl"
value={selectedAccount}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => {
setSelectedAccount(e.target.value);
setBatchLocations([]);
setBatchLocation(null);
}}
>
<option value="">选择账号</option>
{accounts.map(/* 当前回调处理集合中的单个元素。 */ acc => <option key={acc.id} value={acc.id}>{accountName(acc.id)}</option>)}
</select>
<p className="text-xs text-gray-500">表格中“账号ID”为空时,会使用这里选择的账号。</p>
</div>
<div className="rounded-xl border border-amber-200 bg-amber-50/70 p-4 space-y-3">
<div>
<div className="text-sm font-extrabold text-gray-900">默认类目 <span className="font-medium text-gray-500">(可为空)</span></div>
<p className="mt-1 text-xs leading-5 text-amber-800">填写后优先使用该类目;留空时由闲鱼根据每件商品自动识别。仍无法识别时,系统最终使用“电子资料”兜底。</p>
</div>
<div className="flex flex-col gap-2 sm:flex-row">
<label className="relative flex-1">
<span className="sr-only">类目关键词</span>
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
<input
className="w-full ios-input rounded-xl bg-white py-2.5 pl-10 pr-3"
placeholder="输入关键词,例如:课程资料、设计素材"
value={batchCategoryKeyword}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setBatchCategoryKeyword(e.target.value)}
onKeyDown={/* 当前回调处理用户交互或异步状态变化。 */ e => {
if (e.key === 'Enter') {
e.preventDefault();
void handleRecommendBatchCategory();
}
}}
/>
</label>
<button
type="button"
disabled={!selectedAccount || !batchCategoryKeyword.trim() || batchCategoryLoading}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void handleRecommendBatchCategory()}
className="ios-btn-primary flex min-h-[42px] items-center justify-center gap-2 rounded-xl px-4 text-sm font-bold disabled:opacity-50"
>
<Search className="h-4 w-4" />
{batchCategoryLoading ? '匹配中...' : '获取类目'}
</button>
</div>
{batchFallbackCategory.catId ? (
<div className="flex min-h-[46px] items-center justify-between gap-3 border-t border-amber-200 pt-3">
<div className="min-w-0">
<div className="flex items-center gap-2 text-sm font-bold text-gray-900">
<CheckCircle2 className="h-4 w-4 shrink-0 text-emerald-600" />
<span className="truncate">{batchFallbackCategory.catName}</span>
</div>
<div className="mt-1 font-mono text-xs text-gray-500">类目 {batchFallbackCategory.catId} · 频道 {batchFallbackCategory.channelCatId}</div>
</div>
<button
type="button"
title="清除默认类目"
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setBatchFallbackCategory({ catId: '', catName: '', channelCatId: '', tbCatId: '' })}
className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg text-gray-500 hover:bg-white hover:text-gray-900"
>
<X className="h-4 w-4" />
</button>
</div>
) : null}
</div>
<div className="rounded-xl border border-sky-200 bg-sky-50 p-4 space-y-3">
<div className="flex items-center justify-between gap-3">
<div><div className="text-sm font-extrabold text-gray-900">批次发货地(可选)</div><p className="mt-1 text-xs text-sky-800">虚拟商品可留空;填写后整个批次使用同一个发货地,并随任务保存用于恢复和重试。</p></div>
<button type="button" disabled={locationLoading || !selectedAccount} onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void locateForPublish(true)} className="ios-btn-primary flex items-center gap-2 rounded-xl px-4 py-2 text-sm font-bold disabled:opacity-50">
<LocateFixed className="h-4 w-4" />{locationLoading ? '定位中...' : '获取当前位置'}
</button>
</div>
{batchLocations.length > 0 && <select className="w-full ios-input rounded-xl bg-white px-4 py-3" value={String(Math.max(0, batchLocations.indexOf(batchLocation!)))} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setBatchLocation(batchLocations[Number(e.target.value)] || null)}>
{batchLocations.map(/* 当前回调处理集合中的单个元素。 */ (item, index) => <option key={`${item.division_id}-${item.poi_id}-${index}`} value={String(index)}>{[item.province, item.city, item.area, item.poi_name].filter(Boolean).join(' ')}</option>)}
</select>}
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<label className="flex min-h-[150px] cursor-pointer flex-col items-center justify-center rounded-2xl border-2 border-dashed border-gray-200 bg-gray-50 px-4 py-6 text-center hover:border-blue-300 hover:bg-blue-50 transition-colors">
<UploadCloud className="w-9 h-9 text-blue-600 mb-3" />
<span className="text-sm font-extrabold text-gray-900">上传商品表格</span>
<span className="text-xs text-gray-500 mt-1">{batchFile ? batchFile.name : '支持 .xlsx / .csv / .tsv'}</span>
<input
className="hidden"
type="file"
accept=".xlsx,.csv,.tsv"
onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setBatchFile(e.target.files?.[0] || null)}
/>
</label>
<label className="flex min-h-[150px] cursor-pointer flex-col items-center justify-center rounded-2xl border-2 border-dashed border-gray-200 bg-gray-50 px-4 py-6 text-center hover:border-emerald-300 hover:bg-emerald-50 transition-colors">
<UploadCloud className="w-9 h-9 text-emerald-600 mb-3" />
<span className="text-sm font-extrabold text-gray-900">上传图片 zip(可选)</span>
<span className="text-xs text-gray-500 mt-1">{batchImagesZip ? batchImagesZip.name : '表格图片字段使用 zip 内相对路径'}</span>
<input
className="hidden"
type="file"
accept=".zip"
onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setBatchImagesZip(e.target.files?.[0] || null)}
/>
</label>
</div>
<div className="rounded-2xl bg-gray-50 border border-gray-100 p-4 space-y-3">
<div>
<div className="text-sm font-extrabold text-gray-900">字段说明</div>
<p className="text-xs text-gray-500 mt-1">照着下面的“什么时候填写”处理即可。预检发现问题时,会指出具体哪一行需要修改。</p>
</div>
<div className="rounded-xl border border-blue-100 bg-blue-50 p-4 text-xs text-blue-950">
<div className="text-sm font-extrabold">“付款后发送的卡密”怎么填</div>
<div className="mt-3 grid grid-cols-1 gap-3 lg:grid-cols-3">
<div className="rounded-lg bg-white/80 p-3">
<code className="font-bold text-blue-700">101</code>
<p className="mt-1 leading-5">从卡密组 101 立即发送 1 份。卡密组 ID 可以在“卡密库存”页面查看。</p>
</div>
<div className="rounded-lg bg-white/80 p-3">
<code className="font-bold text-blue-700">101:2</code>
<p className="mt-1 leading-5">每购买 1 件,就从卡密组 101 发送 2 份。买家购买 3 件时会发送 6 份。</p>
</div>
<div className="rounded-lg bg-white/80 p-3">
<code className="font-bold text-blue-700">101:1:0;102:2:3</code>
<p className="mt-1 leading-5">先立即发送卡密组 101 的 1 份,再等待 3 秒发送卡密组 102 的 2 份。</p>
</div>
</div>
<p className="mt-3 leading-5 text-blue-800">
每一组依次写“卡密组 ID : 每件发送几份 : 等待几秒”。份数不写时按 1 份处理,等待时间不写时立即发送。需要发送多种卡密时,用英文分号 <code className="font-bold">;</code> 隔开。
</p>
</div>
<div className="overflow-x-auto rounded-xl border border-gray-100 bg-white">
<table className="w-full text-left text-xs">
<thead className="bg-gray-50 text-gray-500">
<tr>
<th className="px-3 py-2">字段</th>
<th className="px-3 py-2">什么时候填写</th>
<th className="px-3 py-2">填写方法</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-50 text-gray-700">
{[
['账号ID', '需要覆盖默认账号时填写', '上方默认发布账号为必选;本列留空时使用默认账号,填写后仅覆盖当前行'],
['标题', '每个商品都要填', '填写买家能看到的商品标题'],
['描述', '可以留空', '留空时会使用商品标题作为描述'],
['价格', '每个商品都要填', '只填数字,例如 19.90'],
['原价', '可以留空', '需要展示划线原价时填写,例如 29.90'],
['库存', '可以留空', '留空按 1 件处理;填写时必须大于 0'],
['邮费模式', '可以留空', '留空表示包邮;包邮填 free,固定邮费填 fixed'],
['邮费', '邮费模式填 fixed 时填写', '只填数字,例如 8.00'],
['图片', '每个商品都要填', '填写 zip 内图片路径或图片网址;多张图片用英文分号隔开'],
['类目ID', '需要指定当前行默认类目时填写', '必须和“类目名称、频道类目ID”同时填写;优先于自动识别'],
['类目名称', '填写了“类目ID”时必填', '填写该 ID 对应的准确类目名称'],
['频道类目ID', '覆盖类目时必填', '必须填写闲鱼返回的准确频道类目 ID'],
['淘宝类目ID', '按闲鱼返回填写', '“电子资料”无淘宝类目 ID,保持为空'],
['付款发货启用', '需要付款后自动发货时填写', '填“是”表示开启;不需要时填“否”或留空'],
['付款发货内容', '“付款发货启用”填“是”时填写', '从“卡密库存”页面取得卡密组 ID,按上方示例填写'],
['评价赠品启用', '需要评价赠品时填写', '填“是”表示开启;不需要时填“否”或留空'],
['评价赠品内容', '“评价赠品启用”填“是”时填写', '格式和付款发货内容相同,也可以同时发送多个卡密组'],
['求评价启用', '需要自动求评价时填写', '填“是”表示开启;不需要时填“否”或留空'],
['求评价等待小时', '“求评价启用”填“是”时填写', '填写等待小时数;留空按 72 小时处理'],
['求评价文案', '“求评价启用”填“是”时填写', '填写要发送给买家的求评价消息'],
['求评价最多次数', '可以留空', '留空只提醒 1 次'],
].map(/* 当前回调处理用户交互或异步状态变化。 */ ([name, when, desc]) => (
<tr key={name}>
<td className="px-3 py-2 font-bold text-gray-900 whitespace-nowrap">{name}</td>
<td className={`px-3 py-2 min-w-[210px] font-bold ${when === '每个商品都要填' ? 'text-red-600' : when === '可以留空' ? 'text-gray-500' : 'text-amber-700'}`}>{when}</td>
<td className="px-3 py-2 min-w-[260px]">{desc}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</div>
)}
{batchPhase === 'preview' && batchPreview && (
<div className="space-y-4">
<div className="grid grid-cols-3 gap-3">
<div className="rounded-2xl bg-gray-50 p-4 border border-gray-100">
<div className="text-xs font-bold text-gray-500">总行数</div>
<div className="text-2xl font-extrabold text-gray-900 mt-1">{batchPreview.total}</div>
</div>
<div className="rounded-2xl bg-emerald-50 p-4 border border-emerald-100">
<div className="text-xs font-bold text-emerald-700">可发布</div>
<div className="text-2xl font-extrabold text-emerald-700 mt-1">{batchPreview.valid}</div>
</div>
<div className="rounded-2xl bg-red-50 p-4 border border-red-100">
<div className="text-xs font-bold text-red-700">有问题</div>
<div className="text-2xl font-extrabold text-red-700 mt-1">{batchPreview.invalid}</div>
</div>
</div>
<div className="max-h-[380px] overflow-y-auto rounded-2xl border border-gray-100">
<table className="w-full text-left text-sm">
<thead className="sticky top-0 bg-white text-xs text-gray-400 border-b border-gray-100">
<tr>
<th className="px-4 py-3">行号</th>
<th className="px-4 py-3">状态</th>
<th className="px-4 py-3">标题</th>
<th className="px-4 py-3">价格/库存</th>
<th className="px-4 py-3">类目策略</th>
<th className="px-4 py-3">图片</th>
<th className="px-4 py-3">问题</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-50">
{batchPreview.rows.map(/* 当前回调处理集合中的单个元素。 */ row => (
<tr key={row.row_no} className="hover:bg-gray-50">
<td className="px-4 py-3 font-mono text-xs">{row.row_no}</td>
<td className="px-4 py-3">
<span className={`inline-flex px-2 py-1 rounded-lg border text-xs font-extrabold ${row.valid ? 'bg-emerald-50 text-emerald-700 border-emerald-100' : 'bg-red-50 text-red-700 border-red-100'}`}>
{row.valid ? '可发布' : '需修正'}
</span>
</td>
<td className="px-4 py-3 font-bold text-gray-900 max-w-[240px] truncate">{row.title || '-'}</td>
<td className="px-4 py-3 text-gray-600">¥{row.price || '-'} / {row.quantity || 1}</td>
<td className="px-4 py-3 text-xs text-gray-600 min-w-[150px]">
<div className="font-bold text-gray-800">{row.category?.cat_name || '自动识别'}</div>
<div className="font-mono text-gray-400">{row.category?.cat_id || '失败后使用电子资料'}</div>
</td>
<td className="px-4 py-3 text-gray-600">{row.images?.length || 0} 张</td>
<td className="px-4 py-3 text-red-600 text-xs max-w-[280px]">{row.errors?.join(';') || '-'}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)}
{(batchPhase === 'running' || batchPhase === 'done') && batchDetail && (
<div className="space-y-4">
<div className="grid grid-cols-2 md:grid-cols-5 gap-3">
<div className={`rounded-2xl p-4 border ${batchStatusClass(batchDetail.status)}`}>
<div className="text-xs font-bold opacity-70">任务状态</div>
<div className="text-xl font-extrabold mt-1">{batchStatusText(batchDetail.status)}</div>
</div>
<div className="rounded-2xl bg-gray-50 p-4 border border-gray-100">
<div className="text-xs font-bold text-gray-500">总数</div>
<div className="text-xl font-extrabold text-gray-900 mt-1">{batchDetail.total}</div>
</div>
<div className="rounded-2xl bg-emerald-50 p-4 border border-emerald-100">
<div className="text-xs font-bold text-emerald-700">成功</div>
<div className="text-xl font-extrabold text-emerald-700 mt-1">{batchDetail.success}</div>
</div>
<div className="rounded-2xl bg-red-50 p-4 border border-red-100">
<div className="text-xs font-bold text-red-700">失败</div>
<div className="text-xl font-extrabold text-red-700 mt-1">{batchDetail.failed}</div>
</div>
<div className="rounded-2xl bg-blue-50 p-4 border border-blue-100">
<div className="text-xs font-bold text-blue-700">等待</div>
<div className="text-xl font-extrabold text-blue-700 mt-1">{batchDetail.pending}</div>
</div>
</div>
<div className="max-h-[420px] overflow-y-auto rounded-2xl border border-gray-100">
<table className="w-full text-left text-sm">
<thead className="sticky top-0 bg-white text-xs text-gray-400 border-b border-gray-100">
<tr>
<th className="px-4 py-3">行号</th>
<th className="px-4 py-3">状态</th>
<th className="px-4 py-3">标题</th>
<th className="px-4 py-3">类目策略</th>
<th className="px-4 py-3">商品ID</th>
<th className="px-4 py-3">错误原因</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-50">
{batchDetail.rows.map(/* 当前回调处理集合中的单个元素。 */ row => (
<tr key={row.id} className="hover:bg-gray-50">
<td className="px-4 py-3 font-mono text-xs">{row.row_no}</td>
<td className="px-4 py-3">
<span className={`inline-flex px-2 py-1 rounded-lg border text-xs font-extrabold ${batchStatusClass(row.status)}`}>
{batchStatusText(row.status)}
</span>
</td>
<td className="px-4 py-3 font-bold text-gray-900 max-w-[260px] truncate">{row.title}</td>
<td className="px-4 py-3 text-xs text-gray-600 min-w-[150px]">
<div className="font-bold text-gray-800">{row.category?.cat_name || '自动识别'}</div>
<div className="font-mono text-gray-400">{row.category?.cat_id || '失败后使用电子资料'}</div>
</td>
<td className="px-4 py-3 text-xs font-mono">
{row.item_url ? <a href={row.item_url} target="_blank" rel="noreferrer" className="text-blue-600 hover:underline">{row.item_id}</a> : (row.item_id || '-')}
</td>
<td className="px-4 py-3 text-red-600 text-xs max-w-[340px]">{row.error_message || '-'}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)}
</div>
<div className="modal-footer">
{batchPhase === 'upload' && (
<button disabled={batchLoading || !batchFile || !selectedAccount} onClick={handlePreviewBatch} className="w-full ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2 disabled:opacity-50">
<RefreshCw className={`w-4 h-4 ${batchLoading ? 'animate-spin' : ''}`} />
{batchLoading ? '正在预检...' : '开始预检'}
</button>
)}
{batchPhase === 'preview' && batchPreview && (
<div className="flex gap-3 w-full">
<button disabled={batchLoading} onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void abandonBatchPreview()} className="flex-1 px-6 py-3.5 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold">
返回修改
</button>
<button disabled={batchLoading || batchPreview.valid <= 0} onClick={handleStartBatch} className="flex-1 ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2 disabled:opacity-50">
<PackagePlus className="w-4 h-4" />
{batchLoading ? '启动中...' : `确认发布 ${batchPreview.valid} 个商品`}
</button>
</div>
)}
{(batchPhase === 'running' || batchPhase === 'done') && batchDetail && (
<div className="flex gap-3 w-full">
{batchDetail.status === 'running' ? (
<button disabled={batchLoading} onClick={handleCancelBatch} className="flex-1 px-6 py-3.5 rounded-xl bg-gray-900 text-white hover:bg-black font-bold">
取消任务
</button>
) : batchDetail.status === 'canceling' ? (
<button disabled className="flex-1 px-6 py-3.5 rounded-xl bg-amber-100 text-amber-800 font-bold">
正在保存远端结果并安全取消…
</button>
) : (
<button onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => window.open(`/api/v1/items/publish-batches/${batchDetail.id}/result.csv`, '_blank')} className="flex-1 px-6 py-3.5 rounded-xl bg-gray-900 text-white hover:bg-black font-bold">
下载结果
</button>
)}
{batchDetail.retryable > 0 && !['running', 'canceling'].includes(batchDetail.status) && (
<button disabled={batchLoading} onClick={handleRetryBatchFailed} className="flex-1 ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2">
<RefreshCw className={`w-4 h-4 ${batchLoading ? 'animate-spin' : ''}`} />
重试失败项
</button>
)}
{!['running', 'canceling'].includes(batchDetail.status) && (
<button onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => { setShowBatchModal(false); loadItems(); loadShippingRules(); }} className="flex-1 px-6 py-3.5 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold">
完成
</button>
)}
</div>
)}
</div>
</div>
</div>
, document.body)}
</div>
);
};
export default ItemList;
+1 -1
View File
@@ -1,5 +1,5 @@
import type { Dispatch, SetStateAction } from 'react';
import type { Item, AccountDetail, ShippingRule } from '../../../types';
import type { Item, AccountDetail, ShippingRule } from '../../../shared/api-contract';
import type { PublishLocation } from './api';
// ItemListProps 描述商品页面从父级接收的规则配置回调。
+133 -10
View File
@@ -1,11 +1,134 @@
export {
createNotificationChannel,
deleteNotificationChannel,
getNotificationChannels,
getSystemSettings,
testNotificationChannel,
updateNotificationChannel,
updateSystemSettings,
} from '../../../services/api';
import { del, get, post, put, type RequestControlOptions } from '../../../shared/http/client';
import type { MutationIDResponse, NotificationBinding, NotificationChannel, NotificationChannelResponse, NotificationEventType, OperationResponse, SystemSettings } from '../../../shared/api-contract';
// notifications feature 通过本适配层声明渠道和 SMTP API 的来源。
/** 通知渠道写入时使用的具名请求 DTO。 */
export interface NotificationChannelRequest {
/** 管理界面展示的渠道名称。 */
name?: string;
/** 后端支持的渠道类型。 */
type?: string;
/** 由各渠道表单构造的非敏感配置。 */
config?: Record<string, unknown>;
/** 需要订阅的系统事件。 */
event_types?: NotificationEventType[];
/** 渠道是否参与通知投递。 */
enabled?: boolean;
}
/** 将后端字符串或历史分隔文本转换为稳定事件类型列表。 */
const parseNotificationEventTypes = (raw: unknown): NotificationEventType[] => {
if (Array.isArray(raw)) return raw.filter(Boolean) as NotificationEventType[];
if (typeof raw !== 'string' || !raw.trim()) return [];
try {
// parsed 是解析后的历史 JSON 事件列表。
const parsed: unknown = JSON.parse(raw);
if (Array.isArray(parsed)) return parsed.filter(Boolean) as NotificationEventType[];
} catch {
// 非 JSON 历史值继续按分隔符兼容解析。
}
return raw.split(/[,\s;]+/).map(value => value.trim()).filter(Boolean) as NotificationEventType[];
};
/** 将事件类型列表序列化为后端稳定保存的 JSON 文本。 */
const stringifyNotificationEventTypes = (eventTypes?: NotificationEventType[]): string => {
// uniqueTypes 是去重且去除空值后的事件列表。
const uniqueTypes = Array.from(new Set((eventTypes || []).filter(Boolean)));
return uniqueTypes.length > 0 ? JSON.stringify(uniqueTypes) : '';
};
/** 把后端渠道 DTO 转换为通知编辑器使用的 UI 模型。 */
const toNotificationChannel = (channel: NotificationChannelResponse): NotificationChannel => {
// config 是解析失败时降级为空对象的渠道配置。
let config: Record<string, unknown> = {};
try {
// parsed 是配置文本解析后的未知 JSON 值。
const parsed: unknown = typeof channel.config === 'string' ? JSON.parse(channel.config) : channel.config;
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) config = parsed as Record<string, unknown>;
} catch {
// 历史损坏配置不阻止用户继续编辑渠道。
}
// type 是处理 ding_talk/lark 历史别名后的渠道类型。
const type = (channel.type === 'ding_talk' ? 'dingtalk' : channel.type === 'lark' ? 'feishu' : channel.type) as NotificationChannel['type'];
return { id: String(channel.id), name: channel.name, type, config, event_types: parseNotificationEventTypes(channel.event_types), enabled: channel.enabled, created_at: channel.created_at, updated_at: channel.updated_at };
};
/** 获取全部通知渠道并转换为编辑器模型。 */
export const getNotificationChannels = async (options?: RequestControlOptions): Promise<{ /** 操作是否完成。 */ success: boolean; /** 渠道列表。 */ data: NotificationChannel[] }> => {
// response 是渠道列表的原始传输响应。
const response = await get<NotificationChannelResponse[] | { /** channels 是后端包装的渠道列表。 */ data?: NotificationChannelResponse[]; /** channels 是兼容字段。 */ channels?: NotificationChannelResponse[] }>('/api/v1/notifications/channels', undefined, options);
// channels 是兼容直接数组与包装数组后的原始渠道列表。
const channels = Array.isArray(response) ? response : response.data || response.channels || [];
return { success: true, data: channels.map(toNotificationChannel) };
};
/** 创建通知渠道,并在传输边界序列化配置与事件。 */
export const createNotificationChannel = async (data: Required<Pick<NotificationChannelRequest, 'name' | 'type' | 'config'>> & NotificationChannelRequest, options?: RequestControlOptions): Promise<MutationIDResponse> => post('/api/v1/notifications/channels', { ...data, config: JSON.stringify(data.config), event_types: stringifyNotificationEventTypes(data.event_types) }, options);
/** 更新通知渠道的可编辑字段。 */
export const updateNotificationChannel = async (channelID: string, data: NotificationChannelRequest, options?: RequestControlOptions): Promise<OperationResponse> => {
// payload 是已完成配置和事件序列化的更新请求。
const payload: Record<string, unknown> = { ...data };
if ('config' in data) payload.config = JSON.stringify(data.config);
if ('event_types' in data) payload.event_types = stringifyNotificationEventTypes(data.event_types);
return put(`/api/v1/notifications/channels/${channelID}`, payload, options);
};
/** 删除指定通知渠道。 */
export const deleteNotificationChannel = async (channelID: string, options?: RequestControlOptions): Promise<OperationResponse> => del(`/api/v1/notifications/channels/${channelID}`, undefined, options);
/** 获取并展平按账号分组存储的消息通知绑定。 */
export const getMessageNotifications = async (): Promise<{ /** 操作是否完成。 */ success: boolean; /** 展平后的绑定列表。 */ data: NotificationBinding[] }> => {
// response 是按账号 ID 分组的通知绑定响应。
const response = await get<Record<string, NotificationBinding[]>>('/api/v1/notifications/messages');
// bindings 是供页面直接渲染的扁平绑定集合。
const bindings: NotificationBinding[] = [];
for (const /* accountID、channelBindings 是当前账号及其原始渠道绑定列表。 */ [accountID, channelBindings] of Object.entries(response || {})) {
if (!Array.isArray(channelBindings)) continue;
for (const /* binding 是当前待展平的单个账号渠道绑定。 */ binding of channelBindings) bindings.push({ ...binding, cookie_id: accountID });
}
return { success: true, data: bindings };
};
/** 设置单个账号与渠道之间的启用状态。 */
export const setMessageNotification = async (accountID: string, channelID: number, enabled: boolean): Promise<OperationResponse> => post(`/api/v1/notifications/accounts/${accountID}/bindings`, { channel_id: channelID, enabled });
/** 删除单个消息通知绑定。 */
export const deleteMessageNotification = async (notificationID: string): Promise<OperationResponse> => del(`/api/v1/notifications/messages/${notificationID}`);
/** 删除指定账号的全部消息通知绑定。 */
export const deleteAccountNotifications = async (accountID: string): Promise<OperationResponse> => del(`/api/v1/notifications/messages/account/${accountID}`);
/** 读取指定账号已绑定的通知渠道主键。 */
export const getAccountBindings = async (accountID: string, options?: RequestControlOptions): Promise<number[]> => {
// response 是账号渠道绑定的具名响应。
const response = await get<{ /** channelIDs 是绑定渠道主键集合。 */ channel_ids?: number[]; /** data 是兼容包装。 */ data?: { /** channelIDs 是绑定渠道主键集合。 */ channel_ids?: number[] } }>(`/api/v1/notifications/accounts/${accountID}/bindings`, undefined, options);
return Array.isArray(response.channel_ids) ? response.channel_ids : Array.isArray(response.data?.channel_ids) ? response.data.channel_ids : [];
};
/** 覆盖保存指定账号的通知渠道绑定。 */
export const setAccountBindings = async (accountID: string, channelIDs: number[]): Promise<OperationResponse> => post(`/api/v1/notifications/accounts/${accountID}/bindings`, { channel_ids: channelIDs });
/** 向单一通知渠道发送测试投递。 */
export const testNotificationChannel = async (channelID: string, options?: RequestControlOptions): Promise<OperationResponse> => post(`/api/v1/notifications/channels/${channelID}/test`, {}, options);
/** 将系统配置响应转换为通知 SMTP 表单使用的状态模型。 */
const normalizeSystemSettings = (settings: Record<string, unknown>): SystemSettings => {
// result 是不改变原始响应对象的设置副本。
const result: Record<string, unknown> = { ...settings };
if ('renewal_log_retention_days' in result) {
// days 是已校验的日志保留天数。
const days = Number(result.renewal_log_retention_days);
result.renewal_log_retention_days = Number.isFinite(days) ? days : 10;
}
return result as SystemSettings;
};
/** 获取通知 SMTP 编辑器需要的系统设置。 */
export const getSystemSettings = async (options?: RequestControlOptions): Promise<SystemSettings> => {
// response 是服务端可能以 data 包装的系统设置响应。
const response = await get<{ /** data 是当前服务端系统设置。 */ data?: Record<string, unknown>; /** settings 是兼容字段。 */ settings?: Record<string, unknown> } & Record<string, unknown>>('/api/v1/settings/system', undefined, options);
return normalizeSystemSettings(response.data || response.settings || response);
};
/** 保存通知 SMTP 编辑器提交的系统设置。 */
export const updateSystemSettings = async (settings: Partial<SystemSettings>, options?: RequestControlOptions): Promise<OperationResponse> => put('/api/v1/settings/system', settings, options);
@@ -1,6 +1,6 @@
import React from 'react';
import { Bell, Edit2, Loader2, Send, Trash2 } from 'lucide-react';
import type { NotificationChannel } from '../../../../types';
import type { NotificationChannel } from '../../../../shared/api-contract';
import { notificationChannelTypes, notificationEventSummary } from '../state';
// NotificationChannelListProps 描述通知渠道列表的操作边界。
@@ -4,7 +4,7 @@ import { Bell, Check, Eye, EyeOff, Loader2, X } from 'lucide-react';
import { enableCustomSMTP } from '../../../../notificationEmailConfig';
import { notificationChannelTypes } from '../state';
import { NotificationEventSelector } from './NotificationEventSelector';
import type { NotificationChannel, NotificationChannelType, NotificationEventType, SystemSettings } from '../../../../types';
import type { NotificationChannel, NotificationChannelType, NotificationEventType, SystemSettings } from '../../../../shared/api-contract';
import type { NotificationForm } from '../types';
// NotificationChannelModalProps 描述渠道编辑弹窗所需的状态和回调。
@@ -1,7 +1,7 @@
import React from 'react';
import { Check } from 'lucide-react';
import { notificationEvents } from '../state';
import type { NotificationEventType } from '../../../../types';
import type { NotificationEventType } from '../../../../shared/api-contract';
// NotificationEventSelectorProps 描述通知事件绑定组件的输入状态。
export interface NotificationEventSelectorProps {
@@ -1,6 +1,6 @@
import React from 'react';
import { Eye, EyeOff, Loader2, Mail, Save } from 'lucide-react';
import type { SystemSettings } from '../../../../types';
import type { SystemSettings } from '../../../../shared/api-contract';
// NotificationSmtpSettingsProps 描述系统 SMTP 配置面板所需的状态和事件。
export interface NotificationSmtpSettingsProps {
@@ -1,7 +1,7 @@
// @vitest-environment jsdom
import { act, renderHook, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, test, vi } from 'vitest';
import type { NotificationChannel, SystemSettings } from '../../../types';
import type { NotificationChannel, SystemSettings } from '../../../shared/api-contract';
import { createNotificationChannel, deleteNotificationChannel, getNotificationChannels, getSystemSettings, testNotificationChannel, updateNotificationChannel, updateSystemSettings } from './api';
import { useNotifications } from './hooks';
+1 -1
View File
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import type { NotificationChannel, NotificationChannelType, SystemSettings } from '../../../types';
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';
@@ -0,0 +1,44 @@
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';
import { useNotifications } from '../hooks';
// NotificationsProps 描述通知页面接收的权限上下文。
interface NotificationsProps {
// isAdmin 表示当前用户是否可以查看和保存系统 SMTP 配置。
isAdmin?: boolean;
}
// Notifications 渲染通知渠道列表、SMTP 配置和渠道编辑边界。
const Notifications: React.FC<NotificationsProps> = ({ isAdmin = false }) => {
// notificationState 统一提供通知页面的数据、表单和异步动作。
const notificationState = useNotifications(isAdmin);
return (
<div className="space-y-8 animate-fade-in">
<div className="flex flex-col md:flex-row justify-between md:items-end gap-4">
<div><h2 className="text-4xl font-extrabold text-gray-900 tracking-tight">通知设置</h2><p className="text-gray-500 mt-2 font-medium">配置通知渠道,账号异常时主动推送告警</p></div>
<div className="flex items-center gap-3">
<button onClick={notificationState.loadChannels} className="px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 transition-colors"><RefreshCw className="w-4 h-4" />刷新</button>
<button onClick={notificationState.openCreate} className="ios-btn-primary px-5 py-2.5 rounded-xl font-bold flex items-center gap-2"><Plus className="w-4 h-4" />新建渠道</button>
</div>
</div>
<div className="ios-card rounded-xl p-5 bg-blue-50/50 border border-blue-100">
<div className="flex items-start gap-3"><Bell className="w-5 h-5 text-brand mt-0.5 flex-shrink-0" /><div className="text-sm text-gray-700 leading-6">配置通知渠道并在「账号管理 → 编辑」里绑定后,以下事件会主动推送到该账号绑定的渠道:<ul className="mt-2 space-y-1 text-gray-600"><li>• <strong>账号 session 失效</strong>:系统正在尝试自动恢复(警告)</li><li>• <strong>自动恢复失败</strong>:账号已停止,需人工处理(严重)</li><li>• <strong>触发风控验证</strong>:可能需要扫码完成验证(警告)</li></ul></div></div>
</div>
{notificationState.loading ? <div className="flex justify-center py-20"><Loader2 className="w-8 h-8 text-brand animate-spin" /></div> : <NotificationChannelList channels={notificationState.channels} testingId={notificationState.testingId} onEdit={notificationState.openEdit} onDelete={notificationState.handleDelete} onToggleEnabled={notificationState.handleToggleEnabled} onTest={notificationState.handleTest} />}
{isAdmin && <NotificationSmtpSettings smtp={notificationState.smtp} setSmtp={notificationState.setSmtp} smtpSaving={notificationState.smtpSaving} showPassword={notificationState.showSmtpPassword} setShowPassword={notificationState.setShowSmtpPassword} onSave={notificationState.handleSaveSmtp} />}
<NotificationChannelModal showModal={notificationState.showModal} editing={notificationState.editing} form={notificationState.form} setForm={notificationState.setForm} smtp={notificationState.smtp} showChannelSmtpPassword={notificationState.showChannelSmtpPassword} setShowChannelSmtpPassword={notificationState.setShowChannelSmtpPassword} saving={notificationState.saving} onClose={notificationState.closeModal} onSave={notificationState.handleSave} />
{notificationState.toast && <div className={`fixed bottom-8 left-1/2 -translate-x-1/2 z-[10000] px-5 py-3 rounded-xl shadow-lg font-bold text-sm flex items-center gap-2 animate-fade-in text-white ${notificationState.toast.type === 'success' ? 'bg-success-500' : 'bg-danger-500'}`}>{notificationState.toast.type === 'success' ? <Check className="w-4 h-4" /> : <X className="w-4 h-4" />}{notificationState.toast.text}</div>}
</div>
);
};
export default Notifications;
@@ -1,5 +1,5 @@
import { expect, test } from 'vitest';
import type { NotificationChannel } from '../../../types';
import type { NotificationChannel } from '../../../shared/api-contract';
import type { NotificationForm } from './types';
import { buildNotificationPayload, emptyNotificationForm, isCurrentNotificationRequest, normalizeNotificationForm, notificationErrorMessage, notificationEventSummary, validateNotificationForm } from './state';
+1 -1
View File
@@ -1,5 +1,5 @@
import { Bell, Mail, MessageCircle, Send as Telegram, Webhook } from 'lucide-react';
import type { NotificationChannel, NotificationChannelType, NotificationEventType, SystemSettings } from '../../../types';
import type { NotificationChannel, NotificationChannelType, NotificationEventType, SystemSettings } from '../../../shared/api-contract';
import { buildEmailChannelConfig, enableCustomSMTP, normalizeEmailChannelConfig } from '../../../notificationEmailConfig';
import type { NotificationChannelMeta, NotificationEventMeta, NotificationForm, NotificationPayload } from './types';
+1 -1
View File
@@ -1,5 +1,5 @@
import type { Dispatch, ElementType, SetStateAction } from 'react';
import type { NotificationChannel, NotificationChannelType, NotificationEventType, SystemSettings } from '../../../types';
import type { NotificationChannel, NotificationChannelType, NotificationEventType, SystemSettings } from '../../../shared/api-contract';
// NotificationField 描述通知渠道表单中的一个配置字段。
export interface NotificationField {
+165 -12
View File
@@ -1,13 +1,166 @@
export {
deleteOrder,
getAccountDetails,
getItems,
getOrders,
importOrders,
manualShipOrder,
syncOrders,
syncSingleOrder,
updateOrder,
} from '../../../services/api';
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';
// 订单 feature 通过本文件声明服务 API 来源,页面不再直接依赖通用 API 模块。
/** 订单筛选器读取非敏感账号摘要。 */
export const getAccountDetails = async (options?: RequestControlOptions): Promise<AccountDetail[]> => get('/api/v1/accounts/details', undefined, options);
/** 订单关联商品展示读取当前商品索引。 */
export const getItems = async (accountID?: string, options?: RequestControlOptions): Promise<Item[]> => get('/api/v1/items', accountID ? { cookie_id: accountID } : undefined, options);
/** 管理员统计仍由订单域兼容 API 提供给历史管理页面。 */
export const getAdminStats = async (): Promise<AdminStatsResponse> => get('/api/v1/admin/stats');
// Orders
// normalizeOrderStatus 归一化订单状态。
const normalizeOrderStatus = (value: unknown): Order['status'] => {
// status 状态值,用于当前 API 处理流程。
const status = String(value || '');
if (status === 'paid') return 'pending_ship';
return ['processing', 'pending_ship', 'shipped', 'completed', 'cancelled', 'refunding'].includes(status)
? status as Order['status']
: 'unknown';
};
// getOrders 读取订单列表。
export const getOrders = async (
cookieId?: string,
status?: string,
page: number = 1,
pageSize: number = 20,
search?: string,
options?: RequestControlOptions,
): Promise<PaginatedResponse<Order>> => {
// params 请求参数,用于当前 API 处理流程。
const params: any = { page, page_size: pageSize };
if (cookieId) params.cookie_id = cookieId;
if (status && status !== 'all') params.status = status;
if (search?.trim()) params.search = search.trim();
// res 接口响应结果,用于当前 API 处理流程。
const response = await get<unknown>('/api/v1/orders', params, options);
// res 是兼容直接分页对象、orders 别名和 data 包裹后的订单响应。
const res = objectFrom<Partial<PaginatedResponse<Order>> & { /** orders 是历史订单列表字段别名。 */ orders?: Order[] }>(response, ['data', 'result']) || {};
// Handle backend response variations
// rawOrders 原始订单列表,用于当前 API 处理流程。
const rawOrders = Array.isArray(res.orders) ? res.orders : collectionFrom<Order>(res.data, ['data', 'orders', 'items']);
// orders 订单列表,用于当前 API 处理流程。
const orders = rawOrders.map(/* 当前回调用于处理集合元素或接口响应。 */ (item: any) => ({
...item,
id: item.id || item.order_id,
status: normalizeOrderStatus(item.status || item.order_status),
quantity: Number(item.quantity || 1),
}));
return {
success: true,
data: orders,
total: res.total || orders.length,
page: res.page || page,
page_size: res.page_size || pageSize,
total_pages: res.total_pages || 1
};
};
// getOrderDetail 读取订单详情。
export const getOrderDetail = async (orderId: string): Promise<{ /** success 表示是否成功。 */ success: boolean; /** data 表示数据。 */ data?: OrderDTOResponse }> => {
// result 接口响应结果,用于当前 API 处理流程。
const result = await get<OrderDetailResponse>(`/api/v1/orders/${orderId}`);
return {
success: true,
data: result.data
};
};
// updateOrder 更新订单。
export const updateOrder = async (orderId: string, data: Partial<Order>): Promise<OperationResponse> => {
return put(`/api/v1/orders/${orderId}`, data);
};
// deleteOrder 删除订单。
export const deleteOrder = async (orderId: string): Promise<OperationResponse> => {
return del(`/api/v1/orders/${orderId}`);
};
// syncOrders 同步订单。
export const syncOrders = async (cookieId?: string, status?: string, options?: RequestControlOptions): Promise<OrderRefreshResponse> => {
// formData 表单数据,用于当前 API 处理流程。
const formData = new FormData();
if (cookieId) formData.append('cookie_id', cookieId);
if (status) formData.append('status', status);
// start 表示后台订单刷新任务创建响应。
const start = await postForm<OrderRefreshJobStartResponse>('/api/v1/orders/refresh', formData, options);
// cancelOnAbort 在调用方取消轮询时通知服务端停止同一后台任务。
const cancelOnAbort = () => {
void cancelOrderRefreshJob(start.job_id).catch(/* 取消请求失败时忽略网络错误,主请求仍按取消语义结束。 */ () => undefined);
};
options?.signal?.addEventListener('abort', cancelOnAbort, { once: true });
// pollLimit 限制前端等待后台任务的轮询次数。
const pollLimit = 180;
// pollIndex 表示当前订单刷新任务状态轮询次数。
let pollIndex = 0;
try {
while (pollIndex < pollLimit) {
// job 表示当前轮询得到的后台任务状态。
const job = await get<OrderRefreshJobStatusResponse>(`/api/v1/orders/refresh/${start.job_id}`, undefined, options);
if (job.status === 'succeeded' && job.result) {
return job.result;
}
if (job.status === 'failed' || job.status === 'cancelled') {
throw new Error(job.error_message || '订单刷新任务失败');
}
// waitMs 是下一次任务状态轮询前的等待时间。
const waitMs = 500;
await new Promise<void>(/* 轮询等待器负责等待下一次任务状态查询。 */ (resolve, reject) => {
// abort 负责响应调用方取消轮询。
const abort = () => {
globalThis.clearTimeout(timer);
reject(new Error('请求已取消'));
};
// timer 表示当前轮询等待定时器。
const timer = globalThis.setTimeout(/* 轮询完成回调清理取消监听并结束等待。 */ () => {
options?.signal?.removeEventListener('abort', abort);
resolve();
}, waitMs);
if (!options?.signal) return;
if (options.signal.aborted) abort();
else options.signal.addEventListener('abort', abort, { once: true });
});
pollIndex += 1;
}
} finally {
options?.signal?.removeEventListener('abort', cancelOnAbort);
}
throw new Error('订单刷新任务等待超时');
};
// cancelOrderRefreshJob 请求取消当前用户的订单刷新后台任务。
export const cancelOrderRefreshJob = async (jobId: string): Promise<OrderRefreshJobCancelResponse> => {
return del(`/api/v1/orders/refresh/${jobId}`);
};
// syncSingleOrder 同步单个订单。
export const syncSingleOrder = async (orderId: string): Promise<OrderSingleRefreshResponse> => {
return post(`/api/v1/orders/${orderId}/refresh`);
};
// manualShipOrder 手动发货订单。
export const manualShipOrder = async (orderIds: string[], shipMode: 'status_only' | 'full_delivery'): Promise<OrderBatchResponse> => {
return post('/api/v1/orders/manual-ship', {
order_ids: orderIds,
ship_mode: shipMode,
});
}
// importOrders 导入订单。
export const importOrders = async (data: Partial<Order>[] | FormData, options?: RequestControlOptions): Promise<OrderBatchResponse> => {
// isFormData 是否为表单请求,用于当前 API 处理流程。
const isFormData = data instanceof FormData;
return isFormData ? postForm('/api/v1/orders/import', data, options) : post('/api/v1/orders/import', data, options);
}
@@ -1,6 +1,6 @@
import React from 'react';
import { Search, User as UserIcon } from 'lucide-react';
import type { AccountDetail } from '../../../../types';
import type { AccountDetail } from '../../../../shared/api-contract';
import { orderStatusOptions } from '../state';
// OrderFilterBarProps 描述订单状态、账号和文本筛选所需的页面状态。
+34 -1
View File
@@ -1,7 +1,7 @@
// @vitest-environment jsdom
import { act, renderHook, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, test, vi } from 'vitest';
import type { AccountDetail, Item } from '../../../types';
import type { AccountDetail, Item } from '../../../shared/api-contract';
import { getAccountDetails, getItems, getOrders, importOrders } from './api';
import { useOrderImport, useOrderQuery } from './hooks';
@@ -287,4 +287,37 @@ describe('useOrderQuery 与 useOrderImport', /* 当前回调处理订单查询
expect(hook.result.current.orders).toEqual([orderFixture]);
hook.unmount();
});
test('订单导入在卸载时取消未完成上传', /* 当前回调验证导入弹窗离开页面后不会接受忽略取消信号的旧响应。 */ async () => {
// importSignal 保存导入接口收到的取消信号。
let importSignal: AbortSignal | undefined;
importOrdersMock.mockImplementation(
// pendingImport 保持文件上传未完成,以便观察 Hook 卸载时的取消行为。
(_formData, requestOptions) => {
importSignal = requestOptions?.signal;
return new Promise(/* pendingImportExecutor 故意不完成导入 Promise,直到 Hook 卸载取消请求。 */ () => undefined);
},
);
// refreshOrders 是导入成功后刷新订单列表的替身。
const refreshOrders = vi.fn().mockResolvedValue(undefined);
// hook 是订单导入 Hook 渲染结果。
const hook = renderHook(
// importHookFactory 使用稳定的列表刷新回调创建导入 Hook。
() => useOrderImport(refreshOrders),
);
await act(
// fileAction 写入符合格式要求的订单导入文件。
() => hook.result.current.setImportFile(new File(['order'], 'orders.csv')),
);
await act(
// importAction 启动上传但不等待未完成网络请求。
() => { void hook.result.current.handleImportOrders(); },
);
await waitFor(
// importStartedAssertion 等待导入请求建立取消信号。
() => expect(importSignal).toBeDefined(),
);
hook.unmount();
expect(importSignal?.aborted).toBe(true);
});
});
+13 -1
View File
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useMemo, useRef, useState, type Dispatch, type SetStateAction } from 'react';
import type { AccountDetail, Item, Order } from '../../../types';
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';
@@ -249,6 +249,18 @@ export const useOrderImport = (loadOrders: () => Promise<void>): OrderImportStat
// importAbort 保存当前导入请求的取消控制器。
const importAbort = useRef<AbortController | null>(null);
useEffect(
// 导入生命周期副作用负责在弹窗组件卸载时取消上传并禁止旧结果继续更新 React 状态。
() => (
// importRequestCleanup 推进导入代次并中止尚未结束的 multipart 请求。
() => {
importGeneration.current += 1;
importAbort.current?.abort();
}
),
[],
);
// openImportModal 打开订单导入弹窗并重置上一次结果。
const openImportModal = useCallback(
// 打开弹窗回调清理上一次导入状态。
@@ -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 { Order } from '../../../types';
import type { Order } from '../../../shared/api-contract';
import { deleteOrder, manualShipOrder, syncOrders, syncSingleOrder, updateOrder } from './api';
import { useOrderActions } from './orderActions';
+1 -1
View File
@@ -1,5 +1,5 @@
import { useCallback, useState, type Dispatch, type SetStateAction } from 'react';
import type { Order, OrderStatus } from '../../../types';
import type { Order, OrderStatus } from '../../../shared/api-contract';
import { deleteOrder, manualShipOrder, syncOrders, syncSingleOrder, updateOrder } from './api';
// OrderShipMode 表示订单发货操作的两种业务模式。
@@ -0,0 +1,194 @@
// @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 { Order } from '../../../../shared/api-contract';
// orderListMocks 保存订单页面测试使用的 Hook、API 和子组件替身。
const orderListMocks = vi.hoisted(/* orderListMockFactory 创建订单页面共享替身。 */ () => ({
orders: [] as Order[],
setFilter: vi.fn(),
setAccountFilter: vi.fn(),
setSearchText: vi.fn(),
setPage: vi.fn(),
loadOrders: vi.fn(),
openImportModal: vi.fn(),
closeImportModal: vi.fn(),
setImportFile: vi.fn(),
handleImportOrders: vi.fn(),
handleRetryImport: vi.fn(),
syncOrders: vi.fn(),
syncSingleOrder: vi.fn(),
manualShipOrder: vi.fn(),
updateOrder: vi.fn(),
deleteOrder: vi.fn(),
}));
vi.mock('../hooks', /* ordersHooksMockFactory 提供订单查询与导入 Hook 替身。 */ () => ({
useOrderQuery: /* useOrderQueryMock 返回订单页面固定查询状态。 */ () => ({
orders: orderListMocks.orders,
accounts: [{ id: 'account-1', enabled: true, auto_confirm: false, nickname: 'Alpha', remark: '主账号' }],
filter: 'all',
setFilter: orderListMocks.setFilter,
accountFilter: '',
setAccountFilter: orderListMocks.setAccountFilter,
searchText: '',
setSearchText: orderListMocks.setSearchText,
page: 2,
setPage: orderListMocks.setPage,
totalPages: 3,
loading: false,
loadOrders: orderListMocks.loadOrders,
accountName: /* accountNameMock 返回订单筛选账号名称。 */ () => '主账号 · account',
accountNickname: /* accountNicknameMock 返回订单行账号名称。 */ () => '主账号',
getItemNameById: /* itemNameMock 返回订单商品名称。 */ (_cookieId: string, _itemId: string, orderItemTitle?: string) => orderItemTitle || '测试商品',
}),
useOrderImport: /* useOrderImportMock 返回订单导入弹窗状态。 */ () => ({
showImportModal: false,
importFile: null,
setImportFile: orderListMocks.setImportFile,
importResult: null,
importing: false,
importError: '',
openImportModal: orderListMocks.openImportModal,
closeImportModal: orderListMocks.closeImportModal,
handleImportOrders: orderListMocks.handleImportOrders,
handleRetryImport: orderListMocks.handleRetryImport,
}),
}));
vi.mock('../api', /* ordersApiMockFactory 提供订单页面动作 API 替身。 */ () => ({
syncOrders: orderListMocks.syncOrders,
syncSingleOrder: orderListMocks.syncSingleOrder,
manualShipOrder: orderListMocks.manualShipOrder,
updateOrder: orderListMocks.updateOrder,
deleteOrder: orderListMocks.deleteOrder,
}));
vi.mock('../components/OrderFilterBar', /* filterBarMockFactory 提供订单筛选栏替身。 */ () => {
// OrderFilterBarMock 暴露筛选栏的状态切换和输入事件。
const OrderFilterBarMock: React.FC<any> = (props /* props 表示筛选栏状态和事件回调。 */) => (
<div data-testid="order-filter-bar">
<button onClick={/* filterAction 切换待发货筛选。 */ () => props.onFilterChange('pending_ship')}>待发货筛选</button>
<select aria-label="按账号筛选订单" value={props.accountFilter} onChange={/* accountAction 切换账号筛选。 */ event => props.onAccountFilterChange(event.target.value)}>
<option value="">全部账号</option>
<option value="account-1">主账号</option>
</select>
<input placeholder="搜索订单号/商品/买家..." value={props.searchText} onChange={/* searchAction 修改订单搜索词。 */ event => props.onSearchChange(event.target.value)} />
</div>
);
return { OrderFilterBar: OrderFilterBarMock };
});
vi.mock('../components/OrderImportModal', /* importModalMockFactory 提供订单导入弹窗替身。 */ () => ({
OrderImportModal: /* OrderImportModalMock 表示订单导入弹窗替身。 */ (props: any) => props.showImportModal ? <div data-testid="import-modal">订单导入弹窗</div> : null,
}));
import OrderList from './OrderList';
// orderFixture 表示订单页面测试中的待发货订单。
const orderFixture: Order = {
id: 'row-1',
order_id: 'order-1',
cookie_id: 'account-1',
item_id: 'item-1',
item_title: '测试商品',
item_image: '',
item_price: '10.00',
buyer_id: 'buyer-1',
quantity: 2,
amount: '20.00',
status: 'pending_ship',
receiver_name: '收货人',
receiver_phone: '13800000000',
receiver_address: '测试地址',
created_at: '2026-08-15T10:00:00Z',
};
describe('OrderList 页面组合行为', /* 当前回调验证订单筛选、编辑、发货、同步、删除和分页流程。 */ () => {
beforeEach(/* 当前回调重置订单页面 API、Hook 状态和浏览器提示替身。 */ () => {
vi.clearAllMocks();
orderListMocks.orders = [orderFixture];
orderListMocks.loadOrders.mockResolvedValue(undefined);
orderListMocks.syncOrders.mockResolvedValue({ success: true, message: '同步完成' });
orderListMocks.syncSingleOrder.mockResolvedValue({ success: true, message: '订单已同步' });
orderListMocks.manualShipOrder.mockResolvedValue({ results: [{ success: true, message: '发货成功' }] });
orderListMocks.updateOrder.mockResolvedValue({ success: true });
orderListMocks.deleteOrder.mockResolvedValue({ success: true });
vi.spyOn(window, 'alert').mockImplementation(/* alertImplementation 屏蔽订单页面提示。 */ () => undefined);
vi.spyOn(window, 'confirm').mockReturnValue(true);
});
afterEach(/* 当前回调清理订单页面 DOM 和浏览器提示替身。 */ () => {
cleanup();
vi.restoreAllMocks();
});
test('筛选栏、同步和导入按钮转发页面操作', /* 当前回调验证订单页面顶部操作组合边界。 */ async () => {
render(<OrderList />);
fireEvent.click(screen.getByText('待发货筛选'));
expect(orderListMocks.setFilter).toHaveBeenCalledWith('pending_ship');
expect(orderListMocks.setPage).toHaveBeenCalledWith(1);
expect(orderListMocks.setSearchText).toHaveBeenCalledWith('');
fireEvent.change(screen.getByLabelText('按账号筛选订单'), { target: { value: 'account-1' } });
expect(orderListMocks.setAccountFilter).toHaveBeenCalledWith('account-1');
fireEvent.change(screen.getByPlaceholderText('搜索订单号/商品/买家...'), { target: { value: 'order-1' } });
expect(orderListMocks.setSearchText).toHaveBeenCalledWith('order-1');
fireEvent.click(screen.getByText('一键同步订单'));
await waitFor(/* syncAssertion 等待订单同步 API 完成。 */ () => expect(orderListMocks.syncOrders).toHaveBeenCalledWith(undefined, 'all'));
expect(orderListMocks.loadOrders).toHaveBeenCalled();
expect(window.alert).toHaveBeenCalledWith('同步完成');
fireEvent.click(screen.getByText('插入订单'));
expect(orderListMocks.openImportModal).toHaveBeenCalledTimes(1);
});
test('订单详情和编辑保存保持字段映射', /* 当前回调验证订单详情展示和编辑提交边界。 */ async () => {
render(<OrderList />);
fireEvent.click(screen.getByTitle('查看详情'));
expect(screen.getByText('订单详情')).toBeTruthy();
fireEvent.click(screen.getByText('关闭'));
expect(screen.queryByText('订单详情')).toBeNull();
fireEvent.click(screen.getByTitle('编辑订单'));
fireEvent.change(screen.getByDisplayValue('buyer-1'), { target: { value: 'buyer-2' } });
fireEvent.change(screen.getByDisplayValue('20.00'), { target: { value: '30.00' } });
fireEvent.click(screen.getByText('保存更改'));
await waitFor(/* updateAssertion 等待订单编辑 API 完成。 */ () => expect(orderListMocks.updateOrder).toHaveBeenCalled());
expect(orderListMocks.updateOrder).toHaveBeenCalledWith('order-1', expect.objectContaining({ order_status: 'pending_ship', buyer_id: 'buyer-2', amount: '30.00' }));
expect(orderListMocks.loadOrders).toHaveBeenCalled();
});
test('发货、单笔同步和删除操作分别调用对应 API', /* 当前回调验证订单行动作和结果收束。 */ async () => {
render(<OrderList />);
fireEvent.click(screen.getByText('立即发货'));
expect(screen.getByText('请选择发货方式:')).toBeTruthy();
fireEvent.click(screen.getByText('仅修改闲鱼发货状态'));
await waitFor(/* shipAssertion 等待订单发货 API 完成。 */ () => expect(orderListMocks.manualShipOrder).toHaveBeenCalledWith(['order-1'], 'status_only'));
expect(screen.getByText('✓ 发货成功')).toBeTruthy();
expect(orderListMocks.loadOrders).toHaveBeenCalled();
fireEvent.click(screen.getByTitle('同步订单'));
await waitFor(/* singleSyncAssertion 等待单笔订单同步 API 完成。 */ () => expect(orderListMocks.syncSingleOrder).toHaveBeenCalledWith('order-1'));
expect(orderListMocks.loadOrders).toHaveBeenCalledTimes(2);
fireEvent.click(screen.getByTitle('删除订单'));
await waitFor(/* deleteAssertion 等待订单删除 API 完成。 */ () => expect(orderListMocks.deleteOrder).toHaveBeenCalledWith('order-1'));
expect(orderListMocks.loadOrders).toHaveBeenCalledTimes(2);
expect(orderListMocks.setPage).toHaveBeenCalledWith(expect.any(Function));
});
test('分页按钮使用函数式更新并遵守边界状态', /* 当前回调验证订单分页控件的可操作边界。 */ () => {
render(<OrderList />);
fireEvent.click(screen.getByRole('button', { name: '上一页' }));
fireEvent.click(screen.getByRole('button', { name: '下一页' }));
expect(orderListMocks.setPage).toHaveBeenCalledWith(expect.any(Function));
// pageUpdaters 保存页面翻页使用的函数式更新回调。
const pageUpdaters = orderListMocks.setPage.mock.calls.filter(/* pageUpdaterCall 筛选分页函数式更新调用。 */ call => typeof call[0] === 'function');
expect(pageUpdaters).toHaveLength(2);
expect(pageUpdaters[0][0](2)).toBe(1);
expect(pageUpdaters[1][0](2)).toBe(3);
});
});
@@ -0,0 +1,625 @@
import React from 'react';
import { createPortal } from 'react-dom';
import type { OrderStatus } from '../../../../shared/api-contract';
import { OrderFilterBar } from '../components/OrderFilterBar';
import { OrderImportModal } from '../components/OrderImportModal';
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 }) => {
// styles 样式表。
const styles = {
processing: 'bg-blue-100 text-blue-800',
pending_ship: 'bg-brand text-white',
shipped: 'bg-blue-100 text-blue-700',
completed: 'bg-green-100 text-green-700',
cancelled: 'bg-gray-100 text-gray-500',
refunding: 'bg-red-100 text-red-600',
unknown: 'bg-gray-100 text-gray-500',
};
// labels labels,负责当前功能中的对应处理。
const labels = {
processing: '处理中',
pending_ship: '待发货',
shipped: '已发货',
completed: '已完成',
cancelled: '已取消',
refunding: '退款中',
unknown: '未知',
};
return (
<span className={`px-3 py-1.5 rounded-lg text-xs font-bold ${styles[status] || styles.cancelled}`}>
{labels[status] || status}
</span>
);
};
// OrderList 渲染订单列表组件。
const OrderList: React.FC = () => {
// orderQuery 负责订单查询、筛选、分页和展示辅助数据。
const orderQuery = useOrderQuery();
// importState 负责订单导入弹窗、上传取消和失败重试。
const importState = useOrderImport(orderQuery.loadOrders);
// { 解构得到当前 Hook 返回的状态和操作函数。
const { orders, accounts, filter, setFilter, accountFilter, setAccountFilter, searchText, setSearchText, page, setPage, totalPages, loading, loadOrders, accountName, accountNickname, getItemNameById } = orderQuery;
// orderActions 集中管理订单动作、弹窗状态和异步结果。
const orderActions = useOrderActions({ orders, page, accountFilter, filter, setPage, loadOrders });
// actionState 解构得到页面动作协调器的状态和操作函数。
const {
showDetailModal,
selectedOrder,
showEditModal,
editingOrder,
showShipModal,
shipOrderId,
shipLoading,
shipResult,
syncingOrderId,
deletingOrderId,
handleSync,
handleShip,
executeShip,
handleViewDetail,
handleEdit,
handleSaveEdit,
updateEditingOrder,
handleSyncSingle,
handleDelete,
closeDetailModal,
closeEditModal,
closeShipModal,
} = orderActions;
// handleFilterChange 切换订单状态筛选并回到第一页。
const handleFilterChange = (value: string) => {
setFilter(value);
setPage(1);
setSearchText('');
};
// handleAccountFilterChange 切换账号筛选并回到第一页。
const handleAccountFilterChange = (value: string) => {
setAccountFilter(value);
setPage(1);
};
// handleSearchChange 更新订单搜索文本并回到第一页。
const handleSearchChange = (value: string) => {
setSearchText(value);
setPage(1);
};
return (
<div className="space-y-6 animate-fade-in">
<div className="flex flex-col md:flex-row justify-between md:items-end gap-4">
<div>
<h2 className="text-4xl font-extrabold text-gray-900 tracking-tight">订单中心</h2>
<p className="text-gray-500 mt-2 font-medium">查看所有闲鱼交易记录与状态。</p>
</div>
<div className="flex items-center gap-3">
<button onClick={loadOrders} className="p-3 rounded-2xl bg-white border border-gray-100 text-gray-600 hover:bg-gray-50 hover:text-black transition-colors shadow-sm">
<RefreshCw className={`w-5 h-5 ${loading ? 'animate-spin' : ''}`} />
</button>
<button
onClick={importState.openImportModal}
className="px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors text-sm flex items-center gap-2 shadow-lg"
>
<Plus className="w-4 h-4" />
插入订单
</button>
<button onClick={handleSync} className="ios-btn-primary px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 text-sm flex items-center gap-2">
<Truck className="w-5 h-5" />
一键同步订单
</button>
</div>
</div>
<div className="ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white">
<OrderFilterBar
filter={filter}
onFilterChange={handleFilterChange}
accountFilter={accountFilter}
onAccountFilterChange={handleAccountFilterChange}
accounts={accounts}
accountName={accountName}
searchText={searchText}
onSearchChange={handleSearchChange}
/>
{/* Table */}
<div className="overflow-x-auto min-h-[400px]">
<table className="w-full text-left border-collapse table-fixed">
<thead>
<tr className="bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50">
<th className="px-6 py-5" style={{width: '28%'}}>订单信息</th>
<th className="px-6 py-5" style={{width: '26%'}}>买家信息</th>
<th className="px-6 py-5" style={{width: '11%'}}>实付金额</th>
<th className="px-6 py-5" style={{width: '13%'}}>当前状态</th>
<th className="px-6 py-5 text-right" style={{width: '22%'}}>操作</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-50">
{orders.map(/* 当前回调处理集合中的单个元素。 */ (order) => (
<tr key={order.id} className="hover:bg-warning-50/50 transition-colors group">
<td className="px-6 py-5">
<div className="flex items-center gap-5">
<div className="w-14 h-14 rounded-xl bg-gray-100 overflow-hidden shadow-sm border border-gray-100 flex-shrink-0">
{order.item_image ? (
<img src={order.item_image} alt="" className="w-full h-full object-cover" />
) : (
<div className="w-full h-full flex items-center justify-center text-gray-300"><PackageCheck /></div>
)}
</div>
<div className="min-w-0">
<div className="font-bold text-gray-900 line-clamp-1 text-sm">
{getItemNameById(order.cookie_id, order.item_id, order.item_title)}
</div>
<div className="mt-1 flex w-fit min-w-0 max-w-full items-center gap-1 rounded-md bg-blue-50 px-2 py-1 text-[10px] font-extrabold text-blue-700" title={accountNickname(order.cookie_id)}>
<UserIcon className="h-3 w-3 shrink-0" />
<span className="min-w-0 truncate whitespace-nowrap">{accountNickname(order.cookie_id)}</span>
</div>
<div className="text-xs text-gray-500 mt-1 font-medium">订单ID: {order.order_id}</div>
<div className="text-xs text-gray-400 mt-0.5">数量: {order.quantity} • {formatLocalDateTime(order.created_at)}</div>
</div>
</div>
</td>
<td className="px-6 py-5">
<div className="flex flex-col gap-1">
<div className="text-xs text-gray-500">买家ID</div>
<div className="text-sm font-bold text-gray-800">{order.buyer_id}</div>
{order.receiver_name && (
<>
<div className="text-xs text-gray-500">收货人</div>
<div className="text-xs text-gray-600">{order.receiver_name}</div>
</>
)}
{order.receiver_phone && (
<>
<div className="text-xs text-gray-500">联系电话</div>
<div className="text-xs text-gray-600 font-mono">{order.receiver_phone}</div>
</>
)}
{order.receiver_address && (
<>
<div className="text-xs text-gray-500">收货地址</div>
<div className="text-xs text-gray-600 line-clamp-1">{order.receiver_address}</div>
</>
)}
</div>
</td>
<td className="px-6 py-5 text-base font-extrabold text-gray-900 font-feature-settings-tnum">
{order.amount ? `¥${order.amount}` : <span className="text-xs text-amber-600 font-bold">待获取</span>}
</td>
<td className="px-6 py-5">
<StatusBadge status={order.status} />
</td>
<td className="px-6 py-5 text-right">
{order.status === 'pending_ship' && (
<button
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => handleShip(order.order_id)}
className="mr-2 text-white bg-black hover:bg-gray-800 shadow-lg shadow-gray-200 text-xs font-bold px-3 py-2 rounded-xl transition-all active:scale-95"
>
立即发货
</button>
)}
<a
href={`https://www.goofish.com/order-detail?orderId=${order.order_id}&role=seller`}
target="_blank"
rel="noopener noreferrer"
className="mr-2 inline-flex text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors"
title="查看闲鱼详情"
>
<ExternalLink className="w-4 h-4" />
</a>
<button
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => handleViewDetail(order)}
className="mr-2 text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors"
title="查看详情"
>
<Eye className="w-4 h-4" />
</button>
<button
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => handleEdit(order)}
className="mr-2 text-gray-400 hover:text-black p-2 rounded-xl hover:bg-gray-100 transition-colors"
title="编辑订单"
>
<Edit className="w-4 h-4" />
</button>
<button
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => handleSyncSingle(order.order_id)}
disabled={syncingOrderId === order.order_id}
className="mr-2 text-gray-400 hover:text-green-600 p-2 rounded-xl hover:bg-green-50 transition-colors disabled:opacity-50"
title="同步订单"
>
<RefreshCw className={`w-4 h-4 ${syncingOrderId === order.order_id ? 'animate-spin' : ''}`} />
</button>
<button
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => handleDelete(order.order_id)}
disabled={deletingOrderId === order.order_id}
className="text-gray-400 hover:text-red-500 p-2 rounded-xl hover:bg-red-50 transition-colors disabled:opacity-50"
title="删除订单"
>
<Trash2 className="w-4 h-4" />
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
{/* Pagination */}
<div className="p-4 border-t border-gray-50 flex items-center justify-between bg-white">
<div className="text-sm text-gray-500 font-medium pl-2">
第 {page} 页 / 共 {totalPages} 页
</div>
<div className="flex gap-2">
<button
disabled={page <= 1}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setPage(/* 当前回调处理用户交互或异步状态变化。 */ p => p - 1)}
aria-label="上一页"
className="p-2.5 rounded-xl bg-gray-50 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed text-gray-600 transition-colors"
>
<ChevronLeft className="w-5 h-5" />
</button>
<button
disabled={page >= totalPages}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setPage(/* 当前回调处理用户交互或异步状态变化。 */ p => p + 1)}
aria-label="下一页"
className="p-2.5 rounded-xl bg-gray-50 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed text-gray-600 transition-colors"
>
<ChevronRight className="w-5 h-5" />
</button>
</div>
</div>
</div>
{/* 订单详情弹窗 - 使用 Portal */}
{showDetailModal && selectedOrder && createPortal(
<div className="modal-overlay-centered">
<div className="modal-container">
<div className="modal-header">
<div className="flex items-center justify-between w-full">
<h3 className="text-2xl font-extrabold text-gray-900">订单详情</h3>
<button
onClick={closeDetailModal}
className="p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors"
>
<X className="w-5 h-5 text-gray-600" />
</button>
</div>
</div>
<div className="modal-body space-y-6">
{/* Order Info */}
<div className="space-y-4">
<h4 className="text-lg font-bold text-gray-800">订单信息</h4>
<div className="grid grid-cols-2 gap-4 p-4 bg-gray-50 rounded-xl">
<div>
<div className="text-xs text-gray-500 mb-1">订单号</div>
<div className="font-mono text-sm font-bold text-gray-900">{selectedOrder.order_id}</div>
</div>
<div>
<div className="text-xs text-gray-500 mb-1">所属账号</div>
<div className="truncate whitespace-nowrap text-sm font-bold text-blue-700" title={accountNickname(selectedOrder.cookie_id)}>{accountNickname(selectedOrder.cookie_id)}</div>
</div>
<div>
<div className="text-xs text-gray-500 mb-1">状态</div>
<StatusBadge status={selectedOrder.status} />
</div>
<div>
<div className="text-xs text-gray-500 mb-1">实付金额</div>
<div className="text-lg font-extrabold text-gray-900">{selectedOrder.amount ? `¥${selectedOrder.amount}` : '待获取'}</div>
</div>
<div>
<div className="text-xs text-gray-500 mb-1">数量</div>
<div className="font-bold text-gray-900">{selectedOrder.quantity}</div>
</div>
<div className="col-span-2">
<div className="text-xs text-gray-500 mb-1">创建时间</div>
<div className="text-sm font-medium text-gray-700">{formatLocalDateTime(selectedOrder.created_at)}</div>
</div>
</div>
</div>
{/* Item Info */}
<div className="space-y-4">
<h4 className="text-lg font-bold text-gray-800">商品信息</h4>
<div className="p-4 bg-gray-50 rounded-xl flex items-center gap-4">
{selectedOrder.item_image && (
<img src={selectedOrder.item_image} alt="" className="w-20 h-20 rounded-xl object-cover border border-gray-200" />
)}
<div className="flex-1">
<div className="font-bold text-gray-900 mb-1">
{getItemNameById(selectedOrder.cookie_id, selectedOrder.item_id, selectedOrder.item_title)}
</div>
<div className="text-sm text-gray-500">商品ID: {selectedOrder.item_id}</div>
{selectedOrder.item_price && (
<div className="text-sm text-gray-500 mt-1">标价: ¥{selectedOrder.item_price}</div>
)}
</div>
</div>
</div>
{/* Buyer Info */}
<div className="space-y-4">
<h4 className="text-lg font-bold text-gray-800">买家信息</h4>
<div className="p-4 bg-gray-50 rounded-xl space-y-3">
<div>
<div className="text-xs text-gray-500 mb-1">买家ID</div>
<div className="font-bold text-gray-900">{selectedOrder.buyer_id}</div>
</div>
{selectedOrder.receiver_name && (
<div>
<div className="text-xs text-gray-500 mb-1">收货人</div>
<div className="font-medium text-gray-700">{selectedOrder.receiver_name}</div>
</div>
)}
{selectedOrder.receiver_phone && (
<div>
<div className="text-xs text-gray-500 mb-1">联系电话</div>
<div className="font-mono text-sm text-gray-700">{selectedOrder.receiver_phone}</div>
</div>
)}
{selectedOrder.receiver_address && (
<div>
<div className="text-xs text-gray-500 mb-1">收货地址</div>
<div className="text-sm text-gray-700">{selectedOrder.receiver_address}</div>
</div>
)}
</div>
</div>
</div>
<div className="modal-footer">
<div className="flex gap-3 w-full">
<button
onClick={closeDetailModal}
className="flex-1 px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors"
>
关闭
</button>
{selectedOrder.status === 'pending_ship' && (
<button
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => {
closeDetailModal();
handleShip(selectedOrder.order_id);
}}
className="flex-1 px-6 py-3 rounded-xl ios-btn-primary font-bold shadow-lg shadow-blue-200"
>
立即发货
</button>
)}
</div>
</div>
</div>
</div>,
document.body
)}
<OrderImportModal {...importState} />
{/* Ship Modal - 发货方式选择 */}
{showShipModal && createPortal(
<div className="modal-overlay-centered">
<div className="modal-container" style={{ maxWidth: '480px' }}>
<div className="modal-header">
<div className="flex items-center justify-between w-full">
<h3 className="text-2xl font-extrabold text-gray-900">立即发货</h3>
<button
onClick={closeShipModal}
className="p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors"
>
<X className="w-5 h-5 text-gray-600" />
</button>
</div>
</div>
<div className="modal-body space-y-4">
<p className="text-sm text-gray-600">请选择发货方式:</p>
{/* 选项A: 仅修改发货状态 */}
<button
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => executeShip('status_only')}
disabled={shipLoading}
className="w-full text-left p-4 rounded-xl border-2 border-gray-200 hover:border-gray-400 hover:bg-gray-50 transition-all disabled:opacity-50 disabled:cursor-not-allowed"
>
<div className="flex items-start gap-3">
<div className="w-10 h-10 rounded-xl bg-blue-100 flex items-center justify-center flex-shrink-0 mt-0.5">
<Truck className="w-5 h-5 text-blue-600" />
</div>
<div>
<div className="font-bold text-gray-900 text-sm">仅修改闲鱼发货状态</div>
<div className="text-xs text-gray-500 mt-1 leading-relaxed">
不实际扣除或发送卡券,仅在闲鱼平台将订单标记为"已发货"。
适用于已经给客户发过货、只是忘记在闲鱼修改状态的情况。
</div>
</div>
</div>
</button>
{/* 选项B: 完整发货流程 */}
<button
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => executeShip('full_delivery')}
disabled={shipLoading}
className="w-full text-left p-4 rounded-xl border-2 border-gray-200 hover:border-brand hover:bg-blue-50 transition-all disabled:opacity-50 disabled:cursor-not-allowed"
>
<div className="flex items-start gap-3">
<div className="w-10 h-10 rounded-xl bg-blue-100 flex items-center justify-center flex-shrink-0 mt-0.5">
<PackageCheck className="w-5 h-5 text-blue-700" />
</div>
<div>
<div className="font-bold text-gray-900 text-sm">完整发货(匹配卡券并发送)</div>
<div className="text-xs text-gray-500 mt-1 leading-relaxed">
自动匹配发货规则、获取卡券、发送卡券信息给买家,并修改发货状态。
适用于订单既没有发送卡券给买家、也没有修改发货状态的情况。
</div>
</div>
</div>
</button>
{/* 加载状态 */}
{shipLoading && (
<div className="flex items-center justify-center gap-2 py-3">
<RefreshCw className="w-4 h-4 animate-spin text-gray-500" />
<span className="text-sm text-gray-500">正在处理中...</span>
</div>
)}
{/* 结果显示 */}
{shipResult && (
<div className={`p-3 rounded-xl text-sm ${shipResult.success ? 'bg-green-50 text-green-800' : 'bg-red-50 text-red-800'}`}>
{shipResult.success ? '✓ ' : '✗ '}{shipResult.message}
</div>
)}
</div>
<div className="modal-footer">
<button
onClick={closeShipModal}
className="w-full px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors"
>
{shipResult?.success ? '完成' : '取消'}
</button>
</div>
</div>
</div>,
document.body
)}
{/* Edit Modal - 使用 Portal */}
{showEditModal && editingOrder && createPortal(
<div className="modal-overlay-centered">
<div className="modal-container">
<div className="modal-header">
<div className="flex items-center justify-between w-full">
<h3 className="text-2xl font-extrabold text-gray-900">编辑订单</h3>
<button
onClick={closeEditModal}
className="p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors"
>
<X className="w-5 h-5 text-gray-600" />
</button>
</div>
</div>
<div className="modal-body space-y-5">
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-bold text-gray-700 mb-2">订单号</label>
<input
type="text"
value={editingOrder.order_id}
disabled
className="w-full ios-input px-4 py-3 rounded-xl bg-gray-50 text-gray-500"
/>
</div>
<div>
<label className="block text-sm font-bold text-gray-700 mb-2">订单状态</label>
<select
value={editingOrder.status}
onChange={/* 当前回调更新订单状态草稿。 */ (e) => updateEditingOrder({ status: e.target.value as OrderStatus })}
className="w-full ios-input px-4 py-3 rounded-xl"
>
<option value="processing">处理中</option>
<option value="pending_ship">待发货</option>
<option value="shipped">已发货</option>
<option value="completed">已完成</option>
<option value="cancelled">已取消</option>
<option value="refunding">退款中</option>
</select>
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-bold text-gray-700 mb-2">买家ID</label>
<input
type="text"
value={editingOrder.buyer_id}
onChange={/* 当前回调更新买家标识草稿。 */ (e) => updateEditingOrder({ buyer_id: e.target.value })}
className="w-full ios-input px-4 py-3 rounded-xl"
/>
</div>
<div>
<label className="block text-sm font-bold text-gray-700 mb-2">实付金额</label>
<input
type="number"
value={editingOrder.amount}
onChange={/* 当前回调更新订单金额草稿。 */ (e) => updateEditingOrder({ amount: e.target.value })}
className="w-full ios-input px-4 py-3 rounded-xl"
/>
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-bold text-gray-700 mb-2">收货人</label>
<input
type="text"
value={editingOrder.receiver_name || ''}
onChange={/* 当前回调更新收货人草稿。 */ (e) => updateEditingOrder({ receiver_name: e.target.value })}
className="w-full ios-input px-4 py-3 rounded-xl"
/>
</div>
<div>
<label className="block text-sm font-bold text-gray-700 mb-2">联系电话</label>
<input
type="text"
value={editingOrder.receiver_phone || ''}
onChange={/* 当前回调更新收货电话草稿。 */ (e) => updateEditingOrder({ receiver_phone: e.target.value })}
className="w-full ios-input px-4 py-3 rounded-xl"
/>
</div>
</div>
<div>
<label className="block text-sm font-bold text-gray-700 mb-2">收货地址</label>
<textarea
value={editingOrder.receiver_address || ''}
onChange={/* 当前回调更新收货地址草稿。 */ (e) => updateEditingOrder({ receiver_address: e.target.value })}
rows={2}
className="w-full ios-input px-4 py-3 rounded-xl resize-none"
/>
</div>
<div>
<label className="block text-sm font-bold text-gray-700 mb-2">商品标题</label>
<input
type="text"
value={editingOrder.item_title || ''}
onChange={/* 当前回调更新商品标题草稿。 */ (e) => updateEditingOrder({ item_title: e.target.value })}
className="w-full ios-input px-4 py-3 rounded-xl"
/>
</div>
</div>
<div className="modal-footer">
<div className="flex gap-3 w-full">
<button
onClick={closeEditModal}
className="flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors"
>
取消
</button>
<button
onClick={handleSaveEdit}
className="flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2"
>
<Save className="w-4 h-4" />
保存更改
</button>
</div>
</div>
</div>
</div>,
document.body
)}
</div>
);
};
export default OrderList;
+1 -1
View File
@@ -1,5 +1,5 @@
import type { Dispatch, SetStateAction } from 'react';
import type { AccountDetail, Item, Order, OrderStatus } from '../../../types';
import type { AccountDetail, Item, Order, OrderStatus } from '../../../shared/api-contract';
// OrderImportRowResult 描述订单导入接口返回的单行处理结果。
export interface OrderImportRowResult {
@@ -1,7 +1,7 @@
import ReactDOMServer from 'react-dom/server';
import { describe, expect, test } from 'vitest';
import type { NotificationChannel } from '../../types';
import type { SystemSettings } from '../../types';
import type { NotificationChannel } from '../../shared/api-contract';
import type { SystemSettings } from '../../shared/api-contract';
import { CardIcon } from './cards/components/CardIcon';
import { BatchPhaseIndicator } from './items/components/BatchPhaseIndicator';
import { NotificationChannelList } from './notifications/components/NotificationChannelList';
+354 -23
View File
@@ -1,24 +1,355 @@
// 规则 feature 只通过本适配层访问共享 API,组件不直接依赖网络客户端。
export {
clearDefaultReplyRecords,
deleteDefaultReply,
deleteReplyRule,
deleteShippingRule,
getAccountDetails,
getCards,
getDefaultReplies,
getDefaultReply,
getItems,
getAutomationIssues,
getReplyRules,
getShippingRules,
getShippingRulesPage,
updateDefaultReply,
updateReplyRule,
updateShippingRule,
resolveAutomationRun,
resolveDeferredAutomationTask,
} from '../../../services/api';
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';
// 规则异常类型由共享 API 层定义,feature 通过类型重导出保持边界稳定。
export type { AutomationRunIssue, DeferredAutomationIssue } from '../../../services/api';
/** 自动化规则筛选器读取非敏感账号摘要。 */
export const getAccountDetails = async (options?: RequestControlOptions): Promise<AccountDetail[]> => get('/api/v1/accounts/details', undefined, options);
/** 自动化动作编辑器读取可选卡券组。 */
export const getCards = async (options?: RequestControlOptions): Promise<Card[]> => get('/api/v1/cards', undefined, options);
/** 自动化规则商品选择器读取商品索引。 */
export const getItems = async (accountID?: string, options?: RequestControlOptions): Promise<Item[]> => get('/api/v1/items', accountID ? { cookie_id: accountID } : undefined, options);
// Rules - 自动化规则
const normalizeShippingRules = (rules: any[]): ShippingRule[] => rules.map(/* 当前回调用于处理集合元素或接口响应。 */ (item: any) => ({
id: String(item.id),
name: item.name || '',
trigger_type: item.trigger_type || 'order_paid',
item_keyword: item.item_title || item.item_id || '',
cookie_id: item.cookie_id || '',
item_id: item.item_id || '',
item_title: item.item_title || '',
card_group_id: Number((item.actions || []).find(/* 当前回调用于处理集合元素或接口响应。 */ (a: any) => a.action_type === 'send_card')?.card_id || 0),
card_group_name: (item.actions || []).find(/* 当前回调用于处理集合元素或接口响应。 */ (a: any) => a.action_type === 'send_card')?.card_name || '',
priority: item.priority || 100,
enabled: item.enabled || false,
config_json: item.config_json || '{}',
actions: (item.actions || []).map(/* 当前回调用于处理集合元素或接口响应。 */ (action: any) => ({
id: action.id ? String(action.id) : undefined,
action_type: action.action_type,
card_id: Number(action.card_id || 0),
card_name: action.card_name || '',
delivery_count: Number(action.delivery_count || 1),
message_template: action.message_template || '',
delay_seconds: Number(action.delay_seconds || 0),
config_json: action.config_json || '{}',
enabled: action.enabled !== false,
sort_order: Number(action.sort_order || 0),
})),
variants: (item.actions || [])
.filter(/* 当前回调用于处理集合元素或接口响应。 */ (action: any) => action.action_type === 'send_card')
.map(/* 当前回调用于处理集合元素或接口响应。 */ (action: any) => {
// cfg 动作配置,用于当前 API 处理流程。
let cfg: any = {};
try { cfg = JSON.parse(action.config_json || '{}'); } catch {}
return {
id: action.id ? String(action.id) : undefined,
spec_name: cfg.spec_name || '',
spec_value: cfg.spec_value || '',
card_id: Number(action.card_id || 0),
card_name: action.card_name || '',
delivery_count: Number(action.delivery_count || 1),
enabled: action.enabled !== false,
delay_override: cfg.delay_override === true,
delay_seconds: Number(action.delay_seconds || 0),
config_json: action.config_json || '{}',
};
}),
}));
// getShippingRules 读取发货规则列表。
export const getShippingRules = async (): Promise<ShippingRule[]> => {
// res 接口响应结果,用于当前 API 处理流程。
const res = await get<unknown>('/api/v1/automation-rules');
// rules 规则列表,用于当前 API 处理流程。
const rules = collectionFrom<AutomationRuleResponse>(res, ['data', 'rules', 'items']);
return normalizeShippingRules(rules);
}
export interface ShippingRuleListParams {
/** cookieId 表示登录凭证标识。 */ cookieId?: string;
/** triggerType 表示触发类型。 */ triggerType?: AutomationTriggerType | '';
/** enabled 表示启用状态。 */ enabled?: boolean;
/** search 表示搜索条件。 */ search?: string;
/** page 表示页码。 */ page?: number;
/** pageSize 表示每页数量。 */ pageSize?: number;
}
// getShippingRulesPage 分页读取发货规则。
export const getShippingRulesPage = async ({
cookieId,
triggerType,
enabled,
search,
page: requestedPage = 1,
pageSize = 10,
}: ShippingRuleListParams = {}): Promise<PaginatedResponse<ShippingRule>> => {
// res 接口响应结果,用于当前 API 处理流程。
const response = await get<unknown>('/api/v1/automation-rules', {
page: requestedPage,
page_size: pageSize,
cookie_id: cookieId || undefined,
trigger_type: triggerType || undefined,
enabled,
search: search?.trim() || undefined,
});
// rules 规则列表,用于当前 API 处理流程。
// page 是兼容直接分页对象和 data 包裹后的分页元数据。
const pageMeta = objectFrom<Partial<AutomationRulePageResponse>>(response, ['data', 'result']) || {};
// rules 是归一化后的自动化规则列表。
const rules = normalizeShippingRules(collectionFrom<AutomationRuleResponse>(response, ['data', 'rules', 'items']));
return {
success: true,
data: rules,
total: Number(pageMeta.total ?? rules.length),
page: Number(pageMeta.page ?? requestedPage),
page_size: Number(pageMeta.page_size ?? pageSize),
total_pages: Number(pageMeta.total_pages ?? (rules.length ? 1 : 0)),
trigger_counts: Object.fromEntries(
Object.entries(pageMeta.trigger_counts || {}).map(/* 当前回调用于处理集合元素或接口响应。 */ ([key, value]) => [key, Number(value)]),
),
};
}
// orderAutomationActions 构建订单自动化动作。
const orderAutomationActions = (triggerType: string, actions: AutomationAction[]) => {
if (triggerType !== 'order_paid') {
return actions.map(/* 当前回调用于处理集合元素或接口响应。 */ (action, index) => ({ ...action, sort_order: action.sort_order || index + 1 }));
}
// sendCards 发送Cards。
const sendCards = actions
.filter(/* 当前回调用于处理集合元素或接口响应。 */ action => action.action_type === 'send_card')
.map(/* 当前回调用于处理集合元素或接口响应。 */ (action, index) => ({ ...action, sort_order: index + 1 }));
// others 其他动作列表,用于当前 API 处理流程。
const others = actions.filter(/* 当前回调用于处理集合元素或接口响应。 */ action => action.action_type !== 'send_card' && action.action_type !== 'confirm_shipment');
return [
...sendCards,
...others.map(/* 当前回调用于处理集合元素或接口响应。 */ (action, index) => ({ ...action, sort_order: sendCards.length + index + 1 })),
{ action_type: 'confirm_shipment' as const, enabled: true, sort_order: sendCards.length + others.length + 1 },
];
};
// updateShippingRule 更新发货规则。
export const updateShippingRule = async (rule: Partial<ShippingRule>): Promise<OperationResponse | MutationIDResponse> => {
// triggerType 触发类型,用于当前 API 处理流程。
const triggerType = rule.trigger_type || 'order_paid';
// triggerName 触发名称,用于当前 API 处理流程。
const triggerName: Record<string, string> = {
order_paid: '付款后自动发货',
buyer_reviewed: '评价后发送赠品',
review_missing_timeout: '超时未评价求评价',
};
// generatedName 生成d名称。
const generatedName = [
triggerName[triggerType] || '自动化规则',
rule.item_title || rule.item_id || rule.cookie_id || '',
].filter(Boolean).join(' - ');
// preservedNonCardActions 保留的非卡密动作,用于当前 API 处理流程。
const preservedNonCardActions = (rule.actions || []).filter(/* 当前回调用于处理集合元素或接口响应。 */ action => action.action_type !== 'send_card' && action.action_type !== 'confirm_shipment');
// baseActions 基础动作列表,用于当前 API 处理流程。
const baseActions: AutomationAction[] = rule.variants && rule.variants.length > 0
? [...rule.variants.map(/* 当前回调用于处理集合元素或接口响应。 */ (variant, index) => ({
action_type: 'send_card' as const,
card_id: variant.card_id,
delivery_count: variant.delivery_count || 1,
enabled: variant.enabled !== false,
sort_order: index + 1,
delay_seconds: variant.delay_seconds || 0,
config_json: JSON.stringify({
spec_name: variant.spec_name || '',
spec_value: variant.spec_value || '',
delay_override: variant.delay_override === true,
}),
})), ...preservedNonCardActions]
: (rule.actions && rule.actions.length > 0 ? rule.actions : [{
action_type: 'send_card' as const,
card_id: rule.card_group_id || 0,
delivery_count: 1,
enabled: true,
sort_order: 1,
}]);
// actions 动作列表,用于当前 API 处理流程。
const actions = orderAutomationActions(triggerType, baseActions);
// payload 请求载荷,用于当前 API 处理流程。
const payload = {
cookie_id: rule.cookie_id || '',
item_id: rule.item_id || '',
name: (rule.name || '').trim() || generatedName || '自动化规则',
trigger_type: triggerType,
enabled: rule.enabled ?? true,
priority: rule.priority || 100,
config_json: rule.config_json || '{}',
actions: actions.map(/* 当前回调用于处理集合元素或接口响应。 */ (action, index) => ({
action_type: action.action_type,
card_id: action.card_id || 0,
delivery_count: action.delivery_count || 1,
message_template: action.message_template || '',
delay_seconds: action.delay_seconds || 0,
config_json: action.config_json || '{}',
enabled: action.enabled !== false,
sort_order: action.sort_order || index + 1,
})),
};
return rule.id ? put(`/api/v1/automation-rules/${rule.id}`, payload) : post('/api/v1/automation-rules', payload);
}
// deleteShippingRule 删除发货规则。
export const deleteShippingRule = async (id: string): Promise<OperationResponse> => del(`/api/v1/automation-rules/${id}`);
export interface AutomationRunIssue {
/** id 表示标识。 */ id: number;
/** cookie_id 表示登录凭证标识。 */ cookie_id: string;
/** order_id 表示订单标识。 */ order_id: string;
/** trigger_type 表示触发条件类型。 */ trigger_type: string;
/** error_message 表示错误消息。 */ error_message: string;
/** issue_kind 表示问题类型。 */ issue_kind: 'external_result_unknown' | 'invalid_snapshot' | 'rule_unavailable' | 'partial_failure' | 'execution_failed';
/** allowed_resolutions 表示允许的解决方式。 */ allowed_resolutions: Array<'continue' | 'retry' | 'cancel'>;
/** action_cursor 表示动作游标。 */ action_cursor: number;
/** sent_count 表示已发送数量。 */ sent_count: number;
/** updated_at 表示最后更新时间。 */ updated_at: string;
}
export interface DeferredAutomationIssue {
/** id 表示标识。 */ id: number;
/** cookie_id 表示登录凭证标识。 */ cookie_id: string;
/** trigger_type 表示触发条件类型。 */ trigger_type: string;
/** error_message 表示错误消息。 */ error_message: string;
/** attempt_count 表示尝试次数。 */ attempt_count: number;
/** updated_at 表示最后更新时间。 */ updated_at: string;
}
// getAutomationIssues 读取自动化问题列表。
export const getAutomationIssues = async (): Promise<{ /** runs 表示运行记录。 */ runs: AutomationRunIssue[]; /** pending_tasks 表示待处理任务列表。 */ pending_tasks: DeferredAutomationIssue[] }> => {
// response 是兼容直接问题对象、data 包裹和 null 的自动化问题响应。
const response = await get<unknown>('/api/v1/automation-issues');
// result 是去除历史包裹后的自动化问题对象。
const result = objectFrom<Partial<AutomationIssuesEnvelope>>(response, ['data', 'result']) || {};
return {
runs: Array.isArray(result?.runs) ? result.runs : [],
pending_tasks: Array.isArray(result?.pending_tasks) ? result.pending_tasks : [],
};
};
// resolveAutomationRun 处理自动化运行记录。
export const resolveAutomationRun = async (id: number, resolution: 'continue' | 'retry' | 'cancel'): Promise<OperationResponse> =>
post(`/api/v1/automation-runs/${id}/resolve`, { resolution });
// resolveDeferredAutomationTask 处理延迟自动化任务。
export const resolveDeferredAutomationTask = async (id: number, resolution: 'retry' | 'dismiss'): Promise<OperationResponse> =>
post(`/api/v1/automation-pending-tasks/${id}/resolve`, { resolution });
// Rules - 关键词回复规则 (使用关键词API)
type KeywordRowPayload = {
/** id 表示标识。 */ id: string;
/** keyword 表示关键词。 */ keyword: string;
/** reply 表示回复内容。 */ reply: string;
/** item_id 表示商品标识。 */ item_id: string;
/** type 表示规则类型。 */ type: 'text' | 'image';
/** image_url 表示图片地址。 */ image_url: string;
};
// normalizeKeywordRow 归一化关键词规则。
const normalizeKeywordRow = (item: any): KeywordRowPayload => ({
id: String(item?.id || ''),
keyword: item?.keyword || '',
reply: item?.reply || '',
item_id: item?.item_id || '',
type: item?.type === 'image' ? 'image' : 'text',
image_url: item?.image_url || '',
});
// getKeywordRowsWithType 读取带类型的关键词规则。
const getKeywordRowsWithType = async (cookieId: string): Promise<KeywordRowPayload[]> => {
// existing 已有规则,用于当前 API 处理流程。
const existing = await get<unknown>(`/api/v1/reply-rules/${cookieId}/typed`);
return collectionFrom<KeywordTypedResponse>(existing, ['data', 'items', 'rules']).map(normalizeKeywordRow);
};
// getReplyRules 读取回复规则。
export const getReplyRules = async (cookieId?: string): Promise<ReplyRule[]> => {
if (!cookieId) return [];
// keywords keywords,用于当前 API 处理流程。
const keywords = await getKeywordRowsWithType(cookieId);
return keywords.map(/* 当前回调用于处理集合元素或接口响应。 */ (item: any) => ({
id: item.id,
keyword: item.keyword || '',
reply_content: item.reply || '',
match_type: 'fuzzy' as const,
enabled: true,
item_id: item.item_id || '',
type: item.type === 'image' ? 'image' : 'text',
image_url: item.image_url || ''
}));
}
// updateReplyRule 更新回复规则。
export const updateReplyRule = async (rule: Partial<ReplyRule>, cookieId: string): Promise<OperationResponse> => {
// type 规则类型,用于当前 API 处理流程。
const type = rule.type || 'text';
// payload 请求载荷,用于当前 API 处理流程。
const payload = {
keyword: rule.keyword || '',
reply: type === 'text' ? (rule.reply_content || '') : '',
item_id: rule.item_id || '',
type,
image_url: type === 'image' ? (rule.image_url || '') : '',
};
return rule.id
? put(`/api/v1/reply-rules/${cookieId}/typed/${rule.id}`, payload)
: post(`/api/v1/reply-rules/${cookieId}/items`, payload);
}
// deleteReplyRule 删除回复规则。
export const deleteReplyRule = async (id: string, cookieId: string): Promise<OperationResponse> => {
return del(`/api/v1/reply-rules/${cookieId}/typed/${id}`);
}
// Default Reply
// getDefaultReplies 读取默认回复列表。
export const getDefaultReplies = async (): Promise<Record<string, DefaultReplyResponse>> => {
const response = await get<unknown>('/api/v1/default-replies');
// replies 是兼容直接映射、data 包裹和 null 的默认回复索引。
return objectFrom<Record<string, DefaultReplyResponse>>(response, ['data', 'replies', 'items']) || {};
};
// getDefaultReply 读取默认回复。
export const getDefaultReply = async (cookieId: string): Promise<DefaultReply> => {
// result 接口响应结果,用于当前 API 处理流程。
const response = await get<unknown>(`/api/v1/default-replies/${cookieId}`);
// result 是兼容直接默认回复和 data 包裹后的对象。
const result = objectFrom<Partial<DefaultReplyResponse>>(response, ['data', 'result']) || {};
return {
cookie_id: cookieId,
enabled: result.enabled || false,
reply_content: result.reply_content || '',
reply_once: result.reply_once || false,
reply_image_url: result.reply_image_url || ''
};
};
// updateDefaultReply 更新默认回复。
export const updateDefaultReply = async (cookieId: string, data: Partial<DefaultReply>): Promise<OperationResponse> => {
return put(`/api/v1/default-replies/${cookieId}`, {
enabled: data.enabled ?? false,
reply_content: data.reply_content || '',
reply_once: data.reply_once ?? false,
reply_image_url: data.reply_image_url || ''
});
};
// deleteDefaultReply 删除默认回复。
export const deleteDefaultReply = async (cookieId: string): Promise<OperationResponse> => {
return del(`/api/v1/default-replies/${cookieId}`);
};
// clearDefaultReplyRecords 清理默认回复记录。
export const clearDefaultReplyRecords = async (cookieId: string): Promise<OperationResponse> => {
return post(`/api/v1/default-replies/${cookieId}/clear-records`, {});
};
+1 -1
View File
@@ -1,7 +1,7 @@
// @vitest-environment jsdom
import { act, renderHook, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, test, vi } from 'vitest';
import type { AccountDetail, Card, DefaultReply, Item, ReplyRule, ShippingRule } from '../../../types';
import type { AccountDetail, Card, DefaultReply, Item, ReplyRule, ShippingRule } from '../../../shared/api-contract';
import {
getAccountDetails,
getAutomationIssues,
+1 -1
View File
@@ -16,7 +16,7 @@ import type {
Item,
ReplyRule,
ShippingRule,
} from '../../../types';
} from '../../../shared/api-contract';
import type { AutomationIssueState, RulesDataOptions, RulesDataResult, RulesTab } from './types';
import { isCurrentRequest, nextRequestGeneration } from './interactionState';
File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -9,7 +9,7 @@ import type {
ReplyRule,
ShippingRule,
ShippingVariant,
} from '../../../types';
} from '../../../shared/api-contract';
import type { AutomationRunIssue, DeferredAutomationIssue } from './api';
// Rules feature 通过此类型入口重导出共享领域模型,避免页面直接依赖全局类型文件。
@@ -23,7 +23,7 @@ export type {
ReplyRule,
ShippingRule,
ShippingVariant,
} from '../../../types';
} from '../../../shared/api-contract';
// RulesTab 表示规则页面的三个业务页签。
export type RulesTab = 'automation' | 'reply' | 'default';
+1 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, test } from 'vitest';
import type { AccountDetail, ShippingRule } from '../../../types';
import type { AccountDetail, ShippingRule } from '../../../shared/api-contract';
import {
accentClasses,
accountLabel,
+1 -1
View File
@@ -5,7 +5,7 @@ import type {
AutomationTriggerType,
ShippingRule,
ShippingVariant,
} from '../../../types';
} from '../../../shared/api-contract';
import type { TriggerMeta } from './types';
// triggerMeta 是自动化触发类型的统一展示元数据,供列表和编辑器复用。
+40 -2
View File
@@ -1,2 +1,40 @@
// Session feature 只通过本适配层访问会话相关网络接口。
export { initializeAdmin, login, logout, verifySession } from '../../../services/api';
import { get, post, type RequestControlOptions } from '../../../shared/http/client';
import type { OperationResponse, SessionResponse } from '../../../shared/api-contract';
/** 会话状态接口返回的只读传输契约。 */
export interface SessionStatusResponse {
/** 当前浏览器会话是否已认证。 */
authenticated: boolean;
/** 服务是否已经完成首次管理员初始化。 */
initialized?: boolean;
/** 当前登录用户的数据库标识。 */
user_id?: number;
/** 当前登录用户的名称。 */
username?: string;
/** 当前登录用户是否具备管理员权限。 */
is_admin?: boolean;
}
/** 登录请求的具名传输 DTO。 */
export interface LoginRequest {
/** 用户名登录方式使用的账号名称。 */
username?: string;
/** 用户名登录方式使用的密码,仅在本次请求体中存在。 */
password?: string;
/** 邮箱验证码登录方式使用的邮箱地址。 */
email?: string;
/** 邮箱验证码登录方式使用的一次性验证码。 */
verification_code?: string;
}
/** 以用户名密码或邮箱验证码建立管理会话。 */
export const login = async (data: LoginRequest): Promise<SessionResponse> => post('/api/v1/session/login', data, { skipAuthLogout: true });
/** 用首次设置的管理员密码完成系统初始化并建立会话。 */
export const initializeAdmin = async (password: string): Promise<SessionResponse> => post('/api/v1/session/initialize', { password }, { skipAuthLogout: true });
/** 读取当前浏览器的认证与初始化状态,调用者可取消页面卸载前的请求。 */
export const verifySession = async (options?: RequestControlOptions): Promise<SessionStatusResponse> => get('/api/v1/session', undefined, options);
/** 结束当前浏览器会话。 */
export const logout = async (): Promise<OperationResponse> => post('/api/v1/session/logout', {});
@@ -0,0 +1,158 @@
import React, { useState } from 'react';
import { ArrowRight, Loader2, Lock, ShieldCheck, User } from 'lucide-react';
import { YdisksBrandIcon } from '../../../../shared/ui/YdisksLogo';
import { useSession } from '../../../providers/SessionProvider';
/** SessionGate 在会话校验完成前显示加载状态,并承载首次初始化和管理员登录表单。 */
export const SessionGate: React.FC = () => {
// checkingAuth 与 needsInit 是 Provider 维护的会话服务端状态,页面不自行请求认证接口。
const { checkingAuth, needsInit, signIn, initialize } = useSession();
// username 与 password 是登录表单短暂状态,永不写入持久化存储。
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
// initialPassword 与 initialPasswordConfirm 是首次初始化时一次性提交的秘密输入。
const [initialPassword, setInitialPassword] = useState('');
const [initialPasswordConfirm, setInitialPasswordConfirm] = useState('');
// isSubmitting 区分当前正在提交的表单,防止重复发起认证或初始化请求。
const [isSubmitting, setIsSubmitting] = useState(false);
// formError 是仅用于当前界面显示的通用失败信息,不保存接口响应载荷。
const [formError, setFormError] = useState('');
/** handleLogin 在管理员明确提交后调用 Provider 登录,并在失败时展示安全错误文本。 */
const handleLogin = async (event: React.FormEvent<HTMLFormElement>): Promise<void> => {
event.preventDefault();
setIsSubmitting(true);
setFormError('');
try {
// response 是服务端登录契约,只使用其公开的成功和消息字段。
const response = await signIn({ username, password });
if (!response.success) setFormError(response.message || '登录失败');
} catch (error /* error 是认证请求失败原因,不能包含或重显密码。 */) {
setFormError(error instanceof Error ? error.message || '登录失败' : '登录失败');
} finally {
setIsSubmitting(false);
}
};
/** handleInitialize 校验两次管理员密码后提交首次初始化,并在成功后立即清空输入。 */
const handleInitialize = async (event: React.FormEvent<HTMLFormElement>): Promise<void> => {
event.preventDefault();
setFormError('');
if (initialPassword.length < 8) {
setFormError('密码至少需要 8 个字符');
return;
}
if (initialPassword !== initialPasswordConfirm) {
setFormError('两次输入的密码不一致');
return;
}
setIsSubmitting(true);
try {
// response 是首次初始化接口返回的公开认证结果。
const response = await initialize(initialPassword);
if (!response.success) {
setFormError(response.message || '初始化失败,请重试');
return;
}
setInitialPassword('');
setInitialPasswordConfirm('');
} catch (error /* error 是初始化请求失败原因,不输出用户输入的密码。 */) {
setFormError(error instanceof Error ? error.message || '初始化失败,请重试' : '初始化失败,请重试');
} finally {
setIsSubmitting(false);
}
};
if (checkingAuth) {
return (
<main className="flex min-h-screen items-center justify-center bg-surface" aria-label="正在校验会话">
<Loader2 className="h-8 w-8 animate-spin text-brand" />
</main>
);
}
// heading 是当前认证流程的页面标题,保证初始化和登录表单使用一致视觉壳。
const heading = needsInit ? '首次设置管理员密码' : '欢迎回来';
// description 是当前认证流程的辅助说明,不泄露任何会话或账户敏感数据。
const description = needsInit ? '设置完成后会自动进入系统,管理员账号为 admin。' : 'Ydisks闲鱼助手 · 自动发货与管家系统';
return (
<main className="flex min-h-screen items-center justify-center bg-canvas p-4 font-sans">
<section className="w-full max-w-lg rounded-xl border border-white bg-white/80 p-8 shadow-panel backdrop-blur-3xl md:p-12">
<header className="mb-8 text-center">
<div className="mx-auto mb-6 flex justify-center">
<YdisksBrandIcon sizeClass="h-24 w-24" />
</div>
<h1 className="text-3xl font-extrabold text-gray-900">{heading}</h1>
<p className="mt-2 font-medium text-gray-600">{description}</p>
</header>
{needsInit ? (
<form className="space-y-5" onSubmit={handleInitialize}>
<label className="relative block">
<span className="sr-only">设置管理员密码</span>
<Lock className="absolute left-5 top-1/2 h-5 w-5 -translate-y-1/2 text-gray-400" />
<input
autoFocus
className="ios-input h-14 w-full rounded-xl py-4 pl-14 pr-6"
onChange={/* initialPasswordChange 仅将本次密码输入保存在短暂表单状态。 */ (event /* event 是密码输入框的最新用户编辑事件。 */) => setInitialPassword(event.target.value)}
placeholder="设置管理员密码(至少 8 个字符)"
type="password"
value={initialPassword}
/>
</label>
<label className="relative block">
<span className="sr-only">确认管理员密码</span>
<ShieldCheck className="absolute left-5 top-1/2 h-5 w-5 -translate-y-1/2 text-gray-400" />
<input
className="ios-input h-14 w-full rounded-xl py-4 pl-14 pr-6"
onChange={/* initialPasswordConfirmChange 仅更新用于前端一致性校验的确认输入。 */ (event /* event 是确认密码输入框的最新用户编辑事件。 */) => setInitialPasswordConfirm(event.target.value)}
placeholder="再次输入密码"
type="password"
value={initialPasswordConfirm}
/>
</label>
<SubmitButton submitting={isSubmitting} text="设置密码并进入系统" />
</form>
) : (
<form className="space-y-5" onSubmit={handleLogin}>
<label className="relative block">
<span className="sr-only">管理员账号</span>
<User className="absolute left-5 top-1/2 h-5 w-5 -translate-y-1/2 text-gray-400" />
<input
autoFocus
className="ios-input h-14 w-full rounded-xl py-4 pl-14 pr-6"
onChange={/* usernameChange 保存管理员主动输入的登录名称。 */ (event /* event 是管理员账号输入框的最新用户编辑事件。 */) => setUsername(event.target.value)}
placeholder="管理员账号"
type="text"
value={username}
/>
</label>
<label className="relative block">
<span className="sr-only">管理员密码</span>
<Lock className="absolute left-5 top-1/2 h-5 w-5 -translate-y-1/2 text-gray-400" />
<input
className="ios-input h-14 w-full rounded-xl py-4 pl-14 pr-6"
onChange={/* passwordChange 只在当前表单生命周期中保存管理员密码。 */ (event /* event 是管理员密码输入框的最新用户编辑事件。 */) => setPassword(event.target.value)}
placeholder="密码"
type="password"
value={password}
/>
</label>
<SubmitButton submitting={isSubmitting} text="立即登录" />
</form>
)}
{formError ? <p className="mt-5 rounded-xl bg-red-50 p-3 text-center text-sm font-medium text-red-600">{formError}</p> : null}
</section>
</main>
);
};
/** SubmitButton 为认证表单提供固定尺寸的提交控件,避免加载状态改变布局。 */
const SubmitButton: React.FC<{ /** submitting 表示认证请求是否仍在执行。 */ submitting: boolean; /** text 是按钮在空闲时显示的操作名称。 */ text: string }> = ({ submitting, text }) => (
<button className="ios-btn-primary flex h-14 w-full items-center justify-center gap-2 rounded-xl text-lg disabled:opacity-70" disabled={submitting} type="submit">
{submitting ? <Loader2 className="h-5 w-5 animate-spin" /> : <><span>{text}</span><ArrowRight className="h-5 w-5" /></>}
</button>
);
Loaded 100 of 305 files, more files were not shown because too many files have changed in this diff. Show more