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

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

No files matched your search

@@ -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 会被丢弃。 */);
+202
View File
@@ -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('稍后重试');
});
});
+43 -11
View File
@@ -1,14 +1,21 @@
import { get, post, put, del, postForm, type RequestControlOptions } from '../../../shared/http/client';
import type { PublishLocation } from '../../../shared/api-contract/items';
import {
SessionResponse, AccountDetail, AccountSummaryResponse, Order, PaginatedResponse,
AdminStats, DashboardStats, Card, SystemSettings, OrderAnalytics,
Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction, AutomationTriggerType,
NotificationChannel, NotificationEventType, AccountTaskSettings, ChatSession, ChatMessage, ItemListEnvelope, AutomationIssuesEnvelope,
CookieSettingsResponse, CookieProfileResponse, ItemDetailResponse, ItemPublishResponse, ItemSyncResponse, OrderDTOResponse, OrderDetailResponse, OrderSingleRefreshResponse, OrderBatchResponse, OrderRefreshResponse, OrderRefreshJobStartResponse, OrderRefreshJobStatusResponse, OrderRefreshJobCancelResponse, AutomationRuleResponse, AutomationRulePageResponse, AIReplySettingsResponse, AIModelsResponse, UserSettingResponse, CardBatchResponse, CardAppendResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchListResponse, BatchIDResponse, ItemPublishBatchResponse, BatchCancelResponse, MutationIDResponse, OperationResponse, NotificationChannelResponse, NotificationBinding, AccountBindingsResponse, CardListResponse, KeywordTypedResponse, DefaultReplyResponse, AccountTaskSettingsResponse, AccountTaskRunResponseEnvelope, AdminStatsResponse, DashboardStatsResponse, OrderAnalyticsResponse, QRLoginGenerateResponse, QRLoginStatusResponse, QRLoginVerificationResponse, ValidOrderResponse, ValidOrdersResponse
} from '../../../shared/api-contract';
import { collectionFrom, objectFrom } from '../../../shared/http/contract';
import { getPublishLocations as queryPublishLocations, type PublishLocationRequestOptions } from '../../../services/amapLocation';
import type { PublishLocation } from '../../../shared/api-contract';
AccountDetail,
BatchCancelResponse,
BatchIDResponse,
CategoryRecommendationResponse,
Item,
ItemDetailResponse,
ItemPublishBatchPreviewResponse,
ItemPublishBatchResponse,
ItemPublishResponse,ItemSyncResponse,
OperationResponse,
ShippingRule
} from '../../../shared/api-contract/items';
import { ApiError,del,get,post,postForm,put,type RequestControlOptions } from '../../../shared/http/client';
import { collectionFrom } from '../../../shared/http/contract';
export type * from '../../../shared/api-contract/items';
import { getPublishLocations as queryPublishLocations,type PublishLocationRequestOptions } from './amapLocation';
/** 商品账号筛选器读取非敏感账号摘要。 */
export const getAccountDetails = async (options?: RequestControlOptions): Promise<AccountDetail[]> => get('/api/v1/accounts/details', undefined, options);
@@ -18,7 +25,32 @@ export const getShippingRules = async (options?: RequestControlOptions): Promise
// getPublishLocations 通过 feature API 边界读取地点,并把取消/超时控制传入地图服务。
export const getPublishLocations = (longitude: number, latitude: number, options?: PublishLocationRequestOptions): Promise<PublishLocation[]> => queryPublishLocations(longitude, latitude, options);
export type { PublishLocation } from '../../../shared/api-contract';
export type { PublishLocation } from '../../../shared/api-contract/items';
// itemErrorMessage 将统一 HTTP 错误码归一为商品 feature 可执行的用户提示。
export const itemErrorMessage = (error: unknown, fallback: string): string => {
if (error instanceof ApiError) {
switch (error.code) {
case 'stock_permission_missing':
return '发布失败:该账号没有库存发布权限,无法按库存数量发布商品。请换账号或先在闲鱼确认库存能力。';
case 'conflict':
case 'item_conflict':
return '商品状态已发生变化,请刷新后重试。';
case 'external_result_unknown':
case 'manual_review_required':
return '平台结果暂时无法确认,请先人工核对闲鱼状态,再决定是否重试。';
case 'retryable':
case 'temporarily_unavailable':
return '平台暂时不可用,请稍后重试。';
default:
return error.message || fallback;
}
}
if (error instanceof Error) return error.message;
// message 保存兼容 API 错误对象中的文本说明。
const message = typeof error === 'object' && error !== null && 'message' in error ? (error as { /** message 是兼容错误对象中的文本说明。 */ message?: unknown }).message : undefined;
return typeof message === 'string' ? message : fallback;
};
// Items
// normalizeBooleanFlag 归一化布尔标记。
const normalizeBooleanFlag = (value: unknown): boolean =>
@@ -1,12 +1,12 @@
import { describe, expect, test } from 'vitest';
import { describe,expect,test } from 'vitest';
import {
batchStatusText,
batchStatusClass,
canRetryBatch,
canStartBatch,
isBatchInProgress,
isCurrentBatchRequest,
selectActivePublishBatch,
batchStatusClass,
batchStatusText,
canRetryBatch,
canStartBatch,
isBatchInProgress,
isCurrentBatchRequest,
selectActivePublishBatch,
} from './batchState';
// ItemList 批量行为测试覆盖预检、取消、重试和过期任务响应。
+11 -11
View File
@@ -1,16 +1,16 @@
// @vitest-environment jsdom
import { act, renderHook, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, test, vi } from 'vitest';
import type { BatchCancelResponse, BatchIDResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchResponse } from '../../../shared/api-contract';
import { act,renderHook } from '@testing-library/react';
import { beforeEach,describe,expect,test,vi } from 'vitest';
import type { BatchCancelResponse,BatchIDResponse,CategoryRecommendationResponse,ItemPublishBatchPreviewResponse,ItemPublishBatchResponse } from '../../../shared/api-contract/items';
import {
cancelItemPublishBatch,
deleteItemPublishBatch,
getItemPublishBatch,
getItemPublishBatches,
previewItemPublishBatch,
recommendPublishCategory,
retryFailedItemPublishBatch,
startItemPublishBatch,
cancelItemPublishBatch,
deleteItemPublishBatch,
getItemPublishBatch,
getItemPublishBatches,
previewItemPublishBatch,
recommendPublishCategory,
retryFailedItemPublishBatch,
startItemPublishBatch,
} from './api';
import { useItemPublishBatch } from './hooks';
+16 -16
View File
@@ -1,22 +1,22 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useCallback,useEffect,useRef,useState } from 'react';
import {
cancelItemPublishBatch,
deleteItemPublishBatch,
getItemPublishBatch,
getItemPublishBatches,
recommendPublishCategory,
previewItemPublishBatch,
retryFailedItemPublishBatch,
startItemPublishBatch,
cancelItemPublishBatch,
deleteItemPublishBatch,
getItemPublishBatch,
getItemPublishBatches,
previewItemPublishBatch,
recommendPublishCategory,
retryFailedItemPublishBatch,
startItemPublishBatch,
} from './api';
import { canRetryBatch, canStartBatch, isBatchInProgress, isCurrentBatchRequest, selectActivePublishBatch } from './batchState';
import { canRetryBatch,canStartBatch,isBatchInProgress,isCurrentBatchRequest,selectActivePublishBatch } from './batchState';
import type {
BatchFallbackCategory,
BatchPhase,
ItemPublishBatchOptions,
ItemPublishBatchState,
PublishBatchDetail,
PublishBatchPreview,
BatchFallbackCategory,
BatchPhase,
ItemPublishBatchOptions,
ItemPublishBatchState,
PublishBatchDetail,
PublishBatchPreview,
} from './types';
// useItemPublishBatch 集中管理批量铺货的表单、任务恢复、轮询和重试状态。
@@ -1,15 +1,16 @@
// @vitest-environment jsdom
import { act, renderHook } from '@testing-library/react';
import { act,renderHook } from '@testing-library/react';
import { useState } from 'react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import type { Item } from '../../../shared/api-contract';
import { createItem, deleteItem, getPublishLocations, publishItem, syncItemsFromAccount, updateItem } from './api';
import { useItemActions, type ItemActionsOptions } from './itemActions';
import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest';
import type { Item } from '../../../shared/api-contract/items';
import { createItem,deleteItem,getPublishLocations,publishItem,syncItemsFromAccount,updateItem } from './api';
import { useItemActions,type ItemActionsOptions } from './itemActions';
vi.mock('./api', /* itemActionsApiMockFactory 提供商品动作 Hook 的确定性 API 替身。 */ () => ({
createItem: vi.fn(),
deleteItem: vi.fn(),
getPublishLocations: vi.fn(),
itemErrorMessage: /* errorMessageMock 将测试动作中的异常转换为稳定回退文本。 */ (error: unknown, fallback: string) => error instanceof Error ? error.message : fallback,
publishItem: vi.fn(),
syncItemsFromAccount: vi.fn(),
updateItem: vi.fn(),
+3 -17
View File
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useRef, useState, type Dispatch, type SetStateAction } from 'react';
import type { Item } from '../../../shared/api-contract';
import { createItem, deleteItem, getPublishLocations, publishItem, syncItemsFromAccount, updateItem } from './api';
import { useCallback,useEffect,useRef,useState,type Dispatch,type SetStateAction } from 'react';
import type { Item } from './api';
import type { PublishLocation } from './api';
import { createItem,deleteItem,getPublishLocations,itemErrorMessage,publishItem,syncItemsFromAccount,updateItem } from './api';
// AddItemForm 描述手动添加商品弹窗的表单字段。
export interface AddItemForm {
@@ -135,14 +135,6 @@ export const emptyAddItemForm = (): AddItemForm => ({ cookie_id: '', item_id: ''
// emptyPublishItemForm 创建普通发布商品表单的初始值。
export const emptyPublishItemForm = (cookieID = ''): PublishItemForm => ({ cookie_id: cookieID, title: '', description: '', price: '', original_price: '', quantity: '1', postage_mode: 'free', postage: '', images: [] });
// itemErrorMessage 将未知异常转换为稳定的商品操作提示。
const itemErrorMessage = (error: unknown, fallback: string): string => {
if (error instanceof Error) return error.message;
// message 保存兼容 API 错误对象中的文本说明。
const message = typeof error === 'object' && error !== null && 'message' in error ? (error as { /** message 是兼容错误对象中的文本说明。 */ message?: unknown }).message : undefined;
return typeof message === 'string' ? message : fallback;
};
// useItemActions 集中管理商品同步、编辑、删除、添加、普通发布和定位动作。
export const useItemActions = ({ selectedAccount, setSelectedAccount, setItems, loadItems, loadShippingRules, onConfigureDelivery, setBatchLocations, setBatchLocation }: ItemActionsOptions): ItemActionsState => {
// loading 表示商品同步请求是否正在执行。
@@ -302,12 +294,6 @@ export const useItemActions = ({ selectedAccount, setSelectedAccount, setItems,
}
} catch (/* error 表示商品发布请求异常。 */ error: unknown) {
console.error('发布商品失败:', error);
// payload 保存服务端返回的结构化错误载荷。
const payload = (error as { /** payload 是服务端结构化错误载荷。 */ payload?: { /** code 是服务端错误码。 */ code?: unknown } })?.payload;
if (payload?.code === 'stock_permission_missing') {
alert('发布失败:该账号没有库存发布权限,无法按库存数量发布商品。请换账号或先在闲鱼确认库存能力。');
return;
}
alert(itemErrorMessage(error, '发布失败,请重试'));
} finally {
setPublishing(false);
+10 -11
View File
@@ -1,19 +1,18 @@
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { ArrowRight,Box,CheckCircle2,CircleDashed,Edit,Filter,Link2,LocateFixed,PackagePlus,Plus,RefreshCw,Save,Search,ShoppingBag,Trash2,UploadCloud,User,X } from 'lucide-react';
import React,{ useCallback,useEffect,useMemo,useRef,useState } from 'react';
import { createPortal } from 'react-dom';
import type { Item } from '../../../../shared/api-contract';
import type { AccountDetail,Item,ShippingRule } from '../api';
import {
getItems,
getAccountDetails,
getShippingRules,
getItemPublishBatches,
getAccountDetails,
getItemPublishBatches,
getItems,
getShippingRules,
} from '../api';
import type { AccountDetail, ShippingRule } from '../../../../shared/api-contract';
import type { ItemListProps } from '../types';
import { batchStatusClass,batchStatusText } from '../batchState';
import { BatchPhaseIndicator } from '../components/BatchPhaseIndicator';
import { useItemPublishBatch } from '../hooks';
import { useItemActions } from '../itemActions';
import { batchStatusClass, batchStatusText } from '../batchState';
import { BatchPhaseIndicator } from '../components/BatchPhaseIndicator';
import { ArrowRight, Box, CheckCircle2, CircleDashed, Edit, Filter, Link2, LocateFixed, PackagePlus, Plus, RefreshCw, Save, Search, ShoppingBag, Trash2, UploadCloud, User, X } from 'lucide-react';
import type { ItemListProps } from '../types';
// formatItemPrice 将商品价格转换为本地化展示文本。
const formatItemPrice = (price?: string) => {
+2 -2
View File
@@ -1,5 +1,5 @@
import type { Dispatch, SetStateAction } from 'react';
import type { Item, AccountDetail, ShippingRule } from '../../../shared/api-contract';
import type { Dispatch,SetStateAction } from 'react';
import type { AccountDetail,Item,ShippingRule } from './api';
import type { PublishLocation } from './api';
// ItemListProps 描述商品页面从父级接收的规则配置回调。