修正商品发货地定位逻辑
改用高德地图附近 POI 查询发货地,移除闲鱼定位接口调用。发货地改为可选项,虚拟商品可直接发布;修正闲鱼网页版要求的纬度、经度 GPS 顺序,并补充前端映射与发布测试。
This commit is contained in:
1 parent
65bcb8f15c
commit
ac85ac8a0a
15 files changed
+255
-214
No files matched your search
@@ -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: '上海市',
|
||||
});
|
||||
});
|
||||
|
||||
test('drops incomplete or invalid AMap POIs', () => {
|
||||
expect(amapPOIToPublishLocation({
|
||||
id: 'poi',
|
||||
name: '无坐标',
|
||||
adcode: '310101',
|
||||
pname: '上海市',
|
||||
cityname: '上海市',
|
||||
location: { lng: 0, lat: 31.2 },
|
||||
})).toBeNull();
|
||||
});
|
||||
@@ -0,0 +1,153 @@
|
||||
import type { PublishLocation } from './api';
|
||||
|
||||
const AMAP_SCRIPT_ID = 'ydisks-amap-js-api';
|
||||
// 高德 JS API 的 Key 是前端公开 Key;部署时可通过 VITE_AMAP_JS_KEY 覆盖。
|
||||
const DEFAULT_AMAP_JS_KEY = 'c9b68d4ce9a2a97f22a4a439404488ca';
|
||||
|
||||
export interface AMapLocationValue {
|
||||
lng: number;
|
||||
lat: number;
|
||||
}
|
||||
|
||||
export interface AMapPOI {
|
||||
id?: string;
|
||||
name?: string;
|
||||
address?: string;
|
||||
adname?: string;
|
||||
cityname?: string;
|
||||
adcode?: string | number;
|
||||
pname?: string;
|
||||
location?: AMapLocationValue;
|
||||
}
|
||||
|
||||
interface AMapPlaceSearchResult {
|
||||
poiList?: {
|
||||
pois?: AMapPOI[];
|
||||
};
|
||||
}
|
||||
|
||||
interface AMapPlaceSearch {
|
||||
searchNearBy(
|
||||
keyword: string,
|
||||
center: [number, number],
|
||||
radius: number,
|
||||
callback: (status: string, result: AMapPlaceSearchResult) => void,
|
||||
): void;
|
||||
}
|
||||
|
||||
interface AMapAPI {
|
||||
PlaceSearch: new (options: { extensions: 'all'; pageSize: number }) => AMapPlaceSearch;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
AMap?: AMapAPI;
|
||||
__ydisksAmapLoaded?: () => void;
|
||||
}
|
||||
|
||||
interface ImportMetaEnv {
|
||||
readonly VITE_AMAP_JS_KEY?: string;
|
||||
}
|
||||
|
||||
interface ImportMeta {
|
||||
readonly env: ImportMetaEnv;
|
||||
}
|
||||
}
|
||||
|
||||
let amapLoadPromise: Promise<AMapAPI> | null = null;
|
||||
|
||||
const configuredAmapKey = (): string => {
|
||||
const key = import.meta.env.VITE_AMAP_JS_KEY?.trim();
|
||||
return key || DEFAULT_AMAP_JS_KEY;
|
||||
};
|
||||
|
||||
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;
|
||||
const script = existing || document.createElement('script');
|
||||
const cleanup = () => {
|
||||
window.__ydisksAmapLoaded = undefined;
|
||||
window.clearTimeout(timeout);
|
||||
};
|
||||
const finish = () => {
|
||||
if (window.AMap) {
|
||||
cleanup();
|
||||
resolve(window.AMap);
|
||||
} else {
|
||||
cleanup();
|
||||
reject(new Error('高德地图 API 加载完成但未找到 AMap 对象'));
|
||||
}
|
||||
};
|
||||
const timeout = window.setTimeout(() => {
|
||||
cleanup();
|
||||
reject(new Error('高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置'));
|
||||
}, 15_000);
|
||||
|
||||
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 配置'));
|
||||
};
|
||||
if (!existing) document.head.appendChild(script);
|
||||
}).catch(error => {
|
||||
amapLoadPromise = null;
|
||||
throw error;
|
||||
});
|
||||
|
||||
return amapLoadPromise;
|
||||
};
|
||||
|
||||
const validCoordinate = (value: number): boolean => Number.isFinite(value) && value !== 0;
|
||||
|
||||
// 字段映射与闲鱼网页版发布页一致:adcode → divisionId,name → poi,pname/cityname/adname → 行政区。
|
||||
export const amapPOIToPublishLocation = (poi: AMapPOI): PublishLocation | null => {
|
||||
const longitude = Number(poi.location?.lng);
|
||||
const latitude = Number(poi.location?.lat);
|
||||
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(),
|
||||
};
|
||||
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): Promise<PublishLocation[]> => {
|
||||
if (!validCoordinate(longitude) || !validCoordinate(latitude) || longitude < -180 || longitude > 180 || latitude < -90 || latitude > 90) {
|
||||
throw new Error('经纬度无效');
|
||||
}
|
||||
const amap = await loadAMap();
|
||||
return new Promise<PublishLocation[]>((resolve, reject) => {
|
||||
const placeSearch = new amap.PlaceSearch({ extensions: 'all', pageSize: 10 });
|
||||
placeSearch.searchNearBy('', [longitude, latitude], 1_000, (status, result) => {
|
||||
if (status !== 'complete') {
|
||||
if (status === 'no_data') {
|
||||
resolve([]);
|
||||
return;
|
||||
}
|
||||
reject(new Error('高德地图附近地址查询失败,请稍后重试'));
|
||||
return;
|
||||
}
|
||||
const locations = (result?.poiList?.pois || [])
|
||||
.map(amapPOIToPublishLocation)
|
||||
.filter((location): location is PublishLocation => location !== null);
|
||||
resolve(locations);
|
||||
});
|
||||
});
|
||||
};
|
||||
@@ -17,8 +17,9 @@ import {
|
||||
getShippingRules,
|
||||
getShippingRulesPage,
|
||||
getSystemSettings,
|
||||
getValidOrders,
|
||||
logout,
|
||||
getValidOrders,
|
||||
publishItem,
|
||||
logout,
|
||||
importOrders,
|
||||
passwordLogin,
|
||||
resolveAutomationRun,
|
||||
@@ -228,6 +229,22 @@ test('deleteItemPublishBatch removes an abandoned preview', async () => {
|
||||
}));
|
||||
});
|
||||
|
||||
test('publishItem allows virtual publishing without an optional location', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
await publishItem({
|
||||
cookie_id: 'acc1',
|
||||
title: '虚拟商品',
|
||||
description: '',
|
||||
price: '12.50',
|
||||
quantity: 1,
|
||||
postage_mode: 'none',
|
||||
images: [],
|
||||
});
|
||||
const body = fetchMock.mock.calls[0][1].body as FormData;
|
||||
expect(body.get('location')).toBeNull();
|
||||
});
|
||||
|
||||
test('getItems normalizes multi-spec flags from backend values', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse([{
|
||||
cookie_id: 'cookie-1',
|
||||
|
||||
@@ -526,7 +526,7 @@ export const publishItem = async (form: {
|
||||
postage_mode: string;
|
||||
postage?: string;
|
||||
images: File[];
|
||||
location: PublishLocation;
|
||||
location?: PublishLocation;
|
||||
}): Promise<any> => {
|
||||
const body = new FormData();
|
||||
body.set('cookie_id', form.cookie_id);
|
||||
@@ -537,7 +537,7 @@ export const publishItem = async (form: {
|
||||
body.set('quantity', String(form.quantity));
|
||||
body.set('postage_mode', form.postage_mode);
|
||||
body.set('postage', form.postage || '');
|
||||
body.set('location', JSON.stringify(form.location));
|
||||
if (form.location) body.set('location', JSON.stringify(form.location));
|
||||
for (const file of form.images) {
|
||||
body.append('images', file);
|
||||
}
|
||||
@@ -555,11 +555,6 @@ export interface PublishLocation {
|
||||
province: string;
|
||||
}
|
||||
|
||||
export const getPublishLocations = async (cookieId: string, longitude: number, latitude: number): Promise<PublishLocation[]> => {
|
||||
const result = await post<any>('/items/publish-locations', { cookie_id: cookieId, longitude, latitude });
|
||||
return Array.isArray(result?.locations) ? result.locations : [];
|
||||
}
|
||||
|
||||
export const recommendPublishCategory = async (cookieId: string, keyword: string): Promise<{
|
||||
success: boolean;
|
||||
category: {
|
||||
@@ -582,7 +577,7 @@ export const previewItemPublishBatch = async (form: {
|
||||
channelCatId?: string;
|
||||
tbCatId?: string;
|
||||
};
|
||||
location: PublishLocation;
|
||||
location?: PublishLocation;
|
||||
}): Promise<any> => {
|
||||
const body = new FormData();
|
||||
body.set('file', form.file);
|
||||
@@ -592,7 +587,7 @@ export const previewItemPublishBatch = async (form: {
|
||||
body.set('fallback_category_name', form.fallbackCategory.catName);
|
||||
body.set('fallback_channel_category_id', form.fallbackCategory.channelCatId || '');
|
||||
body.set('fallback_tb_category_id', form.fallbackCategory.tbCatId || '');
|
||||
body.set('location', JSON.stringify(form.location));
|
||||
if (form.location) body.set('location', JSON.stringify(form.location));
|
||||
return postForm('/items/publish-batches/preview', body);
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user