diff --git a/server/src/routes/mobile/mobileDeliveryRoutes.ts b/server/src/routes/mobile/mobileDeliveryRoutes.ts index fcccb7e..95cb54c 100644 --- a/server/src/routes/mobile/mobileDeliveryRoutes.ts +++ b/server/src/routes/mobile/mobileDeliveryRoutes.ts @@ -26,8 +26,6 @@ import { getDeliveryTrack, loadDriverRoutePlan, planDriverOpenTasks, - reorderOpenStopsFromPoint, - replanOnLocationDeviation, } from '../../services/deliveryRoutingService'; import { markDeliveryGeofenceEntered, @@ -249,7 +247,7 @@ router.post('/delivery/location', authMiddleware, async (req: AuthRequest, res: [taskCode, personCode] ); } - replanOnLocationDeviation({ taskCode, lat, lng, ctx: null }).catch(() => undefined); + // 2026-10-29:定位只用于展示/进圈,不再按当前位置重排计划路线。 } return res.json({ success: true }); @@ -650,9 +648,7 @@ router.post('/delivery/stop', authMiddleware, async (req: AuthRequest, res: Resp accuracy: stopAccuracy, }).catch(() => null); } - reorderOpenStopsFromPoint(personCode, parseRequestLatLng(req.body), taskCode).catch( - () => undefined - ); + // 2026-10-29:结束后不再按当前位置就近重排剩余站,路线只按仓库起点规划一次。 return res.json({ success: true }); } catch (error: any) { return res.status(error?.status || 500).json({ error: error?.code || 'server_error', error_description: error?.message || '结束配送失败' }); diff --git a/server/src/services/deliveryRoutingService.ts b/server/src/services/deliveryRoutingService.ts index fadc681..a23ca47 100644 --- a/server/src/services/deliveryRoutingService.ts +++ b/server/src/services/deliveryRoutingService.ts @@ -308,9 +308,7 @@ async function resolveOrigin( personCode?: string | null, originOverride?: LatLng | null ): Promise { - if (originOverride && isValidLatLng(originOverride)) return originOverride; - const depart = await loadTodayDepartOrigin(personCode); - if (depart) return depart; + // 2026-10-29:路线只按仓库起点规划一次;仓库地址可用时不使用当前位置/发车 GPS。 if (branchCode) { try { const br = await pool.query( @@ -327,6 +325,9 @@ async function resolveOrigin( /* ignore */ } } + const depart = await loadTodayDepartOrigin(personCode); + if (depart) return depart; + if (originOverride && isValidLatLng(originOverride)) return originOverride; return firstStop; } diff --git a/server/src/services/geoProvider.ts b/server/src/services/geoProvider.ts index 15b3653..401e6f9 100644 --- a/server/src/services/geoProvider.ts +++ b/server/src/services/geoProvider.ts @@ -180,6 +180,12 @@ function explainTencentStatus( /** * 腾讯位置服务:地理编码 + 驾车路径;失败回退直线距离。 */ +/** 是否允许调用腾讯「驾车路线规划」;默认关闭,仅显式 1/true/yes/on 开启。 */ +export function isTencentDirectionEnabled(): boolean { + const raw = String(process.env.TENCENT_MAP_DIRECTION_ENABLED ?? '').trim().toLowerCase(); + return ['1', 'true', 'yes', 'on'].includes(raw); +} + export class TencentMapGeoProvider implements GeoProvider { readonly name = 'tencent'; private key: string; @@ -248,7 +254,9 @@ export class TencentMapGeoProvider implements GeoProvider { } async estimateLegsFromCoords(points: LatLng[]): Promise { - if (points.length < 2 || !this.key) { + // 关闭驾车路线规划时直接走直线估算,不请求 /ws/direction/v1/driving; + // 地址解析(geocoder)不受影响。 + if (points.length < 2 || !this.key || !isTencentDirectionEnabled()) { return this.fallback.estimateLegsFromCoords(points); } const legs: GeoRouteLeg[] = []; diff --git a/server/tests/deliveryPlanOnDepart.test.ts b/server/tests/deliveryPlanOnDepart.test.ts index 4f474c1..7f8e3f3 100644 --- a/server/tests/deliveryPlanOnDepart.test.ts +++ b/server/tests/deliveryPlanOnDepart.test.ts @@ -52,15 +52,11 @@ describe('发车首枪规划 + 完成后就近', () => { expect(batchFn.slice(Math.max(0, planIdx - 12), planIdx)).not.toContain('await '); }); - it('结束配送成功后异步就近重排,不 await、失败不拦', () => { + it('结束配送不再按当前位置就近重排剩余站', () => { const stopFn = route.slice(route.indexOf("router.post('/delivery/stop'")); const finalizeIdx = stopFn.indexOf('finalizeOrderFulfillment'); - const reorderIdx = stopFn.indexOf('reorderOpenStopsFromPoint(personCode, parseRequestLatLng(req.body), taskCode)'); - expect(reorderIdx).toBeGreaterThan(finalizeIdx); - expect(stopFn.slice(Math.max(0, reorderIdx - 12), reorderIdx)).not.toContain('await '); - expect(stopFn.slice(reorderIdx, reorderIdx + 160)).toContain('.catch('); - const jsonIdx = stopFn.indexOf('return res.json({ success: true })', reorderIdx); - expect(jsonIdx).toBeGreaterThan(reorderIdx); + expect(finalizeIdx).toBeGreaterThan(-1); + expect(stopFn).not.toContain('reorderOpenStopsFromPoint'); }); it('完成后合并快照:已完成在前,就近未完成接在后', () => { @@ -78,14 +74,25 @@ describe('发车首枪规划 + 完成后就近', () => { expect(merged[1].is_completed).toBe(false); }); - it('偏离触发后就近重排剩余站,不腾讯整车含 30', () => { - const start = routing.indexOf('export async function replanOnLocationDeviation'); - const next = routing.indexOf('export async function', start + 10); + it('出发点取仓库:分公司地址优先于当日原点 / 当次发车 GPS', () => { + const start = routing.indexOf('async function resolveOrigin('); + const next = routing.indexOf('\n}\n', start); const fn = routing.slice(start, next > start ? next : undefined); - expect(fn).toContain('last_route_plan'); - expect(fn).toContain('reorderOpenStopsFromPoint'); - expect(fn).not.toContain('planDeliveryRoute'); - expect(fn).not.toMatch(/IN \(10, 20, 30\)/); + const branchIdx = fn.indexOf('FROM branches'); + const departIdx = fn.indexOf('loadTodayDepartOrigin'); + const overrideIdx = fn.indexOf('originOverride && isValidLatLng(originOverride)'); + expect(branchIdx).toBeGreaterThan(-1); + expect(departIdx).toBeGreaterThan(branchIdx); + expect(overrideIdx).toBeGreaterThan(branchIdx); + }); + + it('定位上报不再按当前位置重算路线', () => { + const locFn = route.slice( + route.indexOf("router.post('/delivery/location'"), + route.indexOf("router.get('/delivery/track/:taskCode'") + ); + expect(locFn).toContain('markDeliveryGeofenceEntered'); + expect(locFn).not.toContain('replanOnLocationDeviation'); }); it('下一站:进圈优先,否则未完成里 sequence 最小(含待发 10)', () => { diff --git a/server/tests/geoProviderDirectionSwitch.test.ts b/server/tests/geoProviderDirectionSwitch.test.ts new file mode 100644 index 0000000..8a816b0 --- /dev/null +++ b/server/tests/geoProviderDirectionSwitch.test.ts @@ -0,0 +1,101 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { + HeuristicGeoProvider, + TencentMapGeoProvider, + isTencentDirectionEnabled, +} from '../src/services/geoProvider'; + +/** + * 2026-10-26 用户要求:「只需要关闭路线规划 而不是地址解析」+「直接是默认关闭的状态」。 + * + * 目标: + * · **默认(不设变量)就不请求** /ws/direction/v1/driving;里程/ETA 退回直线估算 + * · 仅显式 `TENCENT_MAP_DIRECTION_ENABLED=1` 才开启腾讯驾车 + * · **地理编码 /ws/geocoder/v1 必须始终工作**(关的是路线规划,不是地址解析) + */ +const KEY = 'AAAAAAAA-BBBBBB-CCCCCC-DDDDDD-EEEEEE-FFFFF'; +const SK = 'test-sk'; + +function coords() { + return [ + { lat: 29.34, lng: 104.77 }, // 自贡出发 + { lat: 29.35, lng: 104.78 }, + ]; +} + +describe('腾讯地图:路线规划默认关闭、地址解析保留', () => { + const envBackup = { ...process.env }; + + beforeEach(() => { + delete process.env.TENCENT_MAP_DIRECTION_ENABLED; + }); + + afterEach(() => { + process.env = { ...envBackup }; + vi.restoreAllMocks(); + vi.unstubAllGlobals(); + }); + + it('isTencentDirectionEnabled:不设=关闭;仅 1/true/yes/on 开启', () => { + expect(isTencentDirectionEnabled()).toBe(false); // 默认关闭 + for (const v of ['0', 'false', 'no', 'off', '', 'disabled']) { + process.env.TENCENT_MAP_DIRECTION_ENABLED = v; + expect(isTencentDirectionEnabled(), `值 ${JSON.stringify(v)} 应视为关闭`).toBe(false); + } + for (const v of ['1', 'true', 'yes', 'on', ' TRUE ']) { + process.env.TENCENT_MAP_DIRECTION_ENABLED = v; + expect(isTencentDirectionEnabled(), `值 ${v} 应视为开启`).toBe(true); + } + }); + + it('默认关闭:不发 direction 请求,返回直线估算(estimated=true)', async () => { + const fetchSpy = vi.fn(); + vi.stubGlobal('fetch', fetchSpy); + + const provider = new TencentMapGeoProvider(KEY, SK); + const legs = await provider.estimateLegsFromCoords(coords()); + + expect(fetchSpy).not.toHaveBeenCalled(); + expect(legs).toHaveLength(1); + expect(legs[0].estimated).toBe(true); + expect(legs[0].distance_km).toBeGreaterThan(0); + + const expected = await new HeuristicGeoProvider().estimateLegsFromCoords(coords()); + expect(legs).toEqual(expected); + }); + + it('默认关闭:地址解析(geocoder)仍然发起请求并成功返回坐标', async () => { + const fetchSpy = vi.fn(async (url: string) => { + expect(String(url)).toContain('/ws/geocoder/v1'); + return { + headers: { get: () => null }, + json: async () => ({ status: 0, result: { location: { lat: 29.3401, lng: 104.7702 } } }), + } as any; + }); + vi.stubGlobal('fetch', fetchSpy); + + const provider = new TencentMapGeoProvider(KEY, SK); + const loc = await provider.geocodeAddress('四川省自贡市大安区某路1号'); + + expect(fetchSpy).toHaveBeenCalledTimes(1); + expect(loc).toEqual({ lat: 29.3401, lng: 104.7702 }); + }); + + it('显式开启(=1)时才调用腾讯驾车接口', async () => { + process.env.TENCENT_MAP_DIRECTION_ENABLED = '1'; + const fetchSpy = vi.fn(async (url: string) => { + expect(String(url)).toContain('/ws/direction/v1/driving'); + return { + headers: { get: () => null }, + json: async () => ({ status: 0, result: { routes: [{ distance: 1200, duration: 4 }] } }), + } as any; + }); + vi.stubGlobal('fetch', fetchSpy); + + const provider = new TencentMapGeoProvider(KEY, SK); + const legs = await provider.estimateLegsFromCoords(coords()); + + expect(fetchSpy).toHaveBeenCalledTimes(1); + expect(legs[0]).toEqual({ distance_km: 1.2, duration_minutes: 4, estimated: false }); + }); +});