阶段四:完成 React Feature 化和异步状态修复
This commit is contained in:
1 parent
4227e3dd56
commit
e92549da48
176 files changed
+849
-650
No files matched your search
@@ -1,5 +1,5 @@
|
||||
import { get, post, put, type RequestControlOptions } from '../../../shared/http/client';
|
||||
import type { AccountTaskSettings, AccountTaskSettingsResponse, AccountTaskRunResponseEnvelope } from '../../../shared/api-contract';
|
||||
import type { AccountTaskRunResponseEnvelope,AccountTaskSettings,AccountTaskSettingsResponse } from './api';
|
||||
import { get,post,put,type RequestControlOptions } from '../../../shared/http/client';
|
||||
|
||||
/** 获取指定账号的自动评价与自动擦亮设置。 */
|
||||
export const getAccountTaskSettings = async (accountID: string, options?: RequestControlOptions): Promise<AccountTaskSettingsResponse> => get(`/api/v1/account-tasks/${accountID}`, undefined, options);
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { AccountDetail, AccountTaskSettingsResponse } from '../../../shared/api-contract';
|
||||
import { getAccountTaskSettings, runAccountTask, updateAccountTaskSettings } from './accountAutomationApi';
|
||||
import { act,renderHook,waitFor } from '@testing-library/react';
|
||||
import { beforeEach,describe,expect,test,vi } from 'vitest';
|
||||
import type { AccountDetail,AccountTaskSettingsResponse } from '../../../shared/api-contract/accounts';
|
||||
import { getAccountTaskSettings,runAccountTask,updateAccountTaskSettings } from './accountAutomationApi';
|
||||
import { useAccountAutomation } from './accountAutomationHooks';
|
||||
|
||||
vi.mock('./accountAutomationApi', /* apiMockFactory 提供账号任务 Hook 的确定性 API 替身。 */ () => ({
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import type { AccountTaskSettings, AccountTaskSummary } from '../../../shared/api-contract';
|
||||
import { getAccountTaskSettings, runAccountTask, updateAccountTaskSettings } from './accountAutomationApi';
|
||||
import { accountTaskErrorMessage, buildAccountTaskDefaults, canStartAccountTask, isAccountTaskAbortError, isCurrentAccountTaskRequest } from './accountAutomationState';
|
||||
import type { AccountAutomationOptions, AccountAutomationState, AccountTaskType } from './accountAutomationTypes';
|
||||
import { useCallback,useEffect,useRef,useState } from 'react';
|
||||
import type { AccountTaskSettings,AccountTaskSummary } from './api';
|
||||
import { getAccountTaskSettings,runAccountTask,updateAccountTaskSettings } from './accountAutomationApi';
|
||||
import { accountTaskErrorMessage,buildAccountTaskDefaults,canStartAccountTask,isAccountTaskAbortError,isCurrentAccountTaskRequest } from './accountAutomationState';
|
||||
import type { AccountAutomationOptions,AccountAutomationState,AccountTaskType } from './accountAutomationTypes';
|
||||
|
||||
/** AccountAutomation Hook 的完整返回值。 */
|
||||
export type UseAccountAutomationResult = AccountAutomationState & {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { expect, test } from 'vitest';
|
||||
import type { AccountDetail } from '../../../shared/api-contract';
|
||||
import { buildAccountTaskDefaults, canStartAccountTask, isCurrentAccountTaskRequest } from './accountAutomationState';
|
||||
import { expect,test } from 'vitest';
|
||||
import type { AccountDetail } from '../../../shared/api-contract/accounts';
|
||||
import { buildAccountTaskDefaults,canStartAccountTask,isCurrentAccountTaskRequest } from './accountAutomationState';
|
||||
|
||||
// accountFixture 是覆盖任务默认值和账号禁用边界的最小账号数据。
|
||||
const accountFixture: AccountDetail = {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { AccountDetail, AccountTaskSettings } from '../../../shared/api-contract';
|
||||
import type { AccountDetail,AccountTaskSettings } from './api';
|
||||
import type { AccountTaskType } from './accountAutomationTypes';
|
||||
|
||||
/** 根据账号详情创建任务设置初始草稿。 */
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { AccountDetail, AccountTaskSettings, AccountTaskSummary } from '../../../shared/api-contract';
|
||||
import type { AccountDetail,AccountTaskSettings,AccountTaskSummary } from './api';
|
||||
|
||||
/** 账号任务类型。 */
|
||||
export type AccountTaskType = 'auto_rate' | 'auto_polish';
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, test } from 'vitest';
|
||||
import { describe,expect,test } from 'vitest';
|
||||
import { shouldSaveNotificationBindings } from './accountBindings';
|
||||
|
||||
describe('notification binding save guard', /* 当前回调处理用户交互或异步状态变化。 */ () => {
|
||||
|
||||
@@ -1,12 +1,22 @@
|
||||
import { get, post, put, del, postForm, type RequestControlOptions } from '../../../shared/http/client';
|
||||
import {
|
||||
SessionResponse, AccountDetail, AccountSummaryResponse, Order, PaginatedResponse,
|
||||
AdminStats, DashboardStats, Card, SystemSettings, OrderAnalytics,
|
||||
Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction, AutomationTriggerType,
|
||||
NotificationChannel, NotificationEventType, AccountTaskSettings, ChatSession, ChatMessage, ItemListEnvelope, AutomationIssuesEnvelope,
|
||||
CookieSettingsResponse, CookieProfileResponse, ItemDetailResponse, ItemPublishResponse, ItemSyncResponse, OrderDTOResponse, OrderDetailResponse, OrderSingleRefreshResponse, OrderBatchResponse, OrderRefreshResponse, OrderRefreshJobStartResponse, OrderRefreshJobStatusResponse, OrderRefreshJobCancelResponse, AutomationRuleResponse, AutomationRulePageResponse, AIReplySettingsResponse, AIModelsResponse, UserSettingResponse, CardBatchResponse, CardAppendResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchListResponse, BatchIDResponse, ItemPublishBatchResponse, BatchCancelResponse, MutationIDResponse, OperationResponse, NotificationChannelResponse, NotificationBinding, AccountBindingsResponse, CardListResponse, KeywordTypedResponse, DefaultReplyResponse, AccountTaskSettingsResponse, AccountTaskRunResponseEnvelope, AdminStatsResponse, DashboardStatsResponse, OrderAnalyticsResponse, QRLoginGenerateResponse, QRLoginStatusResponse, QRLoginVerificationResponse, ValidOrderResponse, ValidOrdersResponse
|
||||
} from '../../../shared/api-contract';
|
||||
import { collectionFrom, objectFrom } from '../../../shared/http/contract';
|
||||
AIReplySettings,
|
||||
AIReplySettingsResponse,
|
||||
AccountBindingsResponse,
|
||||
AccountDetail,AccountSummaryResponse,
|
||||
AccountTaskRunResponseEnvelope,
|
||||
AccountTaskSettings,
|
||||
AccountTaskSettingsResponse,
|
||||
CookieProfileResponse,
|
||||
CookieSettingsResponse,
|
||||
NotificationChannel,
|
||||
NotificationChannelResponse,
|
||||
NotificationEventType,
|
||||
OperationResponse,
|
||||
QRLoginGenerateResponse,QRLoginStatusResponse,QRLoginVerificationResponse
|
||||
} from '../../../shared/api-contract/accounts';
|
||||
import { del,get,post,put,type RequestControlOptions } from '../../../shared/http/client';
|
||||
import { collectionFrom,objectFrom } from '../../../shared/http/contract';
|
||||
export type * from '../../../shared/api-contract/accounts';
|
||||
// Accounts
|
||||
// addAccount 新增账号。
|
||||
export const addAccount = async (id: string, value: string, loginMethod?: string): Promise<OperationResponse> => {
|
||||
@@ -278,13 +288,6 @@ const parseNotificationEventTypes = (raw: unknown): NotificationEventType[] => {
|
||||
return raw.split(/[,\s;]+/).map(/* 当前回调用于处理集合元素或接口响应。 */ v => v.trim()).filter(Boolean) as NotificationEventType[];
|
||||
};
|
||||
|
||||
// stringifyNotificationEventTypes 序列化通知事件类型。
|
||||
const stringifyNotificationEventTypes = (events?: NotificationEventType[]): string => {
|
||||
// clean 清理后的事件类型列表,用于当前 API 处理流程。
|
||||
const clean = Array.from(new Set((events || []).filter(Boolean)));
|
||||
return clean.length > 0 ? JSON.stringify(clean) : '';
|
||||
};
|
||||
|
||||
// getNotificationChannels 读取通知渠道。
|
||||
export const getNotificationChannels = async (options?: RequestControlOptions): Promise<{ /** success 表示是否成功。 */ success: boolean; /** data 表示数据。 */ data?: NotificationChannel[] }> => {
|
||||
// result 接口响应结果,用于当前 API 处理流程。
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Bot,Loader2,Save,Settings,X } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { Bot, Loader2, Save, Settings, X } from 'lucide-react';
|
||||
import type { AccountDetail, AIReplySettings } from '../../../../shared/api-contract';
|
||||
import type { AccountDetail,AIReplySettings } from '../api';
|
||||
|
||||
// AccountAISettingsModalProps 描述账号 AI 设置弹窗需要的状态和回调。
|
||||
export interface AccountAISettingsModalProps {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { CalendarClock,Loader2,MessageSquareQuote,Play,Save,Sparkles,X } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { CalendarClock, Loader2, MessageSquareQuote, Play, Save, Sparkles, X } from 'lucide-react';
|
||||
import { AccountDetail, AccountTaskSettings } from '../../../../shared/api-contract';
|
||||
import { AccountDetail,AccountTaskSettings } from '../api';
|
||||
import { useAccountAutomation } from '../accountAutomationHooks';
|
||||
|
||||
interface Props {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { AlertCircle,Bot,CalendarClock,Check,Clock,Edit2,Loader2,MessageCircle,Power,QrCode,RefreshCw,Sparkles,Trash2,User } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { AlertCircle, Bot, CalendarClock, Check, Clock, Loader2, MessageCircle, Power, QrCode, RefreshCw, Sparkles, Trash2, User, Edit2 } from 'lucide-react';
|
||||
import type { AccountDetail } from '../../../../shared/api-contract';
|
||||
import type { AccountDetail } from '../api';
|
||||
import { accountRuntimePresentation } from '../runtime';
|
||||
|
||||
// AccountCardProps 描述账号卡片展示所需的数据和动作。
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { AlertCircle,Loader2,Trash2,X } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { AlertCircle, Loader2, Trash2, X } from 'lucide-react';
|
||||
import type { AccountDetail } from '../../../../shared/api-contract';
|
||||
import type { AccountDetail } from '../api';
|
||||
|
||||
// AccountDeleteDialogProps 描述账号删除确认框需要的状态和回调。
|
||||
export interface AccountDeleteDialogProps {
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { Bell,Check,Clock,Eye,EyeOff,Key,Loader2,X } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { Bell, Check, Clock, Eye, EyeOff, Key, Loader2, X } from 'lucide-react';
|
||||
import type { NotificationChannel } from '../api';
|
||||
import type { AccountEditForm,AccountEditModalProps } from '../types';
|
||||
import { SquareQRCode } from './SquareQRCode';
|
||||
import type { NotificationChannel } from '../../../../shared/api-contract';
|
||||
import type { AccountEditForm, AccountEditModalProps } from '../types';
|
||||
|
||||
// AccountEditModal 负责账号备注、暂停、登录信息和通知绑定的编辑界面。
|
||||
export const AccountEditModal: React.FC<AccountEditModalProps> = ({
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Check,Loader2,X } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { Check, Loader2, X } from 'lucide-react';
|
||||
import type { AccountDetail } from '../../../../shared/api-contract';
|
||||
import type { AccountDetail } from '../api';
|
||||
import { RiskVerificationPanel } from './RiskVerificationPanel';
|
||||
import { SquareQRCode } from './SquareQRCode';
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import React from 'react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { expect, test } from 'vitest';
|
||||
import { expect,test } from 'vitest';
|
||||
import { RiskVerificationPanel } from './RiskVerificationPanel';
|
||||
|
||||
test('risk verification panel explains automatic refresh without manual controls', /* 当前回调处理用户交互或异步状态变化。 */ () => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { AlertTriangle,Loader2 } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { AlertTriangle, Loader2 } from 'lucide-react';
|
||||
|
||||
interface RiskVerificationPanelProps {
|
||||
/** faceQrUrl 表示人脸验证二维码地址。 */ faceQrUrl?: string;
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import React from 'react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { expect, test } from 'vitest';
|
||||
import { expect,test } from 'vitest';
|
||||
import { SquareQRCode } from './SquareQRCode';
|
||||
|
||||
test('login QR code preserves a square aspect ratio without stretching', /* 当前回调处理用户交互或异步状态变化。 */ () => {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// @vitest-environment jsdom
|
||||
import { fireEvent, render, screen, cleanup } from '@testing-library/react';
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { AccountDetail, AIReplySettings } from '../../../../shared/api-contract';
|
||||
import { cleanup,fireEvent,render,screen } from '@testing-library/react';
|
||||
import { afterEach,describe,expect,test,vi } from 'vitest';
|
||||
import type { AccountDetail,AIReplySettings } from '../../../../shared/api-contract/accounts';
|
||||
import { AccountAISettingsModal } from './AccountAISettingsModal';
|
||||
import { AccountCard } from './AccountCard';
|
||||
import { AccountDeleteDialog } from './AccountDeleteDialog';
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
// @vitest-environment jsdom
|
||||
import { renderHook, waitFor } from '@testing-library/react';
|
||||
import { renderHook,waitFor } from '@testing-library/react';
|
||||
import { act } from 'react';
|
||||
import { beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { AccountDetail } from '../../../shared/api-contract';
|
||||
import { getAccountDetails, getAccountRuntimeStatuses, getAllAISettings } from './api';
|
||||
import { beforeEach,describe,expect,test,vi } from 'vitest';
|
||||
import type { AccountDetail } from '../../../shared/api-contract/accounts';
|
||||
import { getAccountDetails,getAccountRuntimeStatuses,getAllAISettings } from './api';
|
||||
import { useAccountsData } from './hooks';
|
||||
|
||||
vi.mock('./api', /* accountsApiMockFactory 提供账号列表 Hook 的确定性 API 替身。 */ () => ({
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useCallback, useEffect, useRef, useState, type Dispatch, type SetStateAction } from 'react';
|
||||
import { getAccountDetails, getAccountRuntimeStatuses, getAllAISettings } from './api';
|
||||
import type { AccountDetail } from '../../../shared/api-contract';
|
||||
import { useCallback,useEffect,useRef,useState,type Dispatch,type SetStateAction } from 'react';
|
||||
import type { AccountDetail } from './api';
|
||||
import { getAccountDetails,getAccountRuntimeStatuses,getAllAISettings } from './api';
|
||||
import { mergeAccountRuntimeStatuses } from './runtime';
|
||||
import type { AccountAISettingsState } from './types';
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// @vitest-environment jsdom
|
||||
import { cleanup,fireEvent,render,screen,waitFor } from '@testing-library/react';
|
||||
import React from 'react';
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { AccountDetail } from '../../../../shared/api-contract';
|
||||
import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest';
|
||||
import type { AccountDetail } from '../../../../shared/api-contract/accounts';
|
||||
|
||||
// accountListMocks 保存 AccountList 页面测试使用的 API、Hook 和轮询替身。
|
||||
const accountListMocks = vi.hoisted(/* accountListMockFactory 创建页面测试共享替身。 */ () => ({
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
import React, { useState } from 'react';
|
||||
import { Loader2,QrCode,User } from 'lucide-react';
|
||||
import React,{ useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { AccountDetail } from '../../../../shared/api-contract';
|
||||
import { AccountDetail } from '../api';
|
||||
import {
|
||||
updateAccountStatus,
|
||||
deleteAccount,
|
||||
refreshAccountProfile,
|
||||
deleteAccount,
|
||||
refreshAccountProfile,
|
||||
updateAccountStatus,
|
||||
} from '../api';
|
||||
import { Loader2, QrCode, User } from 'lucide-react';
|
||||
import AccountAutomationModal from '../components/AccountAutomationModal';
|
||||
import { AccountEditModal } from '../components/AccountEditModal';
|
||||
import { AccountAISettingsModal } from '../components/AccountAISettingsModal';
|
||||
import AccountAutomationModal from '../components/AccountAutomationModal';
|
||||
import { AccountCard } from '../components/AccountCard';
|
||||
import { AccountDeleteDialog } from '../components/AccountDeleteDialog';
|
||||
import { AccountEditModal } from '../components/AccountEditModal';
|
||||
import { AccountQRCodeModal } from '../components/AccountQRCodeModal';
|
||||
import { useAccountsData } from '../hooks';
|
||||
import { useAccountQRCodeLogin } from '../qrLogin';
|
||||
import { useAccountSubmodules, type AccountModalType } from '../submoduleHooks';
|
||||
import { useAccountSubmodules,type AccountModalType } from '../submoduleHooks';
|
||||
import type { AccountEditForm } from '../types';
|
||||
|
||||
// AccountList 渲染账号列表组件。
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { AccountDetail } from '../../../shared/api-contract';
|
||||
import { act,renderHook } from '@testing-library/react';
|
||||
import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest';
|
||||
import type { AccountDetail } from '../../../shared/api-contract/accounts';
|
||||
|
||||
// qrLoginMocks 保存二维码登录协调器测试使用的接口替身。
|
||||
const qrLoginMocks = vi.hoisted(/* qrLoginMockFactory 创建二维码登录 API 替身。 */ () => ({
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import type { AccountDetail } from '../../../shared/api-contract';
|
||||
import { checkQRLoginStatus, completeQRVerification, generateQRLogin } from './api';
|
||||
import { createLatestRequestGate, createQRLoginPoller } from './qrPolling';
|
||||
import { useEffect,useRef,useState } from 'react';
|
||||
import type { AccountDetail } from './api';
|
||||
import { checkQRLoginStatus,completeQRVerification,generateQRLogin } from './api';
|
||||
import { createLatestRequestGate,createQRLoginPoller } from './qrPolling';
|
||||
|
||||
// AccountQRCodeLoginOptions 描述二维码登录协调器需要的页面刷新回调。
|
||||
export interface AccountQRCodeLoginOptions {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, expect, test, vi } from 'vitest';
|
||||
import { createLatestRequestGate, createQRLoginPoller } from './qrPolling';
|
||||
import { afterEach,expect,test,vi } from 'vitest';
|
||||
import { createLatestRequestGate,createQRLoginPoller } from './qrPolling';
|
||||
|
||||
afterEach(/* 当前回调处理用户交互或异步状态变化。 */ () => {
|
||||
vi.useRealTimers();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, test } from 'vitest';
|
||||
import type { AccountDetail } from '../../../shared/api-contract';
|
||||
import { accountRuntimePresentation, isOlderStatus, mergeAccountRuntimeStatuses } from './runtime';
|
||||
import { describe,expect,test } from 'vitest';
|
||||
import type { AccountDetail } from '../../../shared/api-contract/accounts';
|
||||
import { accountRuntimePresentation,isOlderStatus,mergeAccountRuntimeStatuses } from './runtime';
|
||||
|
||||
// account 创建运行状态测试使用的最小账号对象。
|
||||
const account = (overrides: Partial<AccountDetail> = {}): AccountDetail => ({
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { AccountDetail } from './api';
|
||||
import type { AccountRuntimeStatus } from './api';
|
||||
import type { AccountDetail } from '../../../shared/api-contract';
|
||||
import type { AccountRuntimePresentation } from './types';
|
||||
|
||||
// isOlderStatus 判断传入的运行时快照是否早于账号当前已展示的快照。
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { expect, test } from 'vitest';
|
||||
import type { AccountDetail } from '../../../shared/api-contract';
|
||||
import { expect,test } from 'vitest';
|
||||
import type { AccountDetail } from '../../../shared/api-contract/accounts';
|
||||
import {
|
||||
buildAccountLoginInfoUpdate,
|
||||
isCurrentAccountRequest,
|
||||
passwordLoginViewFromStatus,
|
||||
shouldUpdateAccountPause,
|
||||
buildAccountLoginInfoUpdate,
|
||||
isCurrentAccountRequest,
|
||||
passwordLoginViewFromStatus,
|
||||
shouldUpdateAccountPause,
|
||||
} from './state';
|
||||
|
||||
// account 是账号编辑状态测试使用的最小领域对象。
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { AccountDetail } from '../../../shared/api-contract';
|
||||
import type { AccountDetail } from './api';
|
||||
import type { PasswordLoginStatusResponse } from './api';
|
||||
import type { AccountEditForm, PasswordLoginView } from './types';
|
||||
import type { AccountEditForm,PasswordLoginView } from './types';
|
||||
|
||||
// AccountLoginEditFields 描述账号编辑表单中参与登录信息比较的字段。
|
||||
export type AccountLoginEditFields = Pick<AccountEditForm, 'username' | 'login_password' | 'show_browser'> & Pick<Partial<AccountEditForm>, 'clear_password'>;
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { Dispatch, SetStateAction } from 'react';
|
||||
import type { AccountDetail, AIReplySettings } from '../../../shared/api-contract';
|
||||
import { act,renderHook } from '@testing-library/react';
|
||||
import type { Dispatch,SetStateAction } from 'react';
|
||||
import { beforeEach,describe,expect,test,vi } from 'vitest';
|
||||
import type { AccountDetail,AIReplySettings } from '../../../shared/api-contract/accounts';
|
||||
import {
|
||||
cancelPasswordLogin,
|
||||
checkPasswordLoginStatus,
|
||||
getAccountAISettings,
|
||||
getAccountBindings,
|
||||
getLongLoginSettings,
|
||||
getNotificationChannels,
|
||||
passwordLogin,
|
||||
setLongLoginSettings,
|
||||
updateAccountAISettings,
|
||||
updateAccountPauseDuration,
|
||||
updateAccountSettings,
|
||||
cancelPasswordLogin,
|
||||
checkPasswordLoginStatus,
|
||||
getAccountAISettings,
|
||||
getAccountBindings,
|
||||
getLongLoginSettings,
|
||||
getNotificationChannels,
|
||||
passwordLogin,
|
||||
setLongLoginSettings,
|
||||
updateAccountAISettings,
|
||||
updateAccountPauseDuration,
|
||||
updateAccountSettings,
|
||||
} from './api';
|
||||
import { useAccountSubmodules, type AccountModalType } from './submoduleHooks';
|
||||
import { useAccountSubmodules,type AccountModalType } from './submoduleHooks';
|
||||
import type { AccountEditForm } from './types';
|
||||
|
||||
vi.mock('./api', /* accountsSubmoduleApiMockFactory 提供账号子模块 Hook 的确定性 API 替身。 */ () => ({
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { useCallback, useEffect, useRef, useState, type Dispatch, type SetStateAction } from 'react';
|
||||
import type { AccountDetail, AIReplySettings, NotificationChannel } from '../../../shared/api-contract';
|
||||
import { cancelPasswordLogin, checkPasswordLoginStatus, getAccountAISettings, getAccountBindings, getLongLoginSettings, getNotificationChannels, passwordLogin, setLongLoginSettings, updateAccountAISettings, updateAccountPauseDuration, updateAccountSettings } from './api';
|
||||
import { buildAccountLoginInfoUpdate, isCurrentAccountRequest, passwordLoginViewFromStatus, shouldUpdateAccountPause } from './state';
|
||||
import type { AccountEditForm, LongLoginState, PasswordLoginView } from './types';
|
||||
import { useCallback,useEffect,useRef,useState,type Dispatch,type SetStateAction } from 'react';
|
||||
import type { AccountDetail,AIReplySettings,NotificationChannel } from './api';
|
||||
import { shouldSaveNotificationBindings } from './accountBindings';
|
||||
import { cancelPasswordLogin,checkPasswordLoginStatus,getAccountAISettings,getAccountBindings,getLongLoginSettings,getNotificationChannels,passwordLogin,setLongLoginSettings,updateAccountAISettings,updateAccountPauseDuration,updateAccountSettings } from './api';
|
||||
import { buildAccountLoginInfoUpdate,isCurrentAccountRequest,passwordLoginViewFromStatus,shouldUpdateAccountPause } from './state';
|
||||
import type { AccountEditForm,LongLoginState,PasswordLoginView } from './types';
|
||||
|
||||
/** AccountList 当前编辑弹窗类型。 */
|
||||
export type AccountModalType = 'edit' | 'ai-settings' | null;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { Dispatch, SetStateAction } from 'react';
|
||||
import type { AccountDetail, AIReplySettings, NotificationChannel } from '../../../shared/api-contract';
|
||||
import type { Dispatch,SetStateAction } from 'react';
|
||||
import type { AccountDetail,AIReplySettings,NotificationChannel } from './api';
|
||||
|
||||
// AccountEditForm 描述账号编辑弹窗中的可编辑字段。
|
||||
export interface AccountEditForm {
|
||||
|
||||
@@ -1,27 +1,39 @@
|
||||
import { afterEach, expect, test, vi } from 'vitest';
|
||||
import { afterEach,expect,test,vi } from 'vitest';
|
||||
import {
|
||||
addAccount,
|
||||
cancelPasswordLogin,
|
||||
checkPasswordLoginStatus,
|
||||
checkQRLoginStatus, completeQRVerification, generateQRLogin,
|
||||
getAllAISettings, getAccountAISettings, updateAccountAISettings,
|
||||
getAccountDetails, getAccountRuntimeStatuses, updateAccountStatus, deleteAccount,
|
||||
passwordLogin,
|
||||
updateAccountCookie,
|
||||
updateAccountLoginInfo,
|
||||
updateAccountSettings, updateAccountRemark, updateAccountAutoConfirm, updateAccountPauseDuration, getLongLoginSettings, setLongLoginSettings, refreshAccountProfile,
|
||||
getAccountTaskSettings, updateAccountTaskSettings,
|
||||
runAccountTask,
|
||||
addAccount,
|
||||
cancelPasswordLogin,
|
||||
checkPasswordLoginStatus,
|
||||
checkQRLoginStatus,completeQRVerification,
|
||||
deleteAccount,
|
||||
generateQRLogin,
|
||||
getAccountAISettings,
|
||||
getAccountDetails,getAccountRuntimeStatuses,
|
||||
getAccountTaskSettings,
|
||||
getAllAISettings,
|
||||
getLongLoginSettings,
|
||||
passwordLogin,
|
||||
refreshAccountProfile,
|
||||
runAccountTask,
|
||||
setLongLoginSettings,
|
||||
updateAccountAISettings,
|
||||
updateAccountAutoConfirm,
|
||||
updateAccountCookie,
|
||||
updateAccountLoginInfo,
|
||||
updateAccountPauseDuration,
|
||||
updateAccountRemark,
|
||||
updateAccountSettings,
|
||||
updateAccountStatus,
|
||||
updateAccountTaskSettings,
|
||||
} from './accounts/api';
|
||||
import { appendCardData, batchCreateCards, createCard, deleteCard, getCardDetails, getCards, updateCard } from './cards/api';
|
||||
import { getChatMessagePage, getChatMessages, getChatSessionPage, getChatSessions, markChatRead, sendChatImage, sendChatMessage } from './chat/api';
|
||||
import { getDashboardStats, getOrderAnalytics, getValidOrders } from './dashboard/api';
|
||||
import { createItem, deleteItem, deleteItemPublishBatch, cancelItemPublishBatch, getItemDetail, getItemPublishBatch, getItemPublishBatches, getItems, previewItemPublishBatch, publishItem, recommendPublishCategory, retryFailedItemPublishBatch, startItemPublishBatch, syncItemsFromAccount, updateItem } from './items/api';
|
||||
import { createNotificationChannel, deleteAccountNotifications, deleteMessageNotification, deleteNotificationChannel, getAccountBindings, getMessageNotifications, getNotificationChannels, setAccountBindings, setMessageNotification, testNotificationChannel, updateNotificationChannel } from './notifications/api';
|
||||
import { cancelOrderRefreshJob, deleteOrder, getAdminStats, getOrderDetail, getOrders, importOrders, manualShipOrder, syncOrders, syncSingleOrder, updateOrder } from './orders/api';
|
||||
import { clearDefaultReplyRecords, deleteDefaultReply, deleteReplyRule, deleteShippingRule, getAutomationIssues, getDefaultReplies, getDefaultReply, getReplyRules, getShippingRules, getShippingRulesPage, resolveAutomationRun, resolveDeferredAutomationTask, updateDefaultReply, updateReplyRule, updateShippingRule } from './rules/api';
|
||||
import { initializeAdmin, login, logout, verifySession } from './session/api';
|
||||
import { changePassword, fetchAIModels, getSystemSettings, updateLoginCredentials, updateSystemSettings } from './settings/api';
|
||||
import { appendCardData,batchCreateCards,createCard,deleteCard,getCardDetails,getCards,updateCard } from './cards/api';
|
||||
import { getChatMessagePage,getChatMessages,getChatSessionPage,getChatSessions,markChatRead,sendChatImage,sendChatMessage } from './chat/api';
|
||||
import { getDashboardStats,getOrderAnalytics,getValidOrders } from './dashboard/api';
|
||||
import { cancelItemPublishBatch,createItem,deleteItem,deleteItemPublishBatch,getItemDetail,getItemPublishBatch,getItemPublishBatches,getItems,previewItemPublishBatch,publishItem,recommendPublishCategory,retryFailedItemPublishBatch,startItemPublishBatch,syncItemsFromAccount,updateItem } from './items/api';
|
||||
import { createNotificationChannel,deleteAccountNotifications,deleteMessageNotification,deleteNotificationChannel,getAccountBindings,getMessageNotifications,getNotificationChannels,setAccountBindings,setMessageNotification,testNotificationChannel,updateNotificationChannel } from './notifications/api';
|
||||
import { cancelOrderRefreshJob,deleteOrder,getAdminStats,getOrderDetail,getOrders,importOrders,manualShipOrder,syncOrders,syncSingleOrder,updateOrder } from './orders/api';
|
||||
import { clearDefaultReplyRecords,deleteDefaultReply,deleteReplyRule,deleteShippingRule,getAutomationIssues,getDefaultReplies,getDefaultReply,getReplyRules,getShippingRules,getShippingRulesPage,resolveAutomationRun,resolveDeferredAutomationTask,updateDefaultReply,updateReplyRule,updateShippingRule } from './rules/api';
|
||||
import { initializeAdmin,login,logout,verifySession } from './session/api';
|
||||
import { changePassword,fetchAIModels,getSystemSettings,updateLoginCredentials,updateSystemSettings } from './settings/api';
|
||||
import { getHealth } from './system/api';
|
||||
|
||||
afterEach(() => {
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { get, post, put, del, postForm, type RequestControlOptions } from '../../../shared/http/client';
|
||||
import {
|
||||
SessionResponse, AccountDetail, AccountSummaryResponse, Order, PaginatedResponse,
|
||||
AdminStats, DashboardStats, Card, SystemSettings, OrderAnalytics,
|
||||
Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction, AutomationTriggerType,
|
||||
NotificationChannel, NotificationEventType, AccountTaskSettings, ChatSession, ChatMessage, ItemListEnvelope, AutomationIssuesEnvelope,
|
||||
CookieSettingsResponse, CookieProfileResponse, ItemDetailResponse, ItemPublishResponse, ItemSyncResponse, OrderDTOResponse, OrderDetailResponse, OrderSingleRefreshResponse, OrderBatchResponse, OrderRefreshResponse, OrderRefreshJobStartResponse, OrderRefreshJobStatusResponse, OrderRefreshJobCancelResponse, AutomationRuleResponse, AutomationRulePageResponse, AIReplySettingsResponse, AIModelsResponse, UserSettingResponse, CardBatchResponse, CardAppendResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchListResponse, BatchIDResponse, ItemPublishBatchResponse, BatchCancelResponse, MutationIDResponse, OperationResponse, NotificationChannelResponse, NotificationBinding, AccountBindingsResponse, CardListResponse, KeywordTypedResponse, DefaultReplyResponse, AccountTaskSettingsResponse, AccountTaskRunResponseEnvelope, AdminStatsResponse, DashboardStatsResponse, OrderAnalyticsResponse, QRLoginGenerateResponse, QRLoginStatusResponse, QRLoginVerificationResponse, ValidOrderResponse, ValidOrdersResponse
|
||||
} from '../../../shared/api-contract';
|
||||
import { collectionFrom, objectFrom } from '../../../shared/http/contract';
|
||||
Card,
|
||||
CardAppendResponse,
|
||||
CardBatchResponse,
|
||||
MutationIDResponse,OperationResponse
|
||||
} from '../../../shared/api-contract/cards';
|
||||
import { del,get,post,postForm,put,type RequestControlOptions } from '../../../shared/http/client';
|
||||
import { collectionFrom } from '../../../shared/http/contract';
|
||||
export type * from '../../../shared/api-contract/cards';
|
||||
// Cards
|
||||
// normalizeCard 归一化卡密数据。
|
||||
const normalizeCard = (item: any): Card => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { expect, test } from 'vitest';
|
||||
import type { Card } from '../../../shared/api-contract';
|
||||
import { canSubmitAppend, filterCards, isCurrentCardRequest, previewAppendContent } from './batchState';
|
||||
import { expect,test } from 'vitest';
|
||||
import type { Card } from '../../../shared/api-contract/cards';
|
||||
import { canSubmitAppend,filterCards,isCurrentCardRequest,previewAppendContent } from './batchState';
|
||||
|
||||
// cards 是卡密筛选测试使用的最小卡密组列表。
|
||||
const cards = [
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Card } from '../../../shared/api-contract';
|
||||
import type { Card } from './api';
|
||||
|
||||
// filterCards 按类型和名称筛选卡密组,两个条件同时满足才保留。
|
||||
export const filterCards = (
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { Card } from '../../../shared/api-contract';
|
||||
import { createCard, deleteCard, updateCard } from './api';
|
||||
import { act,renderHook } from '@testing-library/react';
|
||||
import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest';
|
||||
import type { Card } from '../../../shared/api-contract/cards';
|
||||
import { useCardActions } from './cardActions';
|
||||
|
||||
// cardActionMocks 保存卡密动作 Hook 测试使用的 API 替身。
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { useCallback, useMemo, useState, type Dispatch, type SetStateAction } from 'react';
|
||||
import type { Card } from '../../../shared/api-contract';
|
||||
import { createCard, deleteCard, updateCard } from './api';
|
||||
import { useCallback,useMemo,useState,type Dispatch,type SetStateAction } from 'react';
|
||||
import type { Card } from './api';
|
||||
import { createCard,deleteCard,updateCard } from './api';
|
||||
import { filterCards } from './batchState';
|
||||
import type { AddCardForm, EditCardForm } from './types';
|
||||
import type { AddCardForm,EditCardForm } from './types';
|
||||
|
||||
// emptyAddForm 创建新增卡密组表单的初始值。
|
||||
export const emptyAddForm = (): AddCardForm => ({
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { FileDown,ListPlus,Loader2,Plus,Upload,X } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { FileDown, ListPlus, Loader2, Plus, Upload, X } from 'lucide-react';
|
||||
import type { Card } from '../../../../shared/api-contract';
|
||||
import type { Card } from '../api';
|
||||
import type { CardBatchModalProps } from '../types';
|
||||
|
||||
// BatchCardImportModal 负责卡密批量创建和单组库存追加的交互界面。
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Code,CreditCard,FileText,Image as ImageIcon } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { Code, CreditCard, FileText, Image as ImageIcon } from 'lucide-react';
|
||||
import type { Card } from '../../../../shared/api-contract';
|
||||
import type { Card } from '../api';
|
||||
|
||||
// CardIconProps 描述库存图标所需的卡密类型参数。
|
||||
interface CardIconProps {
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { Card } from '../../../shared/api-contract';
|
||||
import { appendCardData, batchCreateCards, getCards } from './api';
|
||||
import { useCardBatchActions, useCardsData } from './hooks';
|
||||
import { act,renderHook,waitFor } from '@testing-library/react';
|
||||
import { beforeEach,describe,expect,test,vi } from 'vitest';
|
||||
import type { Card } from '../../../shared/api-contract/cards';
|
||||
import { appendCardData,batchCreateCards,getCards } from './api';
|
||||
import { useCardBatchActions,useCardsData } from './hooks';
|
||||
|
||||
vi.mock('./api', /* cardsApiMockFactory 提供卡密 Hook 的确定性 API 替身。 */ () => ({
|
||||
appendCardData: vi.fn(),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type Dispatch, type SetStateAction } from 'react';
|
||||
import { appendCardData, batchCreateCards, getCards } from './api';
|
||||
import type { Card } from '../../../shared/api-contract';
|
||||
import { canSubmitAppend, isCurrentCardRequest, previewAppendContent } from './batchState';
|
||||
import { useCallback,useEffect,useMemo,useRef,useState,type Dispatch,type SetStateAction } from 'react';
|
||||
import type { Card } from './api';
|
||||
import { appendCardData,batchCreateCards,getCards } from './api';
|
||||
import { canSubmitAppend,isCurrentCardRequest,previewAppendContent } from './batchState';
|
||||
import type { CardBatchState } from './types';
|
||||
|
||||
// CardsDataResult 暴露卡密库存、加载状态和可复用刷新动作。
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
// @vitest-environment jsdom
|
||||
import React from 'react';
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { Card } from '../../../../shared/api-contract';
|
||||
import { cleanup,fireEvent,render,screen,waitFor } from '@testing-library/react';
|
||||
import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest';
|
||||
import type { Card } from '../../../../shared/api-contract/cards';
|
||||
|
||||
// cardListMocks 保存卡密页面测试使用的 Hook、API 和批量弹窗替身。
|
||||
const cardListMocks = vi.hoisted(/* cardListMockFactory 创建卡密页面共享替身。 */ () => ({
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { Copy,CreditCard,Edit,FileText,Image as ImageIcon,Package,Plus,Save,Search,SlidersHorizontal,Trash2,Upload,X } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { Card } from '../../../../shared/api-contract';
|
||||
import { Plus, CreditCard, FileText, Image as ImageIcon, Edit, Trash2, Save, X, Eye, EyeOff, Package, Copy, Upload, Loader2, Search, SlidersHorizontal } from 'lucide-react';
|
||||
import { Card } from '../api';
|
||||
import { useCardActions } from '../cardActions';
|
||||
import { BatchCardImportModal } from '../components/BatchCardImportModal';
|
||||
import { CardIcon } from '../components/CardIcon';
|
||||
import { useCardBatchActions, useCardsData } from '../hooks';
|
||||
import { useCardActions } from '../cardActions';
|
||||
import { useCardBatchActions,useCardsData } from '../hooks';
|
||||
|
||||
// CardList 渲染卡密列表组件。
|
||||
const CardList: React.FC = () => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { Dispatch, SetStateAction } from 'react';
|
||||
import type { Card, CardAppendResponse, CardBatchResponse } from '../../../shared/api-contract';
|
||||
import type { Dispatch,SetStateAction } from 'react';
|
||||
import type { Card,CardAppendResponse,CardBatchResponse } from './api';
|
||||
|
||||
// AddCardForm 描述新增卡密组弹窗中的可编辑字段。
|
||||
export interface AddCardForm {
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { get, post, put, del, postForm, type RequestControlOptions } from '../../../shared/http/client';
|
||||
import {
|
||||
SessionResponse, AccountDetail, AccountSummaryResponse, Order, PaginatedResponse,
|
||||
AdminStats, DashboardStats, Card, SystemSettings, OrderAnalytics,
|
||||
Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction, AutomationTriggerType,
|
||||
NotificationChannel, NotificationEventType, AccountTaskSettings, ChatSession, ChatMessage, ItemListEnvelope, AutomationIssuesEnvelope,
|
||||
CookieSettingsResponse, CookieProfileResponse, ItemDetailResponse, ItemPublishResponse, ItemSyncResponse, OrderDTOResponse, OrderDetailResponse, OrderSingleRefreshResponse, OrderBatchResponse, OrderRefreshResponse, OrderRefreshJobStartResponse, OrderRefreshJobStatusResponse, OrderRefreshJobCancelResponse, AutomationRuleResponse, AutomationRulePageResponse, AIReplySettingsResponse, AIModelsResponse, UserSettingResponse, CardBatchResponse, CardAppendResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchListResponse, BatchIDResponse, ItemPublishBatchResponse, BatchCancelResponse, MutationIDResponse, OperationResponse, NotificationChannelResponse, NotificationBinding, AccountBindingsResponse, CardListResponse, KeywordTypedResponse, DefaultReplyResponse, AccountTaskSettingsResponse, AccountTaskRunResponseEnvelope, AdminStatsResponse, DashboardStatsResponse, OrderAnalyticsResponse, QRLoginGenerateResponse, QRLoginStatusResponse, QRLoginVerificationResponse, ValidOrderResponse, ValidOrdersResponse
|
||||
} from '../../../shared/api-contract';
|
||||
import { collectionFrom, objectFrom } from '../../../shared/http/contract';
|
||||
AccountDetail,
|
||||
ChatMessage,
|
||||
ChatSession,
|
||||
OperationResponse
|
||||
} from '../../../shared/api-contract/chat';
|
||||
import { get,post,postForm,type RequestControlOptions } from '../../../shared/http/client';
|
||||
import { objectFrom } from '../../../shared/http/contract';
|
||||
export type * from '../../../shared/api-contract/chat';
|
||||
import type { ChatReadReceipt } from './types';
|
||||
|
||||
/** 聊天账号选择器读取非敏感账号摘要。 */
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { AccountDetail, ChatMessage, ChatSession } from '../../../shared/api-contract';
|
||||
import { getAccountDetails, getAccountRuntimeStatuses, getChatMessagePage, getChatSessionPage, markChatRead, sendChatImage, sendChatMessage } from './api';
|
||||
import { act,renderHook,waitFor } from '@testing-library/react';
|
||||
import { beforeEach,describe,expect,test,vi } from 'vitest';
|
||||
import type { AccountDetail,ChatMessage,ChatSession } from '../../../shared/api-contract/chat';
|
||||
import { getAccountDetails,getAccountRuntimeStatuses,getChatMessagePage,getChatSessionPage,markChatRead,sendChatImage,sendChatMessage } from './api';
|
||||
import { useChat } from './hooks';
|
||||
import { publishChatConnectionState, publishChatLiveMessage } from './liveEvents';
|
||||
import { publishChatConnectionState,publishChatLiveMessage } from './liveEvents';
|
||||
|
||||
vi.mock('./api', /* chatApiMockFactory 提供聊天 Hook 的确定性 API 替身。 */ () => ({
|
||||
getAccountDetails: vi.fn(),
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
||||
import type React from 'react';
|
||||
import type { AccountDetail, ChatMessage, ChatSession } from '../../../shared/api-contract';
|
||||
import { emojiURL, renderXianyuText, xianyuEmojis } from '../../../chatEmojis';
|
||||
import { getAccountDetails, getAccountRuntimeStatuses, getChatMessagePage, getChatSessionPage, markChatRead, sendChatImage, sendChatMessage } from './api';
|
||||
import { publishChatUnreadStatus, subscribeToChatLiveEvents } from './liveEvents';
|
||||
import { collectChatReadReceipts, filterChatSessions, formatClock, isChatAbortError, isCurrentChatRequest, markOutgoingMessagesReadByIncoming, mergeLiveMessage, mergeOlderMessages, messageTime } from './state';
|
||||
import type { ChatFeatureState, ChatLiveState, SessionsByAccount } from './types';
|
||||
import { useCallback,useEffect,useLayoutEffect,useMemo,useRef,useState } from 'react';
|
||||
import { emojiURL,renderXianyuText,xianyuEmojis } from '../../../chatEmojis';
|
||||
import type { AccountDetail,ChatMessage,ChatSession } from './api';
|
||||
import { getAccountDetails,getAccountRuntimeStatuses,getChatMessagePage,getChatSessionPage,markChatRead,sendChatImage,sendChatMessage } from './api';
|
||||
import { publishChatUnreadStatus,subscribeToChatLiveEvents } from './liveEvents';
|
||||
import { collectChatReadReceipts,filterChatSessions,formatClock,isChatAbortError,isCurrentChatRequest,markOutgoingMessagesReadByIncoming,mergeLiveMessage,mergeOlderMessages,messageTime } from './state';
|
||||
import type { ChatFeatureState,ChatLiveState,SessionsByAccount } from './types';
|
||||
|
||||
/** PendingImagePreview 描述等待用户确认的本地图片预览及其资源所有权。 */
|
||||
type PendingImagePreview = {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ChatMessage } from '../../../shared/api-contract';
|
||||
import type { ChatMessage } from './api';
|
||||
import type { ChatLiveState } from './types';
|
||||
|
||||
/** ChatLiveEvent 描述全局聊天连接向已挂载聊天页面发布的最小实时事件集合。 */
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import React from 'react';
|
||||
import {
|
||||
AlertCircle, Check, CheckCheck, ImagePlus, Loader2, MessageCircleMore, RefreshCw,
|
||||
Search, Send, Smile, UserRound, Wifi, WifiOff, X,
|
||||
AlertCircle,Check,CheckCheck,ImagePlus,Loader2,MessageCircleMore,RefreshCw,
|
||||
Search,Send,Smile,UserRound,Wifi,WifiOff,X,
|
||||
} from 'lucide-react';
|
||||
import React from 'react';
|
||||
import Lightbox from 'yet-another-react-lightbox';
|
||||
import 'yet-another-react-lightbox/styles.css';
|
||||
import { useChat } from '../hooks';
|
||||
import { unreadBadgeClassName, unreadBadgeLabel } from '../state';
|
||||
import { unreadBadgeClassName,unreadBadgeLabel } from '../state';
|
||||
|
||||
// Chat 展示实时会话、消息分页和消息发送界面。
|
||||
const Chat: React.FC = () => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { expect, test } from 'vitest';
|
||||
import type { ChatMessage, ChatSession } from '../../../shared/api-contract';
|
||||
import { collectChatReadReceipts, filterChatSessions, formatClock, isChatAbortError, isCurrentChatRequest, markOutgoingMessagesReadByIncoming, mergeLiveMessage, mergeOlderMessages, messageTime, unreadBadgeClassName, unreadBadgeLabel } from './state';
|
||||
import { expect,test } from 'vitest';
|
||||
import type { ChatMessage,ChatSession } from '../../../shared/api-contract/chat';
|
||||
import { collectChatReadReceipts,filterChatSessions,formatClock,isChatAbortError,isCurrentChatRequest,markOutgoingMessagesReadByIncoming,mergeLiveMessage,mergeOlderMessages,messageTime,unreadBadgeClassName,unreadBadgeLabel } from './state';
|
||||
|
||||
// sessionFixture 是覆盖搜索、未读筛选和联系人隔离的最小会话数据。
|
||||
const sessionFixture: ChatSession[] = [
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ChatMessage, ChatSession } from '../../../shared/api-contract';
|
||||
import type { ChatMessage,ChatSession } from './api';
|
||||
import type { ChatReadReceipt } from './types';
|
||||
|
||||
/** 将未读数规范为徽标可展示的文本,超过两位数时统一显示 99+。 */
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { ChatMessage } from '../../../shared/api-contract';
|
||||
import { getAccountDetails, getChatSessionPage } from './api';
|
||||
import { act,renderHook } from '@testing-library/react';
|
||||
import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest';
|
||||
import type { ChatMessage } from '../../../shared/api-contract/chat';
|
||||
import { getAccountDetails,getChatSessionPage } from './api';
|
||||
import { publishChatUnreadStatus } from './liveEvents';
|
||||
import { formatChatNewMessageTitle, useChatTitleNotification, useChatTitleNotifier } from './titleNotification';
|
||||
import { formatChatNewMessageTitle,useChatTitleNotification,useChatTitleNotifier } from './titleNotification';
|
||||
|
||||
vi.mock('./api', /* chatApiMockFactory 提供标题通知初始化未读状态读取的确定性 API 替身。 */ () => ({
|
||||
getAccountDetails: vi.fn(),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import type { ChatMessage } from '../../../shared/api-contract';
|
||||
import { getAccountDetails, getChatSessionPage } from './api';
|
||||
import { publishChatConnectionState, publishChatLiveMessage, subscribeToChatUnreadStatus } from './liveEvents';
|
||||
import { useCallback,useEffect,useRef,useState } from 'react';
|
||||
import type { ChatMessage } from './api';
|
||||
import { getAccountDetails,getChatSessionPage } from './api';
|
||||
import { publishChatConnectionState,publishChatLiveMessage,subscribeToChatUnreadStatus } from './liveEvents';
|
||||
|
||||
/** titleFlashIntervalMs 定义浏览器标题在提示文本与原始标题间切换的周期,单位为毫秒。 */
|
||||
const titleFlashIntervalMs = 1_000;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { AccountDetail, ChatMessage, ChatSession } from '../../../shared/api-contract';
|
||||
import type { AccountDetail,ChatMessage,ChatSession } from './api';
|
||||
|
||||
/** 按账号保存会话列表。 */
|
||||
export type SessionsByAccount = Record<string, ChatSession[]>;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React from 'react';
|
||||
import { ShoppingCart } from 'lucide-react';
|
||||
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, BarChart, Bar, Cell } from 'recharts';
|
||||
import React from 'react';
|
||||
import { Area,AreaChart,Bar,BarChart,CartesianGrid,Cell,ResponsiveContainer,Tooltip,XAxis,YAxis } from 'recharts';
|
||||
import type { DashboardChartPoint } from './state';
|
||||
|
||||
/** 趋势图组件的输入参数。 */
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { get, type RequestControlOptions } from '../../../shared/http/client';
|
||||
import { collectionFrom, objectFrom } from '../../../shared/http/contract';
|
||||
import type { DashboardStatsResponse, Item, ItemListEnvelope, Order, OrderAnalyticsResponse, OrderStatus, ValidOrderResponse, ValidOrdersResponse } from '../../../shared/api-contract';
|
||||
import { formatLocalDate } from '../../../dateRange';
|
||||
import type { DashboardStatsResponse,Item,ItemListEnvelope,Order,OrderAnalyticsResponse,OrderStatus,ValidOrderResponse,ValidOrdersResponse } from '../../../shared/api-contract/admin';
|
||||
import { get,type RequestControlOptions } from '../../../shared/http/client';
|
||||
import { collectionFrom,objectFrom } from '../../../shared/http/contract';
|
||||
export type * from '../../../shared/api-contract/admin';
|
||||
|
||||
/** 仪表盘订单明细接口转换后的分页结果。 */
|
||||
export interface ValidOrdersResult {
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { DashboardStats, Item, OrderAnalyticsResponse } from '../../../shared/api-contract';
|
||||
import { getDashboardStats, getItems, getOrderAnalytics, getValidOrders } from './api';
|
||||
import { useDashboard } from './hooks';
|
||||
import { act,renderHook,waitFor } from '@testing-library/react';
|
||||
import { beforeEach,describe,expect,test,vi } from 'vitest';
|
||||
import type { DashboardStats,Item,OrderAnalyticsResponse } from '../../../shared/api-contract/admin';
|
||||
import { getDashboardStats,getItems,getOrderAnalytics,getValidOrders } from './api';
|
||||
import type { UseDashboardOptions } from './hooks';
|
||||
import { useDashboard } from './hooks';
|
||||
|
||||
vi.mock('./api', /* dashboardApiMockFactory 提供仪表盘 Hook 的确定性 API 替身。 */ () => ({
|
||||
getDashboardStats: vi.fn(),
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { getDateRange, getPreviousDateRange } from '../../../dateRange';
|
||||
import type { TimeRange } from '../../../dateRange';
|
||||
import { buildCategoryData, buildChartData, buildItemNameMap, buildProductSalesData, buildSourceData, getMaxProductSales, getRangeLabel, getTrendPercent, isCurrentDashboardRequest } from './state';
|
||||
import { getDashboardStats, getItems, getOrderAnalytics, getValidOrders } from './api';
|
||||
import type { DashboardData, DashboardRangeSelection, DashboardStatus } from './types';
|
||||
import { useCallback,useEffect,useMemo,useRef,useState } from 'react';
|
||||
import { getDateRange,getPreviousDateRange } from '../../../dateRange';
|
||||
import { getDashboardStats,getItems,getOrderAnalytics,getValidOrders } from './api';
|
||||
import { buildCategoryData,buildChartData,buildItemNameMap,buildProductSalesData,buildSourceData,getMaxProductSales,getRangeLabel,getTrendPercent,isCurrentDashboardRequest } from './state';
|
||||
import type { DashboardData,DashboardRangeSelection,DashboardStatus } from './types';
|
||||
|
||||
/** Dashboard Hook 的输入参数。 */
|
||||
export type UseDashboardOptions = DashboardRangeSelection & { /** customRangeVersion 表示自定义范围版本。 */ customRangeVersion: number };
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import React from 'react';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { describe, expect, test } from 'vitest';
|
||||
import { describe,expect,test } from 'vitest';
|
||||
import { StatusBadge } from './Dashboard';
|
||||
|
||||
// dashboardSource 仪表盘测试数据源。
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import React, { useState } from 'react';
|
||||
import { OrderStatus } from '../../../../shared/api-contract';
|
||||
import { getDateRange, TimeRange } from '../../../../dateRange';
|
||||
import { Activity,AlertCircle,DollarSign,ExternalLink,Package,PackageCheck,ShoppingCart,TrendingUp,Users } from 'lucide-react';
|
||||
import React,{ useState } from 'react';
|
||||
import { Cell,Legend,Pie,PieChart,ResponsiveContainer,Tooltip } from 'recharts';
|
||||
import { getDateRange,TimeRange } from '../../../../dateRange';
|
||||
import { formatLocalDateTime } from '../../../../dateTime';
|
||||
import { TrendingUp, Users, ShoppingCart, AlertCircle, DollarSign, Activity, Package, ArrowUpRight, Calendar, X, BarChart3, PackageCheck, ExternalLink, Eye, Edit } from 'lucide-react';
|
||||
import { Tooltip, ResponsiveContainer, PieChart, Pie, Cell, Legend } from 'recharts';
|
||||
import { useDashboard } from '../hooks';
|
||||
import { OrderStatus } from '../api';
|
||||
import { DashboardTrendChart } from '../DashboardTrendChart';
|
||||
import { useDashboard } from '../hooks';
|
||||
|
||||
// cssColor 状态颜色样式。
|
||||
const cssColor = (token: string, alpha?: number) => (
|
||||
@@ -84,8 +84,6 @@ const Dashboard: React.FC = () => {
|
||||
const stats = data?.stats || null;
|
||||
// analytics 统计分析数据。
|
||||
const analytics = data?.analytics || null;
|
||||
// previousAnalytics 上一份统计数据。
|
||||
const previousAnalytics = data?.previousAnalytics || null;
|
||||
// validOrders 有效订单列表。
|
||||
const validOrders = data?.validOrders.orders || [];
|
||||
// validOrdersTotal 有效数据订单列表总数,负责当前功能中的对应处理。
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { expect, test } from 'vitest';
|
||||
import type { OrderAnalytics } from '../../../shared/api-contract';
|
||||
import { buildCategoryData, buildChartData, buildItemNameMap, buildProductSalesData, buildSourceData, getMaxProductSales, getRangeLabel, getTrendPercent, isCurrentDashboardRequest } from './state';
|
||||
import { expect,test } from 'vitest';
|
||||
import type { OrderAnalytics } from '../../../shared/api-contract/admin';
|
||||
import { buildCategoryData,buildChartData,buildItemNameMap,buildProductSalesData,buildSourceData,getMaxProductSales,getRangeLabel,getTrendPercent,isCurrentDashboardRequest } from './state';
|
||||
|
||||
// analyticsFixture 是覆盖趋势、商品排行和零值边界的最小分析数据。
|
||||
const analyticsFixture: OrderAnalytics = {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { Item, OrderAnalytics } from '../../../shared/api-contract';
|
||||
import type { DateRange, TimeRange } from '../../../dateRange';
|
||||
import type { TimeRange } from '../../../dateRange';
|
||||
import type { Item,OrderAnalytics } from './api';
|
||||
import type { DashboardRangeSelection } from './types';
|
||||
|
||||
/** 趋势图中的单个日期数据点。 */
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { Item, Order, OrderAnalytics, DashboardStats } from '../../../shared/api-contract';
|
||||
import type { DateRange, TimeRange } from '../../../dateRange';
|
||||
import type { DateRange,TimeRange } from '../../../dateRange';
|
||||
import type { DashboardStats,Item,Order,OrderAnalytics } from './api';
|
||||
|
||||
/** Dashboard 请求状态。 */
|
||||
export type DashboardRequestState = 'idle' | 'loading' | 'success' | 'error';
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
// @vitest-environment jsdom
|
||||
import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest';
|
||||
import { amapPOIToPublishLocation,getPublishLocations } from './amapLocation';
|
||||
|
||||
// placeSearchFactory 创建不访问高德网络的地点搜索替身。
|
||||
const placeSearchFactory = (status: string, pois: unknown[] = []) => vi.fn(function placeSearchConstructor() {
|
||||
return {
|
||||
// searchNearBy 根据测试指定的状态回调结果。
|
||||
searchNearBy: createSearchNearByStub(status, pois),
|
||||
};
|
||||
});
|
||||
|
||||
// createSearchNearByStub 创建向业务代码返回可控结果的地点搜索方法。
|
||||
function createSearchNearByStub(status: string, pois: unknown[]): (_keyword: string, _center: [number, number], _radius: number, callback: (status: string, result: unknown) => void) => void {
|
||||
// stub 是保存测试状态和地点列表的搜索方法对象。
|
||||
const stub = new SearchNearByStub(status, pois);
|
||||
return stub.searchNearBy.bind(stub);
|
||||
}
|
||||
|
||||
// SearchNearByStub 保存测试状态并实现高德地点搜索方法。
|
||||
class SearchNearByStub {
|
||||
// status 是高德搜索回调状态。
|
||||
private readonly status: string;
|
||||
|
||||
// pois 是高德搜索返回的地点列表。
|
||||
private readonly pois: unknown[];
|
||||
|
||||
// constructor 保存可控的搜索结果。
|
||||
constructor(status: string, pois: unknown[]) {
|
||||
this.status = status;
|
||||
this.pois = pois;
|
||||
}
|
||||
|
||||
// searchNearBy 向业务代码返回测试指定的地点搜索结果。
|
||||
searchNearBy(_keyword: string, _center: [number, number], _radius: number, callback: (status: string, result: unknown) => void): void {
|
||||
callback(this.status, { poiList: { pois: this.pois } });
|
||||
}
|
||||
}
|
||||
|
||||
describe('AMap 地点业务适配', /* 当前回调覆盖坐标校验和地点搜索结果转换。 */ () => {
|
||||
beforeEach(/* 当前回调安装可控的 AMap API 替身。 */ () => {
|
||||
// placeSearch 是高德 PlaceSearch 构造器的浏览器替身。
|
||||
const placeSearch = placeSearchFactory('complete', [{ id: 'poi-1', name: '地点', adname: '区域', cityname: '城市', adcode: '100', pname: '省份', location: { lng: 120, lat: 30 } }, { id: 'bad', name: '缺字段', location: { lng: 120, lat: 30 } }]);
|
||||
// AMap 是高德地图全局对象的测试替身。
|
||||
Object.defineProperty(window, 'AMap', { configurable: true, value: { PlaceSearch: placeSearch } });
|
||||
});
|
||||
|
||||
afterEach(/* 当前回调清理浏览器全局状态。 */ () => {
|
||||
// AMap 是高德地图全局对象的测试替身。
|
||||
Reflect.deleteProperty(window, 'AMap');
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
test('无效坐标在触发外部 API 前直接拒绝', /* 当前回调验证坐标输入守卫。 */ async () => {
|
||||
await expect(getPublishLocations(0, 30)).rejects.toThrow('经纬度无效');
|
||||
await expect(getPublishLocations(181, 30)).rejects.toThrow('经纬度无效');
|
||||
});
|
||||
|
||||
test('完成状态过滤无效 POI 并转换有效地点', /* 当前回调验证高德完整响应映射。 */ async () => {
|
||||
// locations 是地点搜索业务转换后的结果集合。
|
||||
const locations = await getPublishLocations(120, 30);
|
||||
expect(locations).toHaveLength(1);
|
||||
expect(locations[0]).toMatchObject({ division_id: '100', poi_id: 'poi-1', longitude: 120, latitude: 30 });
|
||||
});
|
||||
|
||||
test('无数据状态返回空数组,失败状态返回业务错误', /* 当前回调验证地点搜索的两类非成功响应。 */ async () => {
|
||||
// placeSearch 是返回无数据状态的构造器替身。
|
||||
const placeSearch = placeSearchFactory('no_data');
|
||||
Object.defineProperty(window, 'AMap', { configurable: true, value: { PlaceSearch: placeSearch } });
|
||||
await expect(getPublishLocations(120, 30)).resolves.toEqual([]);
|
||||
|
||||
// failedPlaceSearch 是返回失败状态的构造器替身。
|
||||
const failedPlaceSearch = placeSearchFactory('error');
|
||||
Object.defineProperty(window, 'AMap', { configurable: true, value: { PlaceSearch: failedPlaceSearch } });
|
||||
await expect(getPublishLocations(120, 30)).rejects.toThrow('附近地址查询失败');
|
||||
});
|
||||
|
||||
test('完成状态没有 POI 时返回空数组', /* 当前回调验证高德成功但无地点结果的边界。 */ async () => {
|
||||
// placeSearch 是返回空地点列表的构造器替身。
|
||||
const placeSearch = placeSearchFactory('complete');
|
||||
Object.defineProperty(window, 'AMap', { configurable: true, value: { PlaceSearch: placeSearch } });
|
||||
await expect(getPublishLocations(120, 30)).resolves.toEqual([]);
|
||||
});
|
||||
|
||||
test('取消和超时会结束等待中的高德查询,晚到回调不会改写结果', /* 当前回调验证地点查询的取消、超时与晚到回调隔离。 */ async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
// callback 保存模拟 SDK 晚到返回时使用的回调。
|
||||
let callback: ((status: string, result: unknown) => void) | undefined;
|
||||
// placeSearch 是永不主动完成的地点搜索构造器替身。
|
||||
const placeSearch = vi.fn(/* placeSearchConstructor 创建不会主动回调的 SDK 搜索替身。 */ function placeSearchConstructor() {
|
||||
return { searchNearBy: /* pendingSearchAction 只保存 SDK 回调,等待测试主动触发。 */ (_keyword: string, _center: [number, number], _radius: number, value: (status: string, result: unknown) => void) => { callback = value; } };
|
||||
});
|
||||
Object.defineProperty(window, 'AMap', { configurable: true, value: { PlaceSearch: placeSearch } });
|
||||
// controller 是主动取消地点查询的调用方取消器。
|
||||
const controller = new AbortController();
|
||||
// cancelled 是等待主动取消结果的查询 Promise。
|
||||
const cancelled = getPublishLocations(120, 30, { signal: controller.signal });
|
||||
controller.abort();
|
||||
await expect(cancelled).rejects.toMatchObject({ name: 'AbortError' });
|
||||
callback?.('complete', { poiList: { pois: [{ id: 'poi-1', name: '晚到地点', adname: '区域', cityname: '城市', adcode: '100', pname: '省份', location: { lng: 120, lat: 30 } }] } });
|
||||
|
||||
// timedOut 是等待 SDK 永不回调时的时间预算收口。
|
||||
const timedOut = getPublishLocations(120, 30, { timeoutMs: 10 });
|
||||
// timeoutAssertion 是对时间预算触发后查询错误的异步断言。
|
||||
const timeoutAssertion = expect(timedOut).rejects.toThrow('附近地址查询超时');
|
||||
await vi.advanceTimersByTimeAsync(10);
|
||||
await timeoutAssertion;
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
test('POI 映射拒绝越界坐标和缺失行政字段', /* 当前回调验证领域地点模型的完整性守卫。 */ () => {
|
||||
expect(amapPOIToPublishLocation({ id: 'poi', name: '地点', adcode: '1', pname: '省', cityname: '市', location: { lng: 181, lat: 30 } })).toBeNull();
|
||||
expect(amapPOIToPublishLocation({ id: 'poi', name: '地点', adcode: '1', pname: '省', cityname: '市', location: { lng: 120, lat: 30 } })).not.toBeNull();
|
||||
expect(amapPOIToPublishLocation({ name: '地点', adcode: '1', pname: '省', cityname: '市', location: { lng: 120, lat: 30 } })).toBeNull();
|
||||
expect(amapPOIToPublishLocation({ id: 'poi', adcode: '1', pname: '省', cityname: '市', location: { lng: 120, lat: 30 } })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
// @vitest-environment jsdom
|
||||
import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest';
|
||||
|
||||
// SCRIPT_ID 是高德脚本加载器使用的固定 DOM 标识。
|
||||
const SCRIPT_ID = 'ydisks-amap-js-api';
|
||||
|
||||
// createAmapStub 创建可完成地点查询的高德 API 替身。
|
||||
function createAmapStub() {
|
||||
// placeSearch 是地点查询构造器替身。
|
||||
const placeSearch = vi.fn(function placeSearchConstructor() {
|
||||
return {
|
||||
// searchNearBy 返回一个可映射的地点结果。
|
||||
searchNearBy: /* searchCallback 返回一个可映射的地点结果。 */ (_keyword: string, _center: [number, number], _radius: number, callback: (status: string, result: unknown) => void) => callback('complete', {
|
||||
poiList: {
|
||||
pois: [{ id: 'poi-1', name: '地点', adname: '区域', cityname: '城市', adcode: '100', pname: '省份', location: { lng: 120, lat: 30 } }],
|
||||
},
|
||||
}),
|
||||
};
|
||||
});
|
||||
// amapStub 是浏览器全局高德 API 替身。
|
||||
return { PlaceSearch: placeSearch };
|
||||
}
|
||||
|
||||
describe('AMap 脚本加载边界', /* describeCallback 组织高德脚本加载测试。 */ () => {
|
||||
beforeEach(/* beforeEachCallback 清理高德脚本全局状态。 */ () => {
|
||||
// script 是上一用例遗留的高德脚本节点。
|
||||
document.getElementById(SCRIPT_ID)?.remove();
|
||||
// AMap 是浏览器全局高德对象。
|
||||
Reflect.deleteProperty(window, 'AMap');
|
||||
// loadedCallback 是上一用例遗留的脚本回调。
|
||||
Reflect.deleteProperty(window, '__ydisksAmapLoaded');
|
||||
});
|
||||
|
||||
afterEach(/* afterEachCallback 恢复高德脚本测试环境。 */ () => {
|
||||
vi.useRealTimers();
|
||||
document.getElementById(SCRIPT_ID)?.remove();
|
||||
Reflect.deleteProperty(window, 'AMap');
|
||||
Reflect.deleteProperty(window, '__ydisksAmapLoaded');
|
||||
});
|
||||
|
||||
test('脚本回调完成后解析高德对象', /* successCallback 验证脚本成功加载。 */ async () => {
|
||||
// amapModule 是每个用例独立加载的业务模块实例。
|
||||
vi.resetModules();
|
||||
const amapModule = await import('./amapLocation');
|
||||
// pending 是等待脚本回调完成的地点查询。
|
||||
const pending = amapModule.getPublishLocations(120, 30);
|
||||
// script 是业务代码插入的高德脚本节点。
|
||||
const script = document.getElementById(SCRIPT_ID) as HTMLScriptElement;
|
||||
expect(script.src).toContain('webapi.amap.com/maps');
|
||||
// amapStub 是脚本加载完成后暴露的高德对象。
|
||||
window.AMap = createAmapStub() as NonNullable<Window['AMap']>;
|
||||
window.__ydisksAmapLoaded?.();
|
||||
await expect(pending).resolves.toMatchObject([{ poi_id: 'poi-1' }]);
|
||||
});
|
||||
|
||||
test('并发地点查询共享同一个脚本加载请求', /* concurrentCallback 验证加载 Promise 复用。 */ async () => {
|
||||
vi.resetModules();
|
||||
const amapModule = await import('./amapLocation');
|
||||
// firstPending 是第一路地点查询的加载 Promise。
|
||||
const firstPending = amapModule.getPublishLocations(120, 30);
|
||||
// secondPending 是并发复用脚本加载器的第二路地点查询。
|
||||
const secondPending = amapModule.getPublishLocations(120, 30);
|
||||
expect(document.querySelectorAll(`#${SCRIPT_ID}`)).toHaveLength(1);
|
||||
window.AMap = createAmapStub() as NonNullable<Window['AMap']>;
|
||||
window.__ydisksAmapLoaded?.();
|
||||
await expect(Promise.all([firstPending, secondPending])).resolves.toHaveLength(2);
|
||||
});
|
||||
|
||||
test('已有脚本节点触发错误时返回加载失败', /* errorCallback 验证脚本错误加载。 */ async () => {
|
||||
// existingScript 是预先插入页面的高德脚本节点。
|
||||
const existingScript = document.createElement('script');
|
||||
existingScript.id = SCRIPT_ID;
|
||||
document.head.appendChild(existingScript);
|
||||
vi.resetModules();
|
||||
const amapModule = await import('./amapLocation');
|
||||
// pending 是等待脚本错误回调的地点查询。
|
||||
const pending = amapModule.getPublishLocations(120, 30);
|
||||
existingScript.onerror?.(new Event('error'));
|
||||
await expect(pending).rejects.toThrow('高德地图 API 加载失败');
|
||||
});
|
||||
|
||||
test('脚本超时后返回网络配置错误', /* timeoutCallback 验证脚本超时加载。 */ async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.resetModules();
|
||||
const amapModule = await import('./amapLocation');
|
||||
// pending 是等待超时结果的地点查询。
|
||||
const pending = amapModule.getPublishLocations(120, 30);
|
||||
// rejection 是等待脚本超时错误的断言。
|
||||
const rejection = expect(pending).rejects.toThrow('高德地图 API 加载超时');
|
||||
await vi.advanceTimersByTimeAsync(15_000);
|
||||
await rejection;
|
||||
});
|
||||
|
||||
test('脚本回调完成但未暴露对象时返回对象缺失错误', /* missingApiCallback 验证脚本对象缺失。 */ async () => {
|
||||
vi.resetModules();
|
||||
const amapModule = await import('./amapLocation');
|
||||
// pending 是等待无对象回调结果的地点查询。
|
||||
const pending = amapModule.getPublishLocations(120, 30);
|
||||
window.__ydisksAmapLoaded?.();
|
||||
await expect(pending).rejects.toThrow('未找到 AMap 对象');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
import { expect,test } from 'vitest';
|
||||
import { amapPOIToPublishLocation } from './amapLocation';
|
||||
|
||||
test('maps AMap POI fields to the publish location shape', () => {
|
||||
expect(amapPOIToPublishLocation({
|
||||
id: 'B000A74398',
|
||||
name: '人民广场',
|
||||
address: '人民大道',
|
||||
adname: '黄浦区',
|
||||
cityname: '上海市',
|
||||
adcode: '310101',
|
||||
pname: '上海市',
|
||||
location: { lng: 121.4737, lat: 31.2304 },
|
||||
})).toEqual({
|
||||
area: '黄浦区',
|
||||
city: '上海市',
|
||||
division_id: '310101',
|
||||
longitude: 121.4737,
|
||||
latitude: 31.2304,
|
||||
poi_id: 'B000A74398',
|
||||
poi_name: '人民广场',
|
||||
province: '上海市',
|
||||
});
|
||||
} /* 测试回调断言高德 POI 字段能够转换为发布地点 DTO。 */);
|
||||
|
||||
test('drops incomplete or invalid AMap POIs', () => {
|
||||
expect(amapPOIToPublishLocation({
|
||||
id: 'poi',
|
||||
name: '无坐标',
|
||||
adcode: '310101',
|
||||
pname: '上海市',
|
||||
cityname: '上海市',
|
||||
location: { lng: 0, lat: 31.2 },
|
||||
})).toBeNull();
|
||||
} /* 测试回调断言缺少或非法坐标的 POI 会被丢弃。 */);
|
||||
@@ -0,0 +1,202 @@
|
||||
import type { PublishLocation } from './api';
|
||||
|
||||
const AMAP_SCRIPT_ID = 'ydisks-amap-js-api'; /* AMAP_SCRIPT_ID 表示AMAPSCRIPTID。 */
|
||||
// 高德 JS API 的 Key 是前端公开 Key;部署时可通过 VITE_AMAP_JS_KEY 覆盖。
|
||||
const DEFAULT_AMAP_JS_KEY = 'c9b68d4ce9a2a97f22a4a439404488ca';
|
||||
|
||||
export interface AMapLocationValue {
|
||||
// lng 表示lng。
|
||||
lng: number;
|
||||
// lat 表示lat。
|
||||
lat: number;
|
||||
}
|
||||
|
||||
export interface AMapPOI {
|
||||
// id 表示id。
|
||||
id?: string;
|
||||
// name 表示name。
|
||||
name?: string;
|
||||
// address 表示address。
|
||||
address?: string;
|
||||
// adname 表示adname。
|
||||
adname?: string;
|
||||
// cityname 表示cityname。
|
||||
cityname?: string;
|
||||
// adcode 表示adcode。
|
||||
adcode?: string | number;
|
||||
// pname 表示pname。
|
||||
pname?: string;
|
||||
// location 表示location。
|
||||
location?: AMapLocationValue;
|
||||
}
|
||||
|
||||
interface AMapPlaceSearchResult {
|
||||
// poiList 表示poiList。
|
||||
poiList?: {
|
||||
// pois 表示pois。
|
||||
pois?: AMapPOI[];
|
||||
};
|
||||
}
|
||||
|
||||
interface AMapPlaceSearch {
|
||||
// searchNearBy 表示searchNearBy。
|
||||
searchNearBy(
|
||||
keyword: string,
|
||||
center: [number, number],
|
||||
radius: number,
|
||||
callback: (status: string, result: AMapPlaceSearchResult) => void,
|
||||
): void;
|
||||
}
|
||||
|
||||
interface AMapAPI {
|
||||
// PlaceSearch 表示PlaceSearch。
|
||||
PlaceSearch: new (options: { /* extensions 表示extensions。 */ extensions: 'all'; /* pageSize 表示pageSize。 */ pageSize: number }) => AMapPlaceSearch;
|
||||
}
|
||||
|
||||
// PublishLocationRequestOptions 控制高德地点查询的取消和最长等待时间。
|
||||
export interface PublishLocationRequestOptions {
|
||||
// signal 是调用方在组件卸载、切换账号或关闭弹窗时触发的取消信号。
|
||||
signal?: AbortSignal;
|
||||
// timeoutMs 是高德地点回调允许占用的最长毫秒数。
|
||||
timeoutMs?: number;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
// AMap 表示AMap。
|
||||
AMap?: AMapAPI;
|
||||
// __ydisksAmapLoaded 表示ydisksAmapLoaded。
|
||||
__ydisksAmapLoaded?: () => void;
|
||||
}
|
||||
|
||||
interface ImportMetaEnv {
|
||||
// VITE_AMAP_JS_KEY 表示VITEAMAPJSKEY。
|
||||
readonly VITE_AMAP_JS_KEY?: string;
|
||||
}
|
||||
|
||||
interface ImportMeta {
|
||||
// env 表示env。
|
||||
readonly env: ImportMetaEnv;
|
||||
}
|
||||
}
|
||||
|
||||
let amapLoadPromise: Promise<AMapAPI> | null = null; /* amapLoadPromise 表示amapLoadPromise。 */
|
||||
|
||||
const configuredAmapKey = (): string => {
|
||||
const key = import.meta.env.VITE_AMAP_JS_KEY?.trim(); /* key 表示key。 */
|
||||
return key || DEFAULT_AMAP_JS_KEY;
|
||||
}; /* configuredAmapKey 表示configuredAmapKey。 */
|
||||
|
||||
const loadAMap = (): Promise<AMapAPI> => {
|
||||
if (window.AMap) return Promise.resolve(window.AMap);
|
||||
if (amapLoadPromise) return amapLoadPromise;
|
||||
|
||||
amapLoadPromise = new Promise<AMapAPI>((resolve, reject) => {
|
||||
const existing = document.getElementById(AMAP_SCRIPT_ID) as HTMLScriptElement | null; /* existing 表示existing。 */
|
||||
const script = existing || document.createElement('script'); /* script 表示script。 */
|
||||
const cleanup = () => {
|
||||
window.__ydisksAmapLoaded = undefined;
|
||||
window.clearTimeout(timeout);
|
||||
}; /* cleanup 表示cleanup。 */
|
||||
const finish = () => {
|
||||
if (window.AMap) {
|
||||
cleanup();
|
||||
resolve(window.AMap);
|
||||
} else {
|
||||
cleanup();
|
||||
reject(new Error('高德地图 API 加载完成但未找到 AMap 对象'));
|
||||
}
|
||||
}; /* finish 表示finish。 */
|
||||
const timeout = window.setTimeout(() => {
|
||||
cleanup();
|
||||
reject(new Error('高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置'));
|
||||
} /* 定时器到期时终止脚本加载并返回网络配置错误。 */, 15_000); /* timeout 是高德脚本加载的毫秒上限。 */
|
||||
|
||||
window.__ydisksAmapLoaded = finish;
|
||||
script.id = AMAP_SCRIPT_ID;
|
||||
script.async = true;
|
||||
script.src = `https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(configuredAmapKey())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`;
|
||||
script.onerror = () => {
|
||||
cleanup();
|
||||
reject(new Error('高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置'));
|
||||
} /* 脚本节点触发 error 时释放监听并拒绝加载 Promise。 */;
|
||||
if (!existing) document.head.appendChild(script);
|
||||
} /* 单例加载过程只创建一次脚本节点并复用完成 Promise。 */).catch(error => {
|
||||
amapLoadPromise = null;
|
||||
throw error;
|
||||
} /* 失败时清空单例 Promise,允许后续调用重新加载脚本。 */);
|
||||
|
||||
return amapLoadPromise;
|
||||
}; /* loadAMap 表示loadAMap。 */
|
||||
|
||||
const validCoordinate = (value: number): boolean => Number.isFinite(value) && value !== 0; /* validCoordinate 表示validCoordinate。 */
|
||||
|
||||
// 字段映射与闲鱼网页版发布页一致:adcode → divisionId,name → poi,pname/cityname/adname → 行政区。
|
||||
export const amapPOIToPublishLocation = (poi: AMapPOI): PublishLocation | null => {
|
||||
const longitude = Number(poi.location?.lng); /* longitude 表示longitude。 */
|
||||
const latitude = Number(poi.location?.lat); /* latitude 表示latitude。 */
|
||||
const location: PublishLocation = {
|
||||
area: String(poi.adname || '').trim(),
|
||||
city: String(poi.cityname || '').trim(),
|
||||
division_id: String(poi.adcode || '').trim(),
|
||||
longitude,
|
||||
latitude,
|
||||
poi_id: String(poi.id || '').trim(),
|
||||
poi_name: String(poi.name || '').trim(),
|
||||
province: String(poi.pname || '').trim(),
|
||||
}; /* location 表示location。 */
|
||||
if (!location.division_id || !location.province || !location.city || !location.poi_id || !location.poi_name) {
|
||||
return null;
|
||||
}
|
||||
if (!validCoordinate(longitude) || !validCoordinate(latitude) || longitude < -180 || longitude > 180 || latitude < -90 || latitude > 90) {
|
||||
return null;
|
||||
}
|
||||
return location;
|
||||
};
|
||||
|
||||
export const getPublishLocations = async (longitude: number, latitude: number, options: PublishLocationRequestOptions = {}): Promise<PublishLocation[]> => {
|
||||
if (!validCoordinate(longitude) || !validCoordinate(latitude) || longitude < -180 || longitude > 180 || latitude < -90 || latitude > 90) {
|
||||
throw new Error('经纬度无效');
|
||||
}
|
||||
const amap = await loadAMap(); /* amap 表示amap。 */
|
||||
return new Promise<PublishLocation[]>((resolve, reject) => {
|
||||
// settled 标记本次查询是否已经结束,阻止超时、取消和 SDK 回调重复收口。
|
||||
let settled = false;
|
||||
// timeoutMs 是地点搜索回调的有限等待预算,防止 AMap 永不回调时永久 loading。
|
||||
const timeoutMs = Math.max(1, options.timeoutMs ?? 10_000);
|
||||
// finish 统一清理本次搜索的定时器和取消监听,确保 Promise 只完成一次。
|
||||
const finish = (callback: () => void) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
globalThis.clearTimeout(timer);
|
||||
options.signal?.removeEventListener('abort', abortSearch);
|
||||
callback();
|
||||
};
|
||||
// abortSearch 将调用方取消转换为 Promise 拒绝,SDK 晚到回调随后只会被忽略。
|
||||
const abortSearch = () => finish(() => reject(new DOMException('aborted', 'AbortError')));
|
||||
// timer 是地点搜索超时定时器,成功、失败和取消时都会清理。
|
||||
const timer = globalThis.setTimeout(/* searchTimeoutAction 在 SDK 未回调时统一结束地点查询。 */ () => finish(/* timeoutRejectAction 将超时原因传回调用方。 */ () => reject(new Error('高德地图附近地址查询超时,请稍后重试'))), timeoutMs);
|
||||
if (options.signal?.aborted) {
|
||||
abortSearch();
|
||||
return;
|
||||
}
|
||||
options.signal?.addEventListener('abort', abortSearch, { once: true });
|
||||
const placeSearch = new amap.PlaceSearch({ extensions: 'all', pageSize: 10 }); /* placeSearch 表示placeSearch。 */
|
||||
placeSearch.searchNearBy('', [longitude, latitude], 1_000, (status, result) => {
|
||||
if (settled) return;
|
||||
if (status !== 'complete') {
|
||||
if (status === 'no_data') {
|
||||
finish(/* noDataResolveAction 将高德无数据状态作为正常空地点列表返回。 */ () => resolve([]));
|
||||
return;
|
||||
}
|
||||
finish(/* searchFailureRejectAction 将高德失败状态转换为用户可见错误。 */ () => reject(new Error('高德地图附近地址查询失败,请稍后重试')));
|
||||
return;
|
||||
}
|
||||
// locations 是过滤无效坐标后的发布地点列表,供商品发布表单使用。
|
||||
const locations = (result?.poiList?.pois || [])
|
||||
.map(amapPOIToPublishLocation)
|
||||
.filter((location): location is PublishLocation => location !== null /* location 是转换后仍具备有效坐标的地点。 */);
|
||||
finish(/* searchSuccessResolveAction 将已过滤的有效地点列表交给调用方。 */ () => resolve(locations));
|
||||
} /* 搜索完成后将地点结果交给调用方并结束本次高德回调。 */);
|
||||
} /* 高德回调只处理当前请求,组件卸载后由 cleanup 移除监听。 */);
|
||||
}; /* getPublishLocations 表示getPublishLocations。 */
|
||||
@@ -0,0 +1,13 @@
|
||||
import { describe, expect, test } from 'vitest';
|
||||
import { ApiError } from '../../../shared/http/client';
|
||||
import { itemErrorMessage } from './api';
|
||||
|
||||
// 商品 API 错误码适配测试覆盖权限、冲突、人工核对和可重试的恢复分支。
|
||||
describe('items API error adapter', /* 商品错误适配测试组覆盖稳定机器码到恢复指引的映射。 */ () => {
|
||||
test('按统一机器错误码输出可执行的恢复提示', /* 当前回调验证权限、冲突、人工核对和重试提示。 */ () => {
|
||||
expect(itemErrorMessage(new ApiError(403, { code: 'stock_permission_missing', message: 'forbidden' }), 'fallback')).toContain('库存发布权限');
|
||||
expect(itemErrorMessage(new ApiError(409, { code: 'conflict', message: 'conflict' }), 'fallback')).toContain('刷新后重试');
|
||||
expect(itemErrorMessage(new ApiError(502, { code: 'external_result_unknown', message: 'unknown' }), 'fallback')).toContain('人工核对');
|
||||
expect(itemErrorMessage(new ApiError(503, { code: 'retryable', message: 'retry' }), 'fallback')).toContain('稍后重试');
|
||||
});
|
||||
});
|
||||
@@ -1,14 +1,21 @@
|
||||
import { get, post, put, del, postForm, type RequestControlOptions } from '../../../shared/http/client';
|
||||
import type { PublishLocation } from '../../../shared/api-contract/items';
|
||||
import {
|
||||
SessionResponse, AccountDetail, AccountSummaryResponse, Order, PaginatedResponse,
|
||||
AdminStats, DashboardStats, Card, SystemSettings, OrderAnalytics,
|
||||
Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction, AutomationTriggerType,
|
||||
NotificationChannel, NotificationEventType, AccountTaskSettings, ChatSession, ChatMessage, ItemListEnvelope, AutomationIssuesEnvelope,
|
||||
CookieSettingsResponse, CookieProfileResponse, ItemDetailResponse, ItemPublishResponse, ItemSyncResponse, OrderDTOResponse, OrderDetailResponse, OrderSingleRefreshResponse, OrderBatchResponse, OrderRefreshResponse, OrderRefreshJobStartResponse, OrderRefreshJobStatusResponse, OrderRefreshJobCancelResponse, AutomationRuleResponse, AutomationRulePageResponse, AIReplySettingsResponse, AIModelsResponse, UserSettingResponse, CardBatchResponse, CardAppendResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchListResponse, BatchIDResponse, ItemPublishBatchResponse, BatchCancelResponse, MutationIDResponse, OperationResponse, NotificationChannelResponse, NotificationBinding, AccountBindingsResponse, CardListResponse, KeywordTypedResponse, DefaultReplyResponse, AccountTaskSettingsResponse, AccountTaskRunResponseEnvelope, AdminStatsResponse, DashboardStatsResponse, OrderAnalyticsResponse, QRLoginGenerateResponse, QRLoginStatusResponse, QRLoginVerificationResponse, ValidOrderResponse, ValidOrdersResponse
|
||||
} from '../../../shared/api-contract';
|
||||
import { collectionFrom, objectFrom } from '../../../shared/http/contract';
|
||||
import { getPublishLocations as queryPublishLocations, type PublishLocationRequestOptions } from '../../../services/amapLocation';
|
||||
import type { PublishLocation } from '../../../shared/api-contract';
|
||||
AccountDetail,
|
||||
BatchCancelResponse,
|
||||
BatchIDResponse,
|
||||
CategoryRecommendationResponse,
|
||||
Item,
|
||||
ItemDetailResponse,
|
||||
ItemPublishBatchPreviewResponse,
|
||||
ItemPublishBatchResponse,
|
||||
ItemPublishResponse,ItemSyncResponse,
|
||||
OperationResponse,
|
||||
ShippingRule
|
||||
} from '../../../shared/api-contract/items';
|
||||
import { ApiError,del,get,post,postForm,put,type RequestControlOptions } from '../../../shared/http/client';
|
||||
import { collectionFrom } from '../../../shared/http/contract';
|
||||
export type * from '../../../shared/api-contract/items';
|
||||
import { getPublishLocations as queryPublishLocations,type PublishLocationRequestOptions } from './amapLocation';
|
||||
|
||||
/** 商品账号筛选器读取非敏感账号摘要。 */
|
||||
export const getAccountDetails = async (options?: RequestControlOptions): Promise<AccountDetail[]> => get('/api/v1/accounts/details', undefined, options);
|
||||
@@ -18,7 +25,32 @@ export const getShippingRules = async (options?: RequestControlOptions): Promise
|
||||
|
||||
// getPublishLocations 通过 feature API 边界读取地点,并把取消/超时控制传入地图服务。
|
||||
export const getPublishLocations = (longitude: number, latitude: number, options?: PublishLocationRequestOptions): Promise<PublishLocation[]> => queryPublishLocations(longitude, latitude, options);
|
||||
export type { PublishLocation } from '../../../shared/api-contract';
|
||||
export type { PublishLocation } from '../../../shared/api-contract/items';
|
||||
|
||||
// itemErrorMessage 将统一 HTTP 错误码归一为商品 feature 可执行的用户提示。
|
||||
export const itemErrorMessage = (error: unknown, fallback: string): string => {
|
||||
if (error instanceof ApiError) {
|
||||
switch (error.code) {
|
||||
case 'stock_permission_missing':
|
||||
return '发布失败:该账号没有库存发布权限,无法按库存数量发布商品。请换账号或先在闲鱼确认库存能力。';
|
||||
case 'conflict':
|
||||
case 'item_conflict':
|
||||
return '商品状态已发生变化,请刷新后重试。';
|
||||
case 'external_result_unknown':
|
||||
case 'manual_review_required':
|
||||
return '平台结果暂时无法确认,请先人工核对闲鱼状态,再决定是否重试。';
|
||||
case 'retryable':
|
||||
case 'temporarily_unavailable':
|
||||
return '平台暂时不可用,请稍后重试。';
|
||||
default:
|
||||
return error.message || fallback;
|
||||
}
|
||||
}
|
||||
if (error instanceof Error) return error.message;
|
||||
// message 保存兼容 API 错误对象中的文本说明。
|
||||
const message = typeof error === 'object' && error !== null && 'message' in error ? (error as { /** message 是兼容错误对象中的文本说明。 */ message?: unknown }).message : undefined;
|
||||
return typeof message === 'string' ? message : fallback;
|
||||
};
|
||||
// Items
|
||||
// normalizeBooleanFlag 归一化布尔标记。
|
||||
const normalizeBooleanFlag = (value: unknown): boolean =>
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { describe, expect, test } from 'vitest';
|
||||
import { describe,expect,test } from 'vitest';
|
||||
import {
|
||||
batchStatusText,
|
||||
batchStatusClass,
|
||||
canRetryBatch,
|
||||
canStartBatch,
|
||||
isBatchInProgress,
|
||||
isCurrentBatchRequest,
|
||||
selectActivePublishBatch,
|
||||
batchStatusClass,
|
||||
batchStatusText,
|
||||
canRetryBatch,
|
||||
canStartBatch,
|
||||
isBatchInProgress,
|
||||
isCurrentBatchRequest,
|
||||
selectActivePublishBatch,
|
||||
} from './batchState';
|
||||
|
||||
// ItemList 批量行为测试覆盖预检、取消、重试和过期任务响应。
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { BatchCancelResponse, BatchIDResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchResponse } from '../../../shared/api-contract';
|
||||
import { act,renderHook } from '@testing-library/react';
|
||||
import { beforeEach,describe,expect,test,vi } from 'vitest';
|
||||
import type { BatchCancelResponse,BatchIDResponse,CategoryRecommendationResponse,ItemPublishBatchPreviewResponse,ItemPublishBatchResponse } from '../../../shared/api-contract/items';
|
||||
import {
|
||||
cancelItemPublishBatch,
|
||||
deleteItemPublishBatch,
|
||||
getItemPublishBatch,
|
||||
getItemPublishBatches,
|
||||
previewItemPublishBatch,
|
||||
recommendPublishCategory,
|
||||
retryFailedItemPublishBatch,
|
||||
startItemPublishBatch,
|
||||
cancelItemPublishBatch,
|
||||
deleteItemPublishBatch,
|
||||
getItemPublishBatch,
|
||||
getItemPublishBatches,
|
||||
previewItemPublishBatch,
|
||||
recommendPublishCategory,
|
||||
retryFailedItemPublishBatch,
|
||||
startItemPublishBatch,
|
||||
} from './api';
|
||||
import { useItemPublishBatch } from './hooks';
|
||||
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useCallback,useEffect,useRef,useState } from 'react';
|
||||
import {
|
||||
cancelItemPublishBatch,
|
||||
deleteItemPublishBatch,
|
||||
getItemPublishBatch,
|
||||
getItemPublishBatches,
|
||||
recommendPublishCategory,
|
||||
previewItemPublishBatch,
|
||||
retryFailedItemPublishBatch,
|
||||
startItemPublishBatch,
|
||||
cancelItemPublishBatch,
|
||||
deleteItemPublishBatch,
|
||||
getItemPublishBatch,
|
||||
getItemPublishBatches,
|
||||
previewItemPublishBatch,
|
||||
recommendPublishCategory,
|
||||
retryFailedItemPublishBatch,
|
||||
startItemPublishBatch,
|
||||
} from './api';
|
||||
import { canRetryBatch, canStartBatch, isBatchInProgress, isCurrentBatchRequest, selectActivePublishBatch } from './batchState';
|
||||
import { canRetryBatch,canStartBatch,isBatchInProgress,isCurrentBatchRequest,selectActivePublishBatch } from './batchState';
|
||||
import type {
|
||||
BatchFallbackCategory,
|
||||
BatchPhase,
|
||||
ItemPublishBatchOptions,
|
||||
ItemPublishBatchState,
|
||||
PublishBatchDetail,
|
||||
PublishBatchPreview,
|
||||
BatchFallbackCategory,
|
||||
BatchPhase,
|
||||
ItemPublishBatchOptions,
|
||||
ItemPublishBatchState,
|
||||
PublishBatchDetail,
|
||||
PublishBatchPreview,
|
||||
} from './types';
|
||||
|
||||
// useItemPublishBatch 集中管理批量铺货的表单、任务恢复、轮询和重试状态。
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { act,renderHook } from '@testing-library/react';
|
||||
import { useState } from 'react';
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { Item } from '../../../shared/api-contract';
|
||||
import { createItem, deleteItem, getPublishLocations, publishItem, syncItemsFromAccount, updateItem } from './api';
|
||||
import { useItemActions, type ItemActionsOptions } from './itemActions';
|
||||
import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest';
|
||||
import type { Item } from '../../../shared/api-contract/items';
|
||||
import { createItem,deleteItem,getPublishLocations,publishItem,syncItemsFromAccount,updateItem } from './api';
|
||||
import { useItemActions,type ItemActionsOptions } from './itemActions';
|
||||
|
||||
vi.mock('./api', /* itemActionsApiMockFactory 提供商品动作 Hook 的确定性 API 替身。 */ () => ({
|
||||
createItem: vi.fn(),
|
||||
deleteItem: vi.fn(),
|
||||
getPublishLocations: vi.fn(),
|
||||
itemErrorMessage: /* errorMessageMock 将测试动作中的异常转换为稳定回退文本。 */ (error: unknown, fallback: string) => error instanceof Error ? error.message : fallback,
|
||||
publishItem: vi.fn(),
|
||||
syncItemsFromAccount: vi.fn(),
|
||||
updateItem: vi.fn(),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useCallback, useEffect, useRef, useState, type Dispatch, type SetStateAction } from 'react';
|
||||
import type { Item } from '../../../shared/api-contract';
|
||||
import { createItem, deleteItem, getPublishLocations, publishItem, syncItemsFromAccount, updateItem } from './api';
|
||||
import { useCallback,useEffect,useRef,useState,type Dispatch,type SetStateAction } from 'react';
|
||||
import type { Item } from './api';
|
||||
import type { PublishLocation } from './api';
|
||||
import { createItem,deleteItem,getPublishLocations,itemErrorMessage,publishItem,syncItemsFromAccount,updateItem } from './api';
|
||||
|
||||
// AddItemForm 描述手动添加商品弹窗的表单字段。
|
||||
export interface AddItemForm {
|
||||
@@ -135,14 +135,6 @@ export const emptyAddItemForm = (): AddItemForm => ({ cookie_id: '', item_id: ''
|
||||
// emptyPublishItemForm 创建普通发布商品表单的初始值。
|
||||
export const emptyPublishItemForm = (cookieID = ''): PublishItemForm => ({ cookie_id: cookieID, title: '', description: '', price: '', original_price: '', quantity: '1', postage_mode: 'free', postage: '', images: [] });
|
||||
|
||||
// itemErrorMessage 将未知异常转换为稳定的商品操作提示。
|
||||
const itemErrorMessage = (error: unknown, fallback: string): string => {
|
||||
if (error instanceof Error) return error.message;
|
||||
// message 保存兼容 API 错误对象中的文本说明。
|
||||
const message = typeof error === 'object' && error !== null && 'message' in error ? (error as { /** message 是兼容错误对象中的文本说明。 */ message?: unknown }).message : undefined;
|
||||
return typeof message === 'string' ? message : fallback;
|
||||
};
|
||||
|
||||
// useItemActions 集中管理商品同步、编辑、删除、添加、普通发布和定位动作。
|
||||
export const useItemActions = ({ selectedAccount, setSelectedAccount, setItems, loadItems, loadShippingRules, onConfigureDelivery, setBatchLocations, setBatchLocation }: ItemActionsOptions): ItemActionsState => {
|
||||
// loading 表示商品同步请求是否正在执行。
|
||||
@@ -302,12 +294,6 @@ export const useItemActions = ({ selectedAccount, setSelectedAccount, setItems,
|
||||
}
|
||||
} catch (/* error 表示商品发布请求异常。 */ error: unknown) {
|
||||
console.error('发布商品失败:', error);
|
||||
// payload 保存服务端返回的结构化错误载荷。
|
||||
const payload = (error as { /** payload 是服务端结构化错误载荷。 */ payload?: { /** code 是服务端错误码。 */ code?: unknown } })?.payload;
|
||||
if (payload?.code === 'stock_permission_missing') {
|
||||
alert('发布失败:该账号没有库存发布权限,无法按库存数量发布商品。请换账号或先在闲鱼确认库存能力。');
|
||||
return;
|
||||
}
|
||||
alert(itemErrorMessage(error, '发布失败,请重试'));
|
||||
} finally {
|
||||
setPublishing(false);
|
||||
|
||||
@@ -1,19 +1,18 @@
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { ArrowRight,Box,CheckCircle2,CircleDashed,Edit,Filter,Link2,LocateFixed,PackagePlus,Plus,RefreshCw,Save,Search,ShoppingBag,Trash2,UploadCloud,User,X } from 'lucide-react';
|
||||
import React,{ useCallback,useEffect,useMemo,useRef,useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import type { Item } from '../../../../shared/api-contract';
|
||||
import type { AccountDetail,Item,ShippingRule } from '../api';
|
||||
import {
|
||||
getItems,
|
||||
getAccountDetails,
|
||||
getShippingRules,
|
||||
getItemPublishBatches,
|
||||
getAccountDetails,
|
||||
getItemPublishBatches,
|
||||
getItems,
|
||||
getShippingRules,
|
||||
} from '../api';
|
||||
import type { AccountDetail, ShippingRule } from '../../../../shared/api-contract';
|
||||
import type { ItemListProps } from '../types';
|
||||
import { batchStatusClass,batchStatusText } from '../batchState';
|
||||
import { BatchPhaseIndicator } from '../components/BatchPhaseIndicator';
|
||||
import { useItemPublishBatch } from '../hooks';
|
||||
import { useItemActions } from '../itemActions';
|
||||
import { batchStatusClass, batchStatusText } from '../batchState';
|
||||
import { BatchPhaseIndicator } from '../components/BatchPhaseIndicator';
|
||||
import { ArrowRight, Box, CheckCircle2, CircleDashed, Edit, Filter, Link2, LocateFixed, PackagePlus, Plus, RefreshCw, Save, Search, ShoppingBag, Trash2, UploadCloud, User, X } from 'lucide-react';
|
||||
import type { ItemListProps } from '../types';
|
||||
|
||||
// formatItemPrice 将商品价格转换为本地化展示文本。
|
||||
const formatItemPrice = (price?: string) => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { Dispatch, SetStateAction } from 'react';
|
||||
import type { Item, AccountDetail, ShippingRule } from '../../../shared/api-contract';
|
||||
import type { Dispatch,SetStateAction } from 'react';
|
||||
import type { AccountDetail,Item,ShippingRule } from './api';
|
||||
import type { PublishLocation } from './api';
|
||||
|
||||
// ItemListProps 描述商品页面从父级接收的规则配置回调。
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { del, get, post, put, type RequestControlOptions } from '../../../shared/http/client';
|
||||
import type { MutationIDResponse, NotificationBinding, NotificationChannel, NotificationChannelResponse, NotificationEventType, OperationResponse, SystemSettings } from '../../../shared/api-contract';
|
||||
import type { MutationIDResponse,NotificationBinding,NotificationChannel,NotificationChannelResponse,NotificationEventType,OperationResponse,SystemSettings } from '../../../shared/api-contract/notifications';
|
||||
import { del,get,post,put,type RequestControlOptions } from '../../../shared/http/client';
|
||||
export type * from '../../../shared/api-contract/notifications';
|
||||
|
||||
/** 通知渠道写入时使用的具名请求 DTO。 */
|
||||
export interface NotificationChannelRequest {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Bell,Edit2,Loader2,Send,Trash2 } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { Bell, Edit2, Loader2, Send, Trash2 } from 'lucide-react';
|
||||
import type { NotificationChannel } from '../../../../shared/api-contract';
|
||||
import { notificationChannelTypes, notificationEventSummary } from '../state';
|
||||
import type { NotificationChannel } from '../api';
|
||||
import { notificationChannelTypes,notificationEventSummary } from '../state';
|
||||
|
||||
// NotificationChannelListProps 描述通知渠道列表的操作边界。
|
||||
export interface NotificationChannelListProps {
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { Bell,Check,Eye,EyeOff,Loader2,X } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { Bell, Check, Eye, EyeOff, Loader2, X } from 'lucide-react';
|
||||
import { enableCustomSMTP } from '../../../../notificationEmailConfig';
|
||||
import type { NotificationChannel,NotificationChannelType,NotificationEventType,SystemSettings } from '../api';
|
||||
import { notificationChannelTypes } from '../state';
|
||||
import { NotificationEventSelector } from './NotificationEventSelector';
|
||||
import type { NotificationChannel, NotificationChannelType, NotificationEventType, SystemSettings } from '../../../../shared/api-contract';
|
||||
import type { NotificationForm } from '../types';
|
||||
import { NotificationEventSelector } from './NotificationEventSelector';
|
||||
|
||||
// NotificationChannelModalProps 描述渠道编辑弹窗所需的状态和回调。
|
||||
export interface NotificationChannelModalProps {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React from 'react';
|
||||
import { Check } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import type { NotificationEventType } from '../api';
|
||||
import { notificationEvents } from '../state';
|
||||
import type { NotificationEventType } from '../../../../shared/api-contract';
|
||||
|
||||
// NotificationEventSelectorProps 描述通知事件绑定组件的输入状态。
|
||||
export interface NotificationEventSelectorProps {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Eye,EyeOff,Loader2,Mail,Save } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { Eye, EyeOff, Loader2, Mail, Save } from 'lucide-react';
|
||||
import type { SystemSettings } from '../../../../shared/api-contract';
|
||||
import type { SystemSettings } from '../api';
|
||||
|
||||
// NotificationSmtpSettingsProps 描述系统 SMTP 配置面板所需的状态和事件。
|
||||
export interface NotificationSmtpSettingsProps {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { NotificationChannel, SystemSettings } from '../../../shared/api-contract';
|
||||
import { createNotificationChannel, deleteNotificationChannel, getNotificationChannels, getSystemSettings, testNotificationChannel, updateNotificationChannel, updateSystemSettings } from './api';
|
||||
import { act,renderHook,waitFor } from '@testing-library/react';
|
||||
import { beforeEach,describe,expect,test,vi } from 'vitest';
|
||||
import type { NotificationChannel,SystemSettings } from '../../../shared/api-contract/notifications';
|
||||
import { createNotificationChannel,deleteNotificationChannel,getNotificationChannels,getSystemSettings,testNotificationChannel,updateNotificationChannel,updateSystemSettings } from './api';
|
||||
import { useNotifications } from './hooks';
|
||||
|
||||
vi.mock('./api', /* notificationsApiMockFactory 提供通知 Hook 的确定性 API 替身。 */ () => ({
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import type { NotificationChannel, NotificationChannelType, SystemSettings } from '../../../shared/api-contract';
|
||||
import { createNotificationChannel, deleteNotificationChannel, getNotificationChannels, getSystemSettings, testNotificationChannel, updateNotificationChannel, updateSystemSettings } from './api';
|
||||
import { buildNotificationPayload, emptyNotificationForm, isCurrentNotificationRequest, notificationErrorMessage, normalizeNotificationForm, validateNotificationForm } from './state';
|
||||
import type { NotificationForm, NotificationState } from './types';
|
||||
import { useCallback,useEffect,useRef,useState } from 'react';
|
||||
import type { NotificationChannel,SystemSettings } from './api';
|
||||
import { createNotificationChannel,deleteNotificationChannel,getNotificationChannels,getSystemSettings,testNotificationChannel,updateNotificationChannel,updateSystemSettings } from './api';
|
||||
import { buildNotificationPayload,emptyNotificationForm,isCurrentNotificationRequest,normalizeNotificationForm,notificationErrorMessage,validateNotificationForm } from './state';
|
||||
import type { NotificationForm,NotificationState } from './types';
|
||||
|
||||
// useNotifications 统一管理通知渠道、事件订阅和系统 SMTP 的异步状态。
|
||||
export const useNotifications = (isAdmin: boolean): NotificationState => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Bell,Check,Loader2,Plus,RefreshCw,X } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { Bell, Check, Loader2, Plus, RefreshCw, X } from 'lucide-react';
|
||||
import { NotificationChannelList } from '../components/NotificationChannelList';
|
||||
import { NotificationChannelModal } from '../components/NotificationChannelModal';
|
||||
import { NotificationSmtpSettings } from '../components/NotificationSmtpSettings';
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { expect, test } from 'vitest';
|
||||
import type { NotificationChannel } from '../../../shared/api-contract';
|
||||
import { expect,test } from 'vitest';
|
||||
import type { NotificationChannel } from '../../../shared/api-contract/notifications';
|
||||
import { buildNotificationPayload,emptyNotificationForm,isCurrentNotificationRequest,normalizeNotificationForm,notificationErrorMessage,notificationEventSummary,validateNotificationForm } from './state';
|
||||
import type { NotificationForm } from './types';
|
||||
import { buildNotificationPayload, emptyNotificationForm, isCurrentNotificationRequest, normalizeNotificationForm, notificationErrorMessage, notificationEventSummary, validateNotificationForm } from './state';
|
||||
|
||||
// createForm 创建通知渠道校验使用的最小表单对象。
|
||||
const createForm = (overrides: Partial<NotificationForm> = {}): NotificationForm => ({
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Bell, Mail, MessageCircle, Send as Telegram, Webhook } from 'lucide-react';
|
||||
import type { NotificationChannel, NotificationChannelType, NotificationEventType, SystemSettings } from '../../../shared/api-contract';
|
||||
import { buildEmailChannelConfig, enableCustomSMTP, normalizeEmailChannelConfig } from '../../../notificationEmailConfig';
|
||||
import type { NotificationChannelMeta, NotificationEventMeta, NotificationForm, NotificationPayload } from './types';
|
||||
import { Bell,Mail,MessageCircle,Send as Telegram,Webhook } from 'lucide-react';
|
||||
import { buildEmailChannelConfig,enableCustomSMTP,normalizeEmailChannelConfig } from '../../../notificationEmailConfig';
|
||||
import type { NotificationChannel,NotificationChannelType,NotificationEventType,SystemSettings } from './api';
|
||||
import type { NotificationChannelMeta,NotificationEventMeta,NotificationForm,NotificationPayload } from './types';
|
||||
|
||||
// notificationChannelTypes 是所有通知渠道的静态字段、图标和使用指南。
|
||||
export const notificationChannelTypes: Record<NotificationChannelType, NotificationChannelMeta> = {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { Dispatch, ElementType, SetStateAction } from 'react';
|
||||
import type { NotificationChannel, NotificationChannelType, NotificationEventType, SystemSettings } from '../../../shared/api-contract';
|
||||
import type { Dispatch,ElementType,SetStateAction } from 'react';
|
||||
import type { NotificationChannel,NotificationChannelType,NotificationEventType,SystemSettings } from './api';
|
||||
|
||||
// NotificationField 描述通知渠道表单中的一个配置字段。
|
||||
export interface NotificationField {
|
||||
|
||||
@@ -1,12 +1,20 @@
|
||||
import { get, post, put, del, postForm, type RequestControlOptions } from '../../../shared/http/client';
|
||||
import {
|
||||
SessionResponse, AccountDetail, AccountSummaryResponse, Order, PaginatedResponse,
|
||||
AdminStats, DashboardStats, Card, SystemSettings, OrderAnalytics,
|
||||
Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction, AutomationTriggerType,
|
||||
NotificationChannel, NotificationEventType, AccountTaskSettings, ChatSession, ChatMessage, ItemListEnvelope, AutomationIssuesEnvelope,
|
||||
CookieSettingsResponse, CookieProfileResponse, ItemDetailResponse, ItemPublishResponse, ItemSyncResponse, OrderDTOResponse, OrderDetailResponse, OrderSingleRefreshResponse, OrderBatchResponse, OrderRefreshResponse, OrderRefreshJobStartResponse, OrderRefreshJobStatusResponse, OrderRefreshJobCancelResponse, AutomationRuleResponse, AutomationRulePageResponse, AIReplySettingsResponse, AIModelsResponse, UserSettingResponse, CardBatchResponse, CardAppendResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchListResponse, BatchIDResponse, ItemPublishBatchResponse, BatchCancelResponse, MutationIDResponse, OperationResponse, NotificationChannelResponse, NotificationBinding, AccountBindingsResponse, CardListResponse, KeywordTypedResponse, DefaultReplyResponse, AccountTaskSettingsResponse, AccountTaskRunResponseEnvelope, AdminStatsResponse, DashboardStatsResponse, OrderAnalyticsResponse, QRLoginGenerateResponse, QRLoginStatusResponse, QRLoginVerificationResponse, ValidOrderResponse, ValidOrdersResponse
|
||||
} from '../../../shared/api-contract';
|
||||
import { collectionFrom, objectFrom } from '../../../shared/http/contract';
|
||||
AccountDetail,
|
||||
AdminStatsResponse,
|
||||
Item,
|
||||
OperationResponse,
|
||||
Order,
|
||||
OrderBatchResponse,
|
||||
OrderDTOResponse,OrderDetailResponse,
|
||||
OrderRefreshJobCancelResponse,
|
||||
OrderRefreshJobStartResponse,OrderRefreshJobStatusResponse,
|
||||
OrderRefreshResponse,
|
||||
OrderSingleRefreshResponse,
|
||||
PaginatedResponse
|
||||
} from '../../../shared/api-contract/orders';
|
||||
import { del,get,post,postForm,put,type RequestControlOptions } from '../../../shared/http/client';
|
||||
import { collectionFrom,objectFrom } from '../../../shared/http/contract';
|
||||
export type * from '../../../shared/api-contract/orders';
|
||||
|
||||
/** 订单筛选器读取非敏感账号摘要。 */
|
||||
export const getAccountDetails = async (options?: RequestControlOptions): Promise<AccountDetail[]> => get('/api/v1/accounts/details', undefined, options);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Search,User as UserIcon } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { Search, User as UserIcon } from 'lucide-react';
|
||||
import type { AccountDetail } from '../../../../shared/api-contract';
|
||||
import type { AccountDetail } from '../api';
|
||||
import { orderStatusOptions } from '../state';
|
||||
|
||||
// OrderFilterBarProps 描述订单状态、账号和文本筛选所需的页面状态。
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Upload,X } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { Upload, X } from 'lucide-react';
|
||||
import { failedOrderImportRows } from '../state';
|
||||
import type { OrderImportState } from '../types';
|
||||
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { AccountDetail, Item } from '../../../shared/api-contract';
|
||||
import { getAccountDetails, getItems, getOrders, importOrders } from './api';
|
||||
import { useOrderImport, useOrderQuery } from './hooks';
|
||||
import { act,renderHook,waitFor } from '@testing-library/react';
|
||||
import { beforeEach,describe,expect,test,vi } from 'vitest';
|
||||
import type { AccountDetail,Item } from '../../../shared/api-contract/orders';
|
||||
import { getAccountDetails,getItems,getOrders,importOrders } from './api';
|
||||
import { useOrderImport,useOrderQuery } from './hooks';
|
||||
|
||||
vi.mock('./api', /* ordersApiMockFactory 提供订单 Hook 的确定性 API 替身。 */ () => ({
|
||||
getAccountDetails: vi.fn(),
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type Dispatch, type SetStateAction } from 'react';
|
||||
import type { AccountDetail, Item, Order } from '../../../shared/api-contract';
|
||||
import { getAccountDetails, getItems, getOrders, importOrders } from './api';
|
||||
import { canSubmitOrderImport, isCurrentOrderRequest, normalizeOrderImportResult, orderErrorMessage, validateOrderImportFile } from './state';
|
||||
import type { OrderImportState, OrderQueryState } from './types';
|
||||
import { useCallback,useEffect,useMemo,useRef,useState } from 'react';
|
||||
import type { AccountDetail,Item,Order } from './api';
|
||||
import { getAccountDetails,getItems,getOrders,importOrders } from './api';
|
||||
import { canSubmitOrderImport,isCurrentOrderRequest,normalizeOrderImportResult,orderErrorMessage,validateOrderImportFile } from './state';
|
||||
import type { OrderImportState,OrderQueryState } from './types';
|
||||
|
||||
// OrderQueryOptions 描述订单查询 Hook 的固定分页参数。
|
||||
interface OrderQueryOptions {
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { Order } from '../../../shared/api-contract';
|
||||
import { deleteOrder, manualShipOrder, syncOrders, syncSingleOrder, updateOrder } from './api';
|
||||
import { act,renderHook } from '@testing-library/react';
|
||||
import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest';
|
||||
import type { Order } from '../../../shared/api-contract/orders';
|
||||
import { useOrderActions } from './orderActions';
|
||||
|
||||
// orderActionMocks 保存订单动作 Hook 测试使用的 API 替身。
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useCallback, useState, type Dispatch, type SetStateAction } from 'react';
|
||||
import type { Order, OrderStatus } from '../../../shared/api-contract';
|
||||
import { deleteOrder, manualShipOrder, syncOrders, syncSingleOrder, updateOrder } from './api';
|
||||
import { useCallback,useState,type Dispatch,type SetStateAction } from 'react';
|
||||
import type { Order } from './api';
|
||||
import { deleteOrder,manualShipOrder,syncOrders,syncSingleOrder,updateOrder } from './api';
|
||||
|
||||
// OrderShipMode 表示订单发货操作的两种业务模式。
|
||||
export type OrderShipMode = 'status_only' | 'full_delivery';
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// @vitest-environment jsdom
|
||||
import { cleanup,fireEvent,render,screen,waitFor } from '@testing-library/react';
|
||||
import React from 'react';
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { Order } from '../../../../shared/api-contract';
|
||||
import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest';
|
||||
import type { Order } from '../../../../shared/api-contract/orders';
|
||||
|
||||
// orderListMocks 保存订单页面测试使用的 Hook、API 和子组件替身。
|
||||
const orderListMocks = vi.hoisted(/* orderListMockFactory 创建订单页面共享替身。 */ () => ({
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { ChevronLeft,ChevronRight,Edit,ExternalLink,Eye,PackageCheck,Plus,RefreshCw,Save,Trash2,Truck,User as UserIcon,X } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import type { OrderStatus } from '../../../../shared/api-contract';
|
||||
import { formatLocalDateTime } from '../../../../dateTime';
|
||||
import type { OrderStatus } from '../api';
|
||||
import { OrderFilterBar } from '../components/OrderFilterBar';
|
||||
import { OrderImportModal } from '../components/OrderImportModal';
|
||||
import { useOrderImport, useOrderQuery } from '../hooks';
|
||||
import { useOrderImport,useOrderQuery } from '../hooks';
|
||||
import { useOrderActions } from '../orderActions';
|
||||
import { Truck, RefreshCw, ChevronLeft, ChevronRight, PackageCheck, Edit, Eye, Plus, Save, X, User as UserIcon, ExternalLink, Trash2 } from 'lucide-react';
|
||||
import { formatLocalDateTime } from '../../../../dateTime';
|
||||
|
||||
// StatusBadge 渲染订单状态徽标。
|
||||
const StatusBadge: React.FC<{ /** status 表示状态。 */ status: OrderStatus }> = ({ status }) => {
|
||||
@@ -56,7 +56,6 @@ const OrderList: React.FC = () => {
|
||||
showEditModal,
|
||||
editingOrder,
|
||||
showShipModal,
|
||||
shipOrderId,
|
||||
shipLoading,
|
||||
shipResult,
|
||||
syncingOrderId,
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { expect, test } from 'vitest';
|
||||
import { expect,test } from 'vitest';
|
||||
import {
|
||||
canSubmitOrderImport,
|
||||
failedOrderImportRows,
|
||||
isCurrentOrderRequest,
|
||||
normalizeOrderImportResult,
|
||||
orderStatusOptions,
|
||||
validateOrderImportFile,
|
||||
canSubmitOrderImport,
|
||||
failedOrderImportRows,
|
||||
isCurrentOrderRequest,
|
||||
normalizeOrderImportResult,
|
||||
orderStatusOptions,
|
||||
validateOrderImportFile,
|
||||
} from './state';
|
||||
|
||||
// createFile 创建订单导入预检使用的最小浏览器文件对象。
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { OrderImportResult, OrderImportRowResult } from './types';
|
||||
import type { OrderImportResult,OrderImportRowResult } from './types';
|
||||
|
||||
// orderStatusOptions 是订单状态筛选标签的稳定配置。
|
||||
export const orderStatusOptions = [
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { Dispatch, SetStateAction } from 'react';
|
||||
import type { AccountDetail, Item, Order, OrderStatus } from '../../../shared/api-contract';
|
||||
import type { Dispatch,SetStateAction } from 'react';
|
||||
import type { AccountDetail,Item,Order,OrderStatus } from './api';
|
||||
|
||||
// OrderImportRowResult 描述订单导入接口返回的单行处理结果。
|
||||
export interface OrderImportRowResult {
|
||||
|
||||
Loaded 100 of 176 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user