fix(partner): restore Tencent locpicker iframe for store map pick

Partner H5 store create/edit uses locpicker again; expose LBS key for iframe.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-07-29 11:20:22 +08:00
parent 804054df33
commit c3362851ff
5 changed files with 164 additions and 258 deletions
@@ -1,8 +1,9 @@
import { useEffect, useRef, useState } from 'react'; import { useEffect, useMemo, useState } from 'react';
import type { ClientRuntimeConfig } from '@dukang/shared-types';
import { request } from '../lib/api'; import { request } from '../lib/api';
import { import {
placeToPicked, buildTencentLocPickerUrl,
type LbsPlaceItem, parseTencentLocPickerMessage,
type TencentPickedLocation, type TencentPickedLocation,
} from '../lib/tencentLocPicker'; } from '../lib/tencentLocPicker';
@@ -12,117 +13,79 @@ type Props = {
onPick: (loc: TencentPickedLocation) => void; onPick: (loc: TencentPickedLocation) => void;
latitude?: number | null; latitude?: number | null;
longitude?: number | null; longitude?: number | null;
region?: string | null;
}; };
let cachedKey: string | null | undefined;
async function loadTencentLbsKey(): Promise<string> {
if (cachedKey) return cachedKey;
const cfg = await request<ClientRuntimeConfig>('PARTNER_H5', '/common/client-config', {
silent: true,
});
const key = (cfg.tencentLbsKey || '').trim();
if (!key) {
throw new Error('未配置腾讯位置服务 Key,请联系管理员在系统设置中配置');
}
cachedKey = key;
return key;
}
export default function TencentLocPickerOverlay({ export default function TencentLocPickerOverlay({
open, open,
onClose, onClose,
onPick, onPick,
latitude, latitude,
longitude, longitude,
region,
}: Props) { }: Props) {
const [keyword, setKeyword] = useState(''); const [key, setKey] = useState<string | null>(cachedKey ?? null);
const [items, setItems] = useState<LbsPlaceItem[]>([]);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [pending, setPending] = useState<TencentPickedLocation | null>(null); const [pending, setPending] = useState<TencentPickedLocation | null>(null);
const [hint, setHint] = useState('输入地点名称搜索');
const seqRef = useRef(0);
useEffect(() => { useEffect(() => {
if (!open) { if (!open) {
setKeyword('');
setItems([]);
setPending(null); setPending(null);
setHint('输入地点名称搜索');
return; return;
} }
const lat = latitude != null ? Number(latitude) : NaN; let cancelled = false;
const lng = longitude != null ? Number(longitude) : NaN; setError('');
if (Number.isFinite(lat) && Number.isFinite(lng) && !(lat === 0 && lng === 0)) { if (key) return;
void loadNearby(lat, lng); setLoading(true);
void loadTencentLbsKey()
.then((k) => {
if (!cancelled) setKey(k);
})
.catch((e) => {
if (!cancelled) setError(e instanceof Error ? e.message : '加载地图配置失败');
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
};
}, [open, key]);
useEffect(() => {
if (!open) return;
function onMessage(event: MessageEvent) {
const picked = parseTencentLocPickerMessage(event.data);
if (!picked) return;
setPending(picked);
} }
// eslint-disable-next-line react-hooks/exhaustive-deps window.addEventListener('message', onMessage);
return () => window.removeEventListener('message', onMessage);
}, [open]); }, [open]);
async function loadNearby(lat: number, lng: number) { const src = useMemo(() => {
const seq = ++seqRef.current; if (!key) return '';
setLoading(true); const lat = latitude != null ? Number(latitude) : undefined;
setHint('正在加载附近地点…'); const lng = longitude != null ? Number(longitude) : undefined;
try { return buildTencentLocPickerUrl(key, {
const res = await request<{ items: LbsPlaceItem[] }>( latitude: lat != null && Number.isFinite(lat) ? lat : undefined,
'PARTNER_H5', longitude: lng != null && Number.isFinite(lng) ? lng : undefined,
`/common/lbs/nearby?lat=${encodeURIComponent(String(lat))}&lng=${encodeURIComponent(String(lng))}`, });
{ silent: true }, }, [key, latitude, longitude]);
);
if (seq !== seqRef.current) return;
setItems(res.items ?? []);
setHint(res.items?.length ? `附近 ${res.items.length} 个地点` : '附近暂无地点,请搜索');
} catch (e) {
if (seq !== seqRef.current) return;
setItems([]);
setHint(e instanceof Error ? e.message : '加载附近地点失败');
} finally {
if (seq === seqRef.current) setLoading(false);
}
}
async function runSearch() {
const trimmed = keyword.trim();
if (!trimmed) {
setHint('请输入搜索关键词');
return;
}
const seq = ++seqRef.current;
setLoading(true);
setHint('搜索中…');
try {
const params = new URLSearchParams({ keyword: trimmed });
if (region?.trim()) params.set('region', region.trim());
const lat = latitude != null ? Number(latitude) : NaN;
const lng = longitude != null ? Number(longitude) : NaN;
if (Number.isFinite(lat) && Number.isFinite(lng)) {
params.set('lat', String(lat));
params.set('lng', String(lng));
}
const res = await request<{ items: LbsPlaceItem[] }>(
'PARTNER_H5',
`/common/lbs/suggest?${params.toString()}`,
{ silent: true },
);
if (seq !== seqRef.current) return;
setItems(res.items ?? []);
setHint(res.items?.length ? `找到 ${res.items.length} 个结果` : '无匹配结果');
} catch (e) {
if (seq !== seqRef.current) return;
setItems([]);
setHint(e instanceof Error ? e.message : '搜索失败');
} finally {
if (seq === seqRef.current) setLoading(false);
}
}
function useBrowserLocation() {
if (!navigator.geolocation) {
setHint('当前浏览器不支持定位');
return;
}
setLoading(true);
navigator.geolocation.getCurrentPosition(
(pos) => {
const lat = pos.coords.latitude;
const lng = pos.coords.longitude;
setPending({ latitude: lat, longitude: lng, name: '当前位置' });
void loadNearby(lat, lng);
},
() => {
setLoading(false);
setHint('定位失败,请检查定位权限');
},
{ enableHighAccuracy: true, timeout: 12000 },
);
}
if (!open) return null; if (!open) return null;
@@ -151,7 +114,6 @@ export default function TencentLocPickerOverlay({
padding: '12px 16px', padding: '12px 16px',
borderBottom: '1px solid rgba(0,0,0,0.06)', borderBottom: '1px solid rgba(0,0,0,0.06)',
flexShrink: 0, flexShrink: 0,
gap: 8,
}} }}
> >
<button type="button" className="partner-btn-outline" style={{ padding: '6px 12px' }} onClick={onClose}> <button type="button" className="partner-btn-outline" style={{ padding: '6px 12px' }} onClick={onClose}>
@@ -168,97 +130,44 @@ export default function TencentLocPickerOverlay({
</button> </button>
</div> </div>
{pending ? (
<div style={{ padding: '12px 16px', borderBottom: '1px solid rgba(0,0,0,0.04)', flexShrink: 0 }}> <p
<div style={{ display: 'flex', gap: 8 }}> className="label-md text-muted"
<input style={{
value={keyword} margin: 0,
onChange={(e) => setKeyword(e.target.value)} padding: '8px 16px',
onKeyDown={(e) => { borderBottom: '1px solid rgba(0,0,0,0.04)',
if (e.key === 'Enter') void runSearch(); flexShrink: 0,
}} }}
placeholder="输入小区 / 写字楼 / 门店名称" >
style={{ {pending.latitude.toFixed(6)}, {pending.longitude.toFixed(6)}
flex: 1, {pending.name ? ` · ${pending.name}` : ''}
padding: '10px 12px', </p>
border: '1px solid rgba(0,0,0,0.12)', ) : null}
borderRadius: 8, <div style={{ flex: 1, minHeight: 0, position: 'relative' }}>
fontSize: 14, {loading ? (
}} <p className="label-md text-muted" style={{ padding: 24, textAlign: 'center' }}>
</p>
) : error ? (
<div style={{ padding: 24 }}>
<p className="label-md" style={{ color: 'var(--color-heritage-red, #a61d24)' }}>
{error}
</p>
<p className="label-md text-muted" style={{ marginTop: 12 }}>
Key WebServiceAPI
apis.map.qq.com
</p>
</div>
) : src ? (
<iframe
title="腾讯地图选点"
src={src}
allow="geolocation *"
style={{ width: '100%', height: '100%', border: 0, display: 'block' }}
/> />
<button
type="button"
className="partner-btn-primary"
style={{ width: 'auto', padding: '8px 14px' }}
disabled={loading}
onClick={() => void runSearch()}
>
</button>
</div>
<div style={{ display: 'flex', gap: 8, marginTop: 8, alignItems: 'center' }}>
<button
type="button"
className="partner-btn-outline"
style={{ padding: '6px 12px' }}
disabled={loading}
onClick={useBrowserLocation}
>
</button>
<span className="label-md text-muted">{hint}</span>
</div>
{pending ? (
<p className="label-md text-muted" style={{ margin: '8px 0 0' }}>
{pending.latitude.toFixed(6)}, {pending.longitude.toFixed(6)}
{pending.name ? ` · ${pending.name}` : ''}
</p>
) : null} ) : null}
</div> </div>
<div style={{ flex: 1, minHeight: 0, overflow: 'auto', WebkitOverflowScrolling: 'touch' }}>
{loading && !items.length ? (
<p className="label-md text-muted" style={{ padding: 24, textAlign: 'center' }}>
</p>
) : items.length ? (
<ul style={{ listStyle: 'none', margin: 0, padding: 0 }}>
{items.map((item) => {
const active =
pending?.latitude === item.latitude && pending?.longitude === item.longitude;
return (
<li key={`${item.id}-${item.latitude}-${item.longitude}`}>
<button
type="button"
onClick={() => setPending(placeToPicked(item))}
style={{
width: '100%',
textAlign: 'left',
padding: '12px 16px',
border: 0,
borderBottom: '1px solid rgba(0,0,0,0.06)',
background: active ? 'rgba(166, 29, 36, 0.06)' : '#fff',
cursor: 'pointer',
}}
>
<div style={{ fontWeight: 600, fontSize: 15 }}>{item.title}</div>
<div className="label-md text-muted" style={{ marginTop: 4 }}>
{item.address}
</div>
<div className="label-md text-muted" style={{ marginTop: 2, fontSize: 12 }}>
{item.latitude.toFixed(6)}, {item.longitude.toFixed(6)}
</div>
</button>
</li>
);
})}
</ul>
) : (
<p className="label-md text-muted" style={{ padding: 24, textAlign: 'center' }}>
{hint}
</p>
)}
</div>
</div> </div>
); );
} }
+67 -13
View File
@@ -6,21 +6,75 @@ export type TencentPickedLocation = {
cityname?: string; cityname?: string;
}; };
export type LbsPlaceItem = { type LocPickerMessage = {
id: string; module?: string;
title: string; latlng?: { lat?: number; lng?: number };
address: string; poiaddress?: string;
latitude: number; poiname?: string;
longitude: number; cityname?: string;
city?: string;
}; };
export function placeToPicked(item: LbsPlaceItem): TencentPickedLocation { const REFERER = 'dukang';
function coerceMessageData(data: unknown): LocPickerMessage | null {
if (data == null) return null;
if (typeof data === 'string') {
const trimmed = data.trim();
if (!trimmed || (trimmed[0] !== '{' && trimmed[0] !== '[')) return null;
try {
return JSON.parse(trimmed) as LocPickerMessage;
} catch {
return null;
}
}
if (typeof data === 'object') return data as LocPickerMessage;
return null;
}
export function buildTencentLocPickerUrl(
key: string,
options?: { latitude?: number; longitude?: number },
): string {
const params = new URLSearchParams({
search: '1',
type: '1',
key,
referer: REFERER,
policy: '1',
total: '20',
radius: '2000',
});
const lat = options?.latitude;
const lng = options?.longitude;
if (
lat != null &&
lng != null &&
Number.isFinite(lat) &&
Number.isFinite(lng) &&
!(lat === 0 && lng === 0)
) {
params.set('coord', `${lat},${lng}`);
params.set('coordtype', '5');
}
return `https://apis.map.qq.com/tools/locpicker?${params.toString()}`;
}
export function parseTencentLocPickerMessage(data: unknown): TencentPickedLocation | null {
const loc = coerceMessageData(data);
if (!loc || loc.module !== 'locationPicker') return null;
const lat = Number(loc.latlng?.lat);
const lng = Number(loc.latlng?.lng);
if (!Number.isFinite(lat) || !Number.isFinite(lng)) return null;
let name = loc.poiname?.trim() || undefined;
const address = loc.poiaddress?.trim() || undefined;
if (name === '我的位置' && address) name = address;
return { return {
latitude: item.latitude, latitude: lat,
longitude: item.longitude, longitude: lng,
address: item.address || undefined, address,
name: item.title || undefined, name,
cityname: item.city || undefined, cityname: loc.cityname?.trim() || undefined,
}; };
} }
+2 -29
View File
@@ -13,7 +13,7 @@ import { resolveRegionBinding } from '../lib/china-region';
import { checkStorePhoneAvailable } from '../lib/storePhone'; import { checkStorePhoneAvailable } from '../lib/storePhone';
import { formatStoreCoords, locateStorePosition } from '../lib/storeLocate'; import { formatStoreCoords } from '../lib/storeLocate';
import { fetchPartnerCities, type OpenCityOption } from '../lib/upload'; import { fetchPartnerCities, type OpenCityOption } from '../lib/upload';
@@ -101,8 +101,6 @@ export default function StoreCreatePage() {
const [categoryTree, setCategoryTree] = useState<StoreCategoryNode[]>([]); const [categoryTree, setCategoryTree] = useState<StoreCategoryNode[]>([]);
const [locating, setLocating] = useState(false);
const [mapPickerOpen, setMapPickerOpen] = useState(false); const [mapPickerOpen, setMapPickerOpen] = useState(false);
const draftSaveDisabledRef = useRef(false); const draftSaveDisabledRef = useRef(false);
@@ -662,31 +660,6 @@ export default function StoreCreatePage() {
<textarea rows={2} placeholder="请输入详细门牌号" value={form.address} onChange={(e) => patchForm({ address: e.target.value })} /> <textarea rows={2} placeholder="请输入详细门牌号" value={form.address} onChange={(e) => patchForm({ address: e.target.value })} />
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 8, flexWrap: 'wrap' }}> <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 8, flexWrap: 'wrap' }}>
<button
type="button"
className="partner-btn-outline"
style={{ padding: '8px 12px', fontSize: 13 }}
disabled={locating}
onClick={() => {
void (async () => {
setLocating(true);
try {
const pos = await locateStorePosition();
patchForm({
latitude: String(pos.latitude),
longitude: String(pos.longitude),
});
toastSuccess('已获取当前坐标');
} catch (e) {
toastError(e instanceof Error ? e.message : '定位失败');
} finally {
setLocating(false);
}
})();
}}
>
{locating ? '定位中…' : '获取当前位置'}
</button>
<button <button
type="button" type="button"
className="partner-btn-outline" className="partner-btn-outline"
@@ -698,7 +671,7 @@ export default function StoreCreatePage() {
<span className="label-md text-muted"> <span className="label-md text-muted">
{formatStoreCoords(form.latitude, form.longitude) {formatStoreCoords(form.latitude, form.longitude)
? `坐标:${formatStoreCoords(form.latitude, form.longitude)}` ? `坐标:${formatStoreCoords(form.latitude, form.longitude)}`
: '未定位(可定位或地图选点)'} : '未选点(可地图选点)'}
</span> </span>
</div> </div>
+2 -32
View File
@@ -6,7 +6,7 @@ import { toastError, toastSuccess } from '../lib/toast';
import { usePartnerSession } from '../contexts/PartnerSessionContext'; import { usePartnerSession } from '../contexts/PartnerSessionContext';
import { canManagePartnerStore } from '../lib/partnerAccess'; import { canManagePartnerStore } from '../lib/partnerAccess';
import { normalizeStringArray, patchEnvPhotoAt } from '../lib/storeDraft'; import { normalizeStringArray, patchEnvPhotoAt } from '../lib/storeDraft';
import { formatStoreCoords, locateStorePosition } from '../lib/storeLocate'; import { formatStoreCoords } from '../lib/storeLocate';
import OssUploadField from '../components/OssUploadField'; import OssUploadField from '../components/OssUploadField';
import TencentLocPickerOverlay from '../components/TencentLocPickerOverlay'; import TencentLocPickerOverlay from '../components/TencentLocPickerOverlay';
import { import {
@@ -55,7 +55,6 @@ export default function StoreDetailPage() {
const [statusSaving, setStatusSaving] = useState(false); const [statusSaving, setStatusSaving] = useState(false);
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
const [mediaSaving, setMediaSaving] = useState(false); const [mediaSaving, setMediaSaving] = useState(false);
const [locating, setLocating] = useState(false);
const [mapPickerOpen, setMapPickerOpen] = useState(false); const [mapPickerOpen, setMapPickerOpen] = useState(false);
const [actionError, setActionError] = useState(''); const [actionError, setActionError] = useState('');
const [closeConfirmOpen, setCloseConfirmOpen] = useState(false); const [closeConfirmOpen, setCloseConfirmOpen] = useState(false);
@@ -346,35 +345,6 @@ export default function StoreDetailPage() {
<textarea disabled={readOnly} rows={2} value={form.address} onChange={(e) => setForm({ ...form, address: e.target.value })} /> <textarea disabled={readOnly} rows={2} value={form.address} onChange={(e) => setForm({ ...form, address: e.target.value })} />
{!readOnly ? ( {!readOnly ? (
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 8, flexWrap: 'wrap' }}> <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 8, flexWrap: 'wrap' }}>
<button
type="button"
className="partner-btn-outline"
style={{ padding: '8px 12px', fontSize: 13 }}
disabled={locating}
onClick={() => {
void (async () => {
setLocating(true);
setActionError('');
try {
const pos = await locateStorePosition();
setForm((prev) => ({
...prev,
latitude: String(pos.latitude),
longitude: String(pos.longitude),
}));
toastSuccess('已获取当前坐标');
} catch (e) {
const msg = e instanceof Error ? e.message : '定位失败';
setActionError(msg);
toastError(msg);
} finally {
setLocating(false);
}
})();
}}
>
{locating ? '定位中…' : '获取当前位置'}
</button>
<button <button
type="button" type="button"
className="partner-btn-outline" className="partner-btn-outline"
@@ -386,7 +356,7 @@ export default function StoreDetailPage() {
<span className="label-md text-muted"> <span className="label-md text-muted">
{formatStoreCoords(form.latitude, form.longitude) {formatStoreCoords(form.latitude, form.longitude)
? `坐标:${formatStoreCoords(form.latitude, form.longitude)}` ? `坐标:${formatStoreCoords(form.latitude, form.longitude)}`
: '未定位'} : '未选点'}
</span> </span>
</div> </div>
) : formatStoreCoords(form.latitude, form.longitude) ? ( ) : formatStoreCoords(form.latitude, form.longitude) ? (
@@ -17,7 +17,7 @@ export class ClientConfigController {
mockSms: cfg.mockSms, mockSms: cfg.mockSms,
mockWechat: cfg.mockWechat, mockWechat: cfg.mockWechat,
wxAuthorize: cfg.wxAuthorize, wxAuthorize: cfg.wxAuthorize,
/** 可选暴露;选点已改为服务端 /common/lbs,前端可不依赖此字段 */ /** 合伙人 H5 腾讯地图 locpicker iframe 选点 */
tencentLbsKey: cfg.tencentLbsKey || undefined, tencentLbsKey: cfg.tencentLbsKey || undefined,
miniHome: { miniHome: {
banners: parseMiniHomeBanners(env.MINI_HOME_BANNERS), banners: parseMiniHomeBanners(env.MINI_HOME_BANNERS),