修正商品发货地定位逻辑

改用高德地图附近 POI 查询发货地,移除闲鱼定位接口调用。发货地改为可选项,虚拟商品可直接发布;修正闲鱼网页版要求的纬度、经度 GPS 顺序,并补充前端映射与发布测试。
This commit is contained in:
Christ committed 2026-08-13 11:44:35 +08:00
1 parent 65bcb8f15c
commit ac85ac8a0a
15 files changed
+255 -214

No files matched your search

+9 -11
View File
@@ -9,7 +9,6 @@ import {
createItem,
publishItem,
recommendPublishCategory,
getPublishLocations,
previewItemPublishBatch,
startItemPublishBatch,
getItemPublishBatch,
@@ -22,6 +21,7 @@ import {
getShippingRules
} from '../services/api';
import type { PublishLocation } from '../services/api';
import { getPublishLocations } from '../services/amapLocation';
import { ArrowRight, Box, CheckCircle2, CircleDashed, Edit, Filter, Link2, LocateFixed, PackagePlus, Plus, RefreshCw, Save, Search, ShoppingBag, Trash2, UploadCloud, User, X } from 'lucide-react';
interface ItemListProps {
@@ -292,13 +292,12 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
if (!publishForm.title.trim()) return alert('请填写商品标题');
if (!publishForm.price.trim()) return alert('请填写商品价格');
if (!publishForm.quantity || Number(publishForm.quantity) <= 0) return alert('库存数量必须大于 0');
if (publishForm.images.length === 0) return alert('至少上传 1 张商品图片');
if (publishForm.postage_mode === 'fixed' && !publishForm.postage.trim()) return alert('请填写一口价邮费');
if (!publishLocation) return alert('请获取当前位置并选择发货地');
if (publishForm.images.length === 0) return alert('至少上传 1 张商品图片');
if (publishForm.postage_mode === 'fixed' && !publishForm.postage.trim()) return alert('请填写一口价邮费');
setPublishing(true);
try {
const result = await publishItem({ ...publishForm, location: publishLocation });
const result = await publishItem({ ...publishForm, location: publishLocation || undefined });
await loadItems();
setShowPublishModal(false);
setPublishForm({
@@ -409,7 +408,6 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
const handlePreviewBatch = async () => {
if (!batchFile) return alert('请先上传商品表格');
if (!selectedAccount) return alert('请先选择默认发布账号');
if (!batchLocation) return alert('请获取当前位置并选择发货地');
setBatchLoading(true);
try {
const result = await previewItemPublishBatch({
@@ -417,7 +415,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
imagesZip: batchImagesZip,
defaultCookieId: selectedAccount,
fallbackCategory: batchFallbackCategory,
location: batchLocation!,
location: batchLocation || undefined,
});
setBatchPreview(result);
setBatchDetail(null);
@@ -538,8 +536,8 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
setLocationLoading(true);
navigator.geolocation.getCurrentPosition(async position => {
try {
const locations = await getPublishLocations(cookieId, position.coords.longitude, position.coords.latitude);
if (!locations.length) throw new Error('当前位置没有可用的发货地');
const locations = await getPublishLocations(position.coords.longitude, position.coords.latitude);
if (!locations.length) throw new Error('当前位置附近没有可用的高德发货地,请稍后重试');
if (batch) { setBatchLocations(locations); setBatchLocation(locations[0]); }
else { setPublishLocations(locations); setPublishLocation(locations[0]); }
} catch (error: any) {
@@ -906,7 +904,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
)}
<div className="rounded-2xl border border-sky-200 bg-sky-50 p-4 space-y-3">
<div className="flex items-center justify-between gap-3">
<div><div className="text-sm font-extrabold text-gray-900">发货地</div><p className="mt-1 text-xs text-sky-800">使用当前位置向闲鱼查询可发布的行政区。</p></div>
<div><div className="text-sm font-extrabold text-gray-900">发货地(可选)</div><p className="mt-1 text-xs text-sky-800">虚拟商品无需发货地;发布失败时可再定位并作为补充信息提交。</p></div>
<button type="button" disabled={locationLoading || !publishForm.cookie_id} onClick={() => void locateForPublish(false)} className="ios-btn-primary flex items-center gap-2 rounded-xl px-4 py-2 text-sm font-bold disabled:opacity-50">
<LocateFixed className="h-4 w-4" />{locationLoading ? '定位中...' : '获取当前位置'}
</button>
@@ -1067,7 +1065,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
<div className="rounded-xl border border-sky-200 bg-sky-50 p-4 space-y-3">
<div className="flex items-center justify-between gap-3">
<div><div className="text-sm font-extrabold text-gray-900">批次发货地</div><p className="mt-1 text-xs text-sky-800">整个批次使用同一个发货地,并随任务保存用于恢复和重试。</p></div>
<div><div className="text-sm font-extrabold text-gray-900">批次发货地(可选)</div><p className="mt-1 text-xs text-sky-800">虚拟商品可留空;填写后整个批次使用同一个发货地,并随任务保存用于恢复和重试。</p></div>
<button type="button" disabled={locationLoading || !selectedAccount} onClick={() => void locateForPublish(true)} className="ios-btn-primary flex items-center gap-2 rounded-xl px-4 py-2 text-sm font-bold disabled:opacity-50">
<LocateFixed className="h-4 w-4" />{locationLoading ? '定位中...' : '获取当前位置'}
</button>
+35
View File
@@ -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();
});
+153
View File
@@ -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);
});
});
};
+19 -2
View File
@@ -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',
+4 -9
View File
@@ -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);
}