refactor(stage11): 两个热力图拆出 repository,并补契约测试
vehicle-heatmap
- 拆为 routes.ts / repository.ts(model.ts 原已存在),改为 registerVehicleHeatmapRoutes(app, deps)。
- 该域同时访问两个库,因此依赖分成 MysqlDatabase(execute,考核批次→车牌)与
PgDatabase(query 返回 { rows },定位点),两者返回形状不同,不做统一抽象。
- 保留 $4 的原语义:是否"选择了考核批次"(而非"车牌集合是否为空");
批次无车牌时由调用方提前返回,与原实现一致。
- 保留 loadBatchModelPlates 的降级行为(查询失败→空映射)与"命中缓存不查主库"。
hydrogen-heatmap
- 拆为 routes.ts / repository.ts,改为 registerHydrogenHeatmapRoutes(app, deps)。
- VALID_COORDINATE(含西藏排除)与 buildWhere 移入 repository 并导出:
它被 meta 的统计口径复用,散落两处极易漂移。
- 5 条 SQL 由脚本从原文件按顺序抽取后原样落位,避免手工转写长 SQL 出错。
契约测试(新增 19 个用例)
- 逐条断言 SQL 文本(规范化空格)与参数顺序:分页/白名单/批次车牌数组/
WHERE 片段顺序/IN 占位符拼接/半径内无站点时不发第二条查询。
- buildWhere 直接单测片段与参数顺序。
- 架构守护的"已完整分层"清单扩到 5 个域。
等价性验证(关键)
- 把两个文件改造前的实现从 git 取出,与改造后跑同一批请求,对比落库 SQL、参数、
HTTP 状态与响应体:
vehicle-heatmap :8 个场景完全一致(含批次路径、"未知批次"提前返回、错误分支)
hydrogen-heatmap :8 个场景完全一致(含筛选组合、无权限 403、错误分支)
期间的修正:曾为 /meta 的空结果新增 503 分支,属于原实现没有的行为变更,已回退为原样。
lint / test(181) / build 全绿,可达性 0 未引用文件。
This commit is contained in:
@@ -0,0 +1,142 @@
|
||||
import type { VehicleHeatmapRecord } from './model.js';
|
||||
|
||||
/**
|
||||
* 车辆热力图的数据访问。
|
||||
*
|
||||
* 该域同时使用两个库:主业务库(MySQL,考核批次 → 车牌映射)与车辆位置库
|
||||
* (PostgreSQL 只读,定位点)。两者的 query 返回形状不同,因此分别声明依赖,
|
||||
* 并由 routes.test.ts 的契约测试锁定 SQL 与参数。
|
||||
*/
|
||||
|
||||
/** MySQL 连接:只声明用到的能力。 */
|
||||
export interface MysqlDatabase {
|
||||
execute<T = any>(sql: string, values?: any[]): Promise<[T, ...any[]]>;
|
||||
}
|
||||
|
||||
/** PostgreSQL 连接:pg 的返回形状是 { rows }。 */
|
||||
export interface PgDatabase {
|
||||
query<T = any>(sql: string, values?: any[]): Promise<{ rows: T[] }>;
|
||||
}
|
||||
|
||||
export type MetaRow = {
|
||||
start_date: string;
|
||||
end_date: string;
|
||||
location_count: string;
|
||||
vehicle_count: string;
|
||||
day_count: string;
|
||||
total_location_count: string;
|
||||
excluded_location_count: string;
|
||||
outside_mainland_count: string;
|
||||
tibet_count: string;
|
||||
};
|
||||
|
||||
export type VehicleOptionRow = {
|
||||
vin: string;
|
||||
plate_number: string;
|
||||
};
|
||||
|
||||
type RecordRow = {
|
||||
date: string;
|
||||
vin: string;
|
||||
plate: string;
|
||||
time: string;
|
||||
longitude: number;
|
||||
latitude: number;
|
||||
source: string;
|
||||
source_record_id: string;
|
||||
};
|
||||
|
||||
type BatchModelRow = {
|
||||
target_name: string;
|
||||
plate_number: string;
|
||||
};
|
||||
|
||||
/** 考核批次 → 车牌集合。 */
|
||||
export async function loadBatchModelPlates(mysql: MysqlDatabase): Promise<Map<string, Set<string>>> {
|
||||
const [rows] = await mysql.execute(`
|
||||
select t.target_name, v.plate_number
|
||||
from lingniu_prod.tab_mileage_assessment_target t
|
||||
join lingniu_prod.tab_mileage_assessment_vehicle v
|
||||
on v.target_id = t.id and v.is_deleted = 0
|
||||
where t.is_deleted = 0
|
||||
`) as [BatchModelRow[], unknown];
|
||||
const result = new Map<string, Set<string>>();
|
||||
for (const row of rows) {
|
||||
const plates = result.get(row.target_name) || new Set<string>();
|
||||
plates.add(row.plate_number);
|
||||
result.set(row.target_name, plates);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** 与既有实现一致:把首行直接当作 MetaRow(缺行时由调用方行为保持不变)。 */
|
||||
export async function loadMeta(pg: PgDatabase): Promise<MetaRow> {
|
||||
const metaResult = await pg.query<MetaRow>(`
|
||||
select
|
||||
to_char(min(stat_date) filter (where is_heatmap_eligible), 'YYYY-MM-DD') as start_date,
|
||||
to_char(max(stat_date) filter (where is_heatmap_eligible), 'YYYY-MM-DD') as end_date,
|
||||
count(*) filter (where is_heatmap_eligible)::text as location_count,
|
||||
count(distinct vin) filter (where is_heatmap_eligible)::text as vehicle_count,
|
||||
count(distinct stat_date) filter (where is_heatmap_eligible)::text as day_count,
|
||||
count(*)::text as total_location_count,
|
||||
count(*) filter (where not is_heatmap_eligible)::text as excluded_location_count,
|
||||
count(*) filter (where exclusion_reason = 'outside_mainland_china')::text as outside_mainland_count,
|
||||
count(*) filter (where exclusion_reason = 'tibet')::text as tibet_count
|
||||
from analytics.vehicle_daily_first_location
|
||||
`);
|
||||
return metaResult.rows[0] as MetaRow;
|
||||
}
|
||||
|
||||
export async function loadVehicleOptions(pg: PgDatabase): Promise<VehicleOptionRow[]> {
|
||||
const vehiclesResult = await pg.query<VehicleOptionRow>(`
|
||||
select distinct on (vin) vin, plate_number
|
||||
from analytics.vehicle_daily_first_location
|
||||
where is_heatmap_eligible
|
||||
order by vin, stat_date desc
|
||||
`);
|
||||
return vehiclesResult.rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* 逐车每日首个有效定位点。
|
||||
* `$4` 沿用原实现的语义——是否选择了考核批次(而不是"车牌集合是否为空"),
|
||||
* 调用方需在批次无车牌时提前返回,不要靠这里兜底。
|
||||
*/
|
||||
export async function loadRecords(
|
||||
pg: PgDatabase,
|
||||
args: { startDate: string; endDate: string; query: string; batchModelSelected: boolean; batchPlates: string[] },
|
||||
): Promise<VehicleHeatmapRecord[]> {
|
||||
const result = await pg.query<RecordRow>(`
|
||||
select
|
||||
to_char(stat_date, 'YYYY-MM-DD') as date,
|
||||
vin,
|
||||
plate_number as plate,
|
||||
to_char(first_event_time at time zone 'Asia/Shanghai',
|
||||
'YYYY-MM-DD HH24:MI:SS') as time,
|
||||
longitude,
|
||||
latitude,
|
||||
source_name as source,
|
||||
coalesce(source_record_id::text, '') as source_record_id
|
||||
from analytics.vehicle_daily_first_location
|
||||
where stat_date between $1::date and $2::date
|
||||
and is_heatmap_eligible
|
||||
and ($4::boolean = false or plate_number = any($5::text[]))
|
||||
and (
|
||||
$3 = ''
|
||||
or upper(vin) like '%' || upper($3) || '%'
|
||||
or upper(plate_number) like '%' || upper($3) || '%'
|
||||
)
|
||||
order by stat_date, vin
|
||||
`, [args.startDate, args.endDate, args.query.trim(), args.batchModelSelected, args.batchPlates]);
|
||||
|
||||
return result.rows.map((row) => ({
|
||||
date: row.date,
|
||||
vin: row.vin,
|
||||
plate: row.plate,
|
||||
time: row.time,
|
||||
longitude: Number(row.longitude),
|
||||
latitude: Number(row.latitude),
|
||||
source: row.source,
|
||||
sourceRecordId: row.source_record_id,
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import { Hono } from "hono";
|
||||
import { registerVehicleHeatmapRoutes, type VehicleHeatmapDependencies } from "./routes.js";
|
||||
import type { MysqlDatabase, PgDatabase } from "./repository.js";
|
||||
|
||||
interface Call {
|
||||
sql: string;
|
||||
params: unknown[];
|
||||
}
|
||||
|
||||
const normalize = (sql: string) => sql.replace(/\s+/g, " ").trim();
|
||||
|
||||
function createMysql(results: unknown[] = []): { db: MysqlDatabase; calls: Call[] } {
|
||||
const calls: Call[] = [];
|
||||
const queue = [...results];
|
||||
return {
|
||||
calls,
|
||||
db: {
|
||||
async execute(sql: string, params?: any[]) {
|
||||
calls.push({ sql: normalize(sql), params: (params ?? []) as unknown[] });
|
||||
return [queue.shift() ?? [], []] as never;
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function createPg(results: { rows: unknown[] }[] = []): { db: PgDatabase; calls: Call[] } {
|
||||
const calls: Call[] = [];
|
||||
const queue = [...results];
|
||||
return {
|
||||
calls,
|
||||
db: {
|
||||
async query(sql: string, params?: any[]) {
|
||||
calls.push({ sql: normalize(sql), params: (params ?? []) as unknown[] });
|
||||
return (queue.shift() ?? { rows: [] }) as never;
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function makeApp(deps: VehicleHeatmapDependencies): Hono {
|
||||
const app = new Hono();
|
||||
registerVehicleHeatmapRoutes(app, deps);
|
||||
return app;
|
||||
}
|
||||
|
||||
const META_ROW = {
|
||||
start_date: "2026-01-01",
|
||||
end_date: "2026-07-13",
|
||||
location_count: "10",
|
||||
vehicle_count: "3",
|
||||
day_count: "5",
|
||||
total_location_count: "12",
|
||||
excluded_location_count: "2",
|
||||
outside_mainland_count: "1",
|
||||
tibet_count: "1",
|
||||
};
|
||||
|
||||
const RECORD_ROW = {
|
||||
date: "2026-07-01",
|
||||
vin: "VIN1",
|
||||
plate: "粤A1",
|
||||
time: "2026-07-01 08:00:00",
|
||||
longitude: "113.1",
|
||||
latitude: "23.2",
|
||||
source: "gps",
|
||||
source_record_id: "r1",
|
||||
};
|
||||
|
||||
const EMPTY_BATCH_PLATES = [[], []];
|
||||
|
||||
test("/config:缺少高德配置时返回 503", async () => {
|
||||
const prevKey = process.env.AMAP_WEB_KEY;
|
||||
const prevCode = process.env.AMAP_SECURITY_JS_CODE;
|
||||
delete process.env.AMAP_WEB_KEY;
|
||||
delete process.env.AMAP_SECURITY_JS_CODE;
|
||||
try {
|
||||
const app = makeApp({ mysql: createMysql().db, pg: createPg().db });
|
||||
const res = await app.request("/config");
|
||||
assert.equal(res.status, 503);
|
||||
} finally {
|
||||
if (prevKey !== undefined) process.env.AMAP_WEB_KEY = prevKey;
|
||||
if (prevCode !== undefined) process.env.AMAP_SECURITY_JS_CODE = prevCode;
|
||||
}
|
||||
});
|
||||
|
||||
test("/meta:两条定位库查询与批次映射的 SQL 原样保留", async () => {
|
||||
const mysql = createMysql([[]]);
|
||||
const pg = createPg([{ rows: [META_ROW] }, { rows: [{ vin: "VIN2", plate_number: "粤B2" }] }]);
|
||||
// /meta issues: loadMeta, loadVehicleOptions (parallel) + batch plates
|
||||
const app = makeApp({ mysql: mysql.db, pg: pg.db, cachedBatchPlates: () => new Map([["B1", new Set(["粤A1"])]]) });
|
||||
|
||||
const res = await app.request("/meta");
|
||||
assert.equal(res.status, 200);
|
||||
const body = await res.json() as Record<string, unknown>;
|
||||
assert.deepEqual(body, {
|
||||
startDate: "2026-01-01",
|
||||
endDate: "2026-07-13",
|
||||
locationCount: 10,
|
||||
vehicleCount: 3,
|
||||
dayCount: 5,
|
||||
totalLocationCount: 12,
|
||||
excludedLocationCount: 2,
|
||||
outsideMainlandCount: 1,
|
||||
tibetCount: 1,
|
||||
batchModels: ["B1"],
|
||||
vehicles: [{ vin: "VIN2", plateNumber: "粤B2" }],
|
||||
});
|
||||
|
||||
assert.equal(pg.calls.length, 2);
|
||||
assert.equal(
|
||||
pg.calls[0].sql,
|
||||
"select to_char(min(stat_date) filter (where is_heatmap_eligible), 'YYYY-MM-DD') as start_date, to_char(max(stat_date) filter (where is_heatmap_eligible), 'YYYY-MM-DD') as end_date, count(*) filter (where is_heatmap_eligible)::text as location_count, count(distinct vin) filter (where is_heatmap_eligible)::text as vehicle_count, count(distinct stat_date) filter (where is_heatmap_eligible)::text as day_count, count(*)::text as total_location_count, count(*) filter (where not is_heatmap_eligible)::text as excluded_location_count, count(*) filter (where exclusion_reason = 'outside_mainland_china')::text as outside_mainland_count, count(*) filter (where exclusion_reason = 'tibet')::text as tibet_count from analytics.vehicle_daily_first_location",
|
||||
);
|
||||
assert.equal(pg.calls[1].sql.includes("select distinct on (vin) vin, plate_number"), true);
|
||||
assert.equal(mysql.calls.length, 0, "命中缓存的批次映射不应查主库");
|
||||
});
|
||||
|
||||
test("/meta:缓存缺失时查主库取批次车牌,失败按空映射降级", async () => {
|
||||
const mysql = createMysql([[{ target_name: "B1", plate_number: "粤A1" }, { target_name: "B1", plate_number: "粤A2" }]]);
|
||||
const pg = createPg([{ rows: [META_ROW] }, { rows: [] }]);
|
||||
const app = makeApp({ mysql: mysql.db, pg: pg.db });
|
||||
|
||||
const res = await app.request("/meta");
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(mysql.calls.length, 1);
|
||||
assert.equal(
|
||||
mysql.calls[0].sql,
|
||||
"select t.target_name, v.plate_number from lingniu_prod.tab_mileage_assessment_target t join lingniu_prod.tab_mileage_assessment_vehicle v on v.target_id = t.id and v.is_deleted = 0 where t.is_deleted = 0",
|
||||
);
|
||||
});
|
||||
|
||||
test("/points:日期倒置返回 400 且不查定位库", async () => {
|
||||
const mysql = createMysql();
|
||||
const pg = createPg();
|
||||
const app = makeApp({ mysql: mysql.db, pg: pg.db });
|
||||
|
||||
const res = await app.request("/points?startDate=2026-07-10&endDate=2026-07-01");
|
||||
assert.equal(res.status, 400);
|
||||
assert.equal(pg.calls.length, 0);
|
||||
});
|
||||
|
||||
test("/points:定位点查询的 $4/$5 语义与参数顺序保持不变", async () => {
|
||||
const mysql = createMysql();
|
||||
const pg = createPg([{ rows: [RECORD_ROW] }]);
|
||||
const app = makeApp({ mysql: mysql.db, pg: pg.db });
|
||||
|
||||
const res = await app.request("/points?startDate=2026-07-01&endDate=2026-07-02&query=%20VIN1%20&metric=locations");
|
||||
assert.equal(res.status, 200);
|
||||
const body = await res.json() as Record<string, unknown>;
|
||||
assert.equal(body.locationCount, 1);
|
||||
assert.equal(body.vehicleCount, 1);
|
||||
assert.equal(body.metric, "locations");
|
||||
assert.equal(Array.isArray(body.points), true);
|
||||
assert.deepEqual(body.topVehicles, [{ vin: "VIN1", plateNumber: "粤A1", locationCount: 1, firstSeen: RECORD_ROW.time, lastSeen: RECORD_ROW.time }]);
|
||||
|
||||
assert.equal(pg.calls.length, 1);
|
||||
assert.equal(pg.calls[0].sql.includes("from analytics.vehicle_daily_first_location where stat_date between $1::date and $2::date"), true);
|
||||
assert.equal(pg.calls[0].sql.includes("and ($4::boolean = false or plate_number = any($5::text[]))"), true);
|
||||
assert.deepEqual(pg.calls[0].params, ["2026-07-01", "2026-07-02", "VIN1", false, []]);
|
||||
});
|
||||
|
||||
test("/points:选择批次但批次无车牌时直接返回空,不查定位库", async () => {
|
||||
const mysql = createMysql([[]]); // batch model exists but has no plates
|
||||
const pg = createPg();
|
||||
const app = makeApp({ mysql: mysql.db, pg: pg.db });
|
||||
|
||||
const res = await app.request("/points?startDate=2026-07-01&endDate=2026-07-02&batchModel=unknown");
|
||||
assert.equal(res.status, 200);
|
||||
const body = await res.json() as Record<string, unknown>;
|
||||
assert.equal(body.locationCount, 0);
|
||||
assert.deepEqual(body.points, []);
|
||||
assert.equal(pg.calls.length, 0, "无车牌时不应查定位库");
|
||||
});
|
||||
|
||||
test("/points:选定批次时 $4=true 且 $5 为车牌数组", async () => {
|
||||
const mysql = createMysql([[]]);
|
||||
const pg = createPg([{ rows: [] }]);
|
||||
const app = makeApp({
|
||||
mysql: mysql.db,
|
||||
pg: pg.db,
|
||||
cachedBatchPlates: () => new Map([["B1", new Set(["粤A1", "粤A2"])]]),
|
||||
});
|
||||
|
||||
await app.request("/points?startDate=2026-07-01&endDate=2026-07-02&batchModel=B1");
|
||||
assert.deepEqual(pg.calls[0].params, ["2026-07-01", "2026-07-02", "", true, ["粤A1", "粤A2"]]);
|
||||
});
|
||||
|
||||
test("/nearby:非法经纬度返回 400", async () => {
|
||||
const app = makeApp({ mysql: createMysql().db, pg: createPg().db });
|
||||
const res = await app.request("/nearby?lng=abc&lat=23");
|
||||
assert.equal(res.status, 400);
|
||||
});
|
||||
|
||||
test("/nearby:半径过滤与排名口径不变", async () => {
|
||||
const pg = createPg([{ rows: [
|
||||
{ ...RECORD_ROW, longitude: "113.1", latitude: "23.2" },
|
||||
{ ...RECORD_ROW, vin: "VIN2", source_record_id: "r2", longitude: "120.0", latitude: "30.0" },
|
||||
] }]);
|
||||
const app = makeApp({ mysql: createMysql().db, pg: pg.db });
|
||||
|
||||
const res = await app.request("/nearby?lng=113.1&lat=23.2&radiusKm=5&startDate=2026-07-01&endDate=2026-07-02");
|
||||
assert.equal(res.status, 200);
|
||||
const body = await res.json() as Record<string, unknown>;
|
||||
assert.equal(body.locationCount, 1, "只保留半径内的点");
|
||||
assert.equal(body.vehicleCount, 1);
|
||||
assert.equal(body.radiusKm, 5);
|
||||
});
|
||||
|
||||
test("分层:路由文件不再直接书写 SQL", () => {
|
||||
const source = readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), "routes.ts"), "utf8");
|
||||
const offenders = source.match(/\b(select|insert into|insert ignore|update |delete from|create table|alter table)\b/gi) ?? [];
|
||||
assert.deepEqual(offenders, [], "SQL 必须留在 repository.ts(注意本域 SQL 为小写)");
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Hono } from 'hono';
|
||||
import pool from '../../db/mysql.js';
|
||||
import mysqlPool from '../../db/mysql.js';
|
||||
import heatmapPool from '../../db/heatmap.js';
|
||||
import { getCache } from '../mileage/cache.js';
|
||||
import {
|
||||
@@ -12,223 +12,158 @@ import {
|
||||
vehicleGridPrecision,
|
||||
type VehicleHeatmapRecord,
|
||||
} from './model.js';
|
||||
import {
|
||||
loadBatchModelPlates,
|
||||
loadMeta,
|
||||
loadRecords,
|
||||
loadVehicleOptions,
|
||||
type MysqlDatabase,
|
||||
type PgDatabase,
|
||||
} from './repository.js';
|
||||
|
||||
type MetaRow = {
|
||||
start_date: string;
|
||||
end_date: string;
|
||||
location_count: string;
|
||||
vehicle_count: string;
|
||||
day_count: string;
|
||||
total_location_count: string;
|
||||
excluded_location_count: string;
|
||||
outside_mainland_count: string;
|
||||
tibet_count: string;
|
||||
};
|
||||
export interface VehicleHeatmapDependencies {
|
||||
mysql: MysqlDatabase;
|
||||
pg: PgDatabase;
|
||||
/** 里程缓存里的考核批次车牌映射(可命中热缓存,避免每次查主库)。 */
|
||||
cachedBatchPlates?: () => Map<string, Set<string>> | undefined;
|
||||
}
|
||||
|
||||
type VehicleOptionRow = {
|
||||
vin: string;
|
||||
plate_number: string;
|
||||
};
|
||||
export function registerVehicleHeatmapRoutes(app: Hono, deps: VehicleHeatmapDependencies): void {
|
||||
const { mysql, pg } = deps;
|
||||
|
||||
type RecordRow = {
|
||||
date: string;
|
||||
vin: string;
|
||||
plate: string;
|
||||
time: string;
|
||||
longitude: number;
|
||||
latitude: number;
|
||||
source: string;
|
||||
source_record_id: string;
|
||||
};
|
||||
|
||||
type BatchModelRow = {
|
||||
target_name: string;
|
||||
plate_number: string;
|
||||
};
|
||||
|
||||
async function loadBatchModelPlates(): Promise<Map<string, Set<string>>> {
|
||||
const cached = getCache()?.targetPlatesMap;
|
||||
if (cached?.size) return cached;
|
||||
|
||||
try {
|
||||
const [rows] = await pool.execute(`
|
||||
select t.target_name, v.plate_number
|
||||
from lingniu_prod.tab_mileage_assessment_target t
|
||||
join lingniu_prod.tab_mileage_assessment_vehicle v
|
||||
on v.target_id = t.id and v.is_deleted = 0
|
||||
where t.is_deleted = 0
|
||||
`) as [BatchModelRow[], unknown];
|
||||
const result = new Map<string, Set<string>>();
|
||||
for (const row of rows) {
|
||||
const plates = result.get(row.target_name) || new Set<string>();
|
||||
plates.add(row.plate_number);
|
||||
result.set(row.target_name, plates);
|
||||
/**
|
||||
* 批次 → 车牌映射。优先用里程缓存;缓存缺失时查主库。
|
||||
* 查询失败按"无批次数据"降级,不影响其他筛选(与既有行为一致)。
|
||||
*/
|
||||
async function resolveBatchModelPlates(): Promise<Map<string, Set<string>>> {
|
||||
const cached = deps.cachedBatchPlates?.() ?? getCache()?.targetPlatesMap;
|
||||
if (cached?.size) return cached;
|
||||
try {
|
||||
return await loadBatchModelPlates(mysql);
|
||||
} catch (error) {
|
||||
console.error('[vehicle-heatmap] batch model lookup failed', error);
|
||||
return new Map();
|
||||
}
|
||||
return result;
|
||||
} catch (error) {
|
||||
console.error('[vehicle-heatmap] batch model lookup failed', error);
|
||||
return new Map();
|
||||
}
|
||||
|
||||
async function collectRecords(
|
||||
startDate: string,
|
||||
endDate: string,
|
||||
query: string,
|
||||
batchModel: string,
|
||||
): Promise<VehicleHeatmapRecord[]> {
|
||||
let batchPlates: string[] = [];
|
||||
if (batchModel) {
|
||||
const modelPlates = await resolveBatchModelPlates();
|
||||
batchPlates = [...(modelPlates.get(batchModel) || [])];
|
||||
if (batchPlates.length === 0) return [];
|
||||
}
|
||||
return loadRecords(pg, {
|
||||
startDate,
|
||||
endDate,
|
||||
query,
|
||||
batchModelSelected: Boolean(batchModel),
|
||||
batchPlates,
|
||||
});
|
||||
}
|
||||
|
||||
app.get('/config', (c) => {
|
||||
const key = process.env.AMAP_WEB_KEY;
|
||||
const securityCode = process.env.AMAP_SECURITY_JS_CODE;
|
||||
if (!key || !securityCode) {
|
||||
return c.json({ error: '高德地图配置缺失' }, 503);
|
||||
}
|
||||
return c.json({ key, securityCode });
|
||||
});
|
||||
|
||||
app.get('/meta', async (c) => {
|
||||
const [meta, vehicleRows, batchModelPlates] = await Promise.all([
|
||||
loadMeta(pg),
|
||||
loadVehicleOptions(pg),
|
||||
resolveBatchModelPlates(),
|
||||
]);
|
||||
const vehicles = vehicleRows
|
||||
.map(({ vin, plate_number: plateNumber }) => ({ vin, plateNumber }))
|
||||
.sort((left, right) => left.plateNumber.localeCompare(right.plateNumber, 'zh-CN'));
|
||||
return c.json({
|
||||
startDate: meta.start_date,
|
||||
endDate: meta.end_date,
|
||||
locationCount: Number(meta.location_count),
|
||||
vehicleCount: Number(meta.vehicle_count),
|
||||
dayCount: Number(meta.day_count),
|
||||
totalLocationCount: Number(meta.total_location_count),
|
||||
excludedLocationCount: Number(meta.excluded_location_count),
|
||||
outsideMainlandCount: Number(meta.outside_mainland_count),
|
||||
tibetCount: Number(meta.tibet_count),
|
||||
batchModels: [...batchModelPlates.keys()].sort((left, right) => left.localeCompare(right, 'zh-CN')),
|
||||
vehicles,
|
||||
});
|
||||
});
|
||||
|
||||
app.get('/points', async (c) => {
|
||||
const { startDate, endDate, query, batchModel, metric } = parseVehicleHeatmapQuery({
|
||||
startDate: c.req.query('startDate'),
|
||||
endDate: c.req.query('endDate'),
|
||||
query: c.req.query('query'),
|
||||
batchModel: c.req.query('batchModel'),
|
||||
metric: c.req.query('metric'),
|
||||
});
|
||||
if (startDate > endDate) return c.json({ error: '开始日期不能晚于结束日期' }, 400);
|
||||
|
||||
const records = await collectRecords(startDate, endDate, query, batchModel);
|
||||
const precision = vehicleGridPrecision(startDate, endDate, query, batchModel);
|
||||
const { points, max } = buildVehicleGrid(records, metric, precision);
|
||||
const summary = summarizeVehicleRecords(records);
|
||||
|
||||
return c.json({
|
||||
startDate,
|
||||
endDate,
|
||||
metric,
|
||||
locationCount: summary.locationCount,
|
||||
vehicleCount: summary.vehicleCount,
|
||||
dayCount: summary.dayCount,
|
||||
points,
|
||||
max,
|
||||
topVehicles: buildVehicleRanking(records),
|
||||
});
|
||||
});
|
||||
|
||||
app.get('/nearby', async (c) => {
|
||||
const { center, radiusKm } = parseNearbyQuery({
|
||||
lng: c.req.query('lng'),
|
||||
lat: c.req.query('lat'),
|
||||
radiusKm: c.req.query('radiusKm'),
|
||||
});
|
||||
if (!center) {
|
||||
return c.json({ error: '经纬度参数无效' }, 400);
|
||||
}
|
||||
|
||||
const { startDate, endDate, query, batchModel } = parseVehicleHeatmapQuery({
|
||||
startDate: c.req.query('startDate'),
|
||||
endDate: c.req.query('endDate'),
|
||||
query: c.req.query('query'),
|
||||
batchModel: c.req.query('batchModel'),
|
||||
});
|
||||
const records = await collectRecords(startDate, endDate, query, batchModel);
|
||||
const nearby = filterVehicleRecordsByRadius(records, center, radiusKm);
|
||||
const summary = summarizeVehicleRecords(nearby);
|
||||
|
||||
return c.json({
|
||||
center,
|
||||
radiusKm,
|
||||
locationCount: summary.locationCount,
|
||||
vehicleCount: summary.vehicleCount,
|
||||
topVehicles: buildVehicleRanking(nearby),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function loadRecords(
|
||||
startDate: string,
|
||||
endDate: string,
|
||||
query: string,
|
||||
batchModel: string,
|
||||
): Promise<VehicleHeatmapRecord[]> {
|
||||
let batchPlates: string[] = [];
|
||||
if (batchModel) {
|
||||
const modelPlates = await loadBatchModelPlates();
|
||||
batchPlates = [...(modelPlates.get(batchModel) || [])];
|
||||
if (batchPlates.length === 0) return [];
|
||||
}
|
||||
|
||||
const result = await heatmapPool.query<RecordRow>(`
|
||||
select
|
||||
to_char(stat_date, 'YYYY-MM-DD') as date,
|
||||
vin,
|
||||
plate_number as plate,
|
||||
to_char(first_event_time at time zone 'Asia/Shanghai',
|
||||
'YYYY-MM-DD HH24:MI:SS') as time,
|
||||
longitude,
|
||||
latitude,
|
||||
source_name as source,
|
||||
coalesce(source_record_id::text, '') as source_record_id
|
||||
from analytics.vehicle_daily_first_location
|
||||
where stat_date between $1::date and $2::date
|
||||
and is_heatmap_eligible
|
||||
and ($4::boolean = false or plate_number = any($5::text[]))
|
||||
and (
|
||||
$3 = ''
|
||||
or upper(vin) like '%' || upper($3) || '%'
|
||||
or upper(plate_number) like '%' || upper($3) || '%'
|
||||
)
|
||||
order by stat_date, vin
|
||||
`, [startDate, endDate, query.trim(), Boolean(batchModel), batchPlates]);
|
||||
|
||||
return result.rows.map((row) => ({
|
||||
...row,
|
||||
longitude: Number(row.longitude),
|
||||
latitude: Number(row.latitude),
|
||||
sourceRecordId: row.source_record_id,
|
||||
}));
|
||||
/** 生产用路由器:绑定真实连接池。 */
|
||||
export function createVehicleHeatmapRouter(): Hono {
|
||||
const app = new Hono();
|
||||
registerVehicleHeatmapRoutes(app, { mysql: mysqlPool, pg: heatmapPool });
|
||||
return app;
|
||||
}
|
||||
|
||||
const router = new Hono();
|
||||
|
||||
router.get('/config', (c) => {
|
||||
const key = process.env.AMAP_WEB_KEY;
|
||||
const securityCode = process.env.AMAP_SECURITY_JS_CODE;
|
||||
if (!key || !securityCode) {
|
||||
return c.json({ error: '高德地图配置缺失' }, 503);
|
||||
}
|
||||
return c.json({ key, securityCode });
|
||||
});
|
||||
|
||||
router.get('/meta', async (c) => {
|
||||
const [metaResult, vehiclesResult, batchModelPlates] = await Promise.all([
|
||||
heatmapPool.query<MetaRow>(`
|
||||
select
|
||||
to_char(min(stat_date) filter (where is_heatmap_eligible), 'YYYY-MM-DD') as start_date,
|
||||
to_char(max(stat_date) filter (where is_heatmap_eligible), 'YYYY-MM-DD') as end_date,
|
||||
count(*) filter (where is_heatmap_eligible)::text as location_count,
|
||||
count(distinct vin) filter (where is_heatmap_eligible)::text as vehicle_count,
|
||||
count(distinct stat_date) filter (where is_heatmap_eligible)::text as day_count,
|
||||
count(*)::text as total_location_count,
|
||||
count(*) filter (where not is_heatmap_eligible)::text as excluded_location_count,
|
||||
count(*) filter (where exclusion_reason = 'outside_mainland_china')::text as outside_mainland_count,
|
||||
count(*) filter (where exclusion_reason = 'tibet')::text as tibet_count
|
||||
from analytics.vehicle_daily_first_location
|
||||
`),
|
||||
heatmapPool.query<VehicleOptionRow>(`
|
||||
select distinct on (vin) vin, plate_number
|
||||
from analytics.vehicle_daily_first_location
|
||||
where is_heatmap_eligible
|
||||
order by vin, stat_date desc
|
||||
`),
|
||||
loadBatchModelPlates(),
|
||||
]);
|
||||
const meta = metaResult.rows[0];
|
||||
const vehicles = vehiclesResult.rows
|
||||
.map(({ vin, plate_number: plateNumber }) => ({ vin, plateNumber }))
|
||||
.sort((left, right) => left.plateNumber.localeCompare(right.plateNumber, 'zh-CN'));
|
||||
return c.json({
|
||||
startDate: meta.start_date,
|
||||
endDate: meta.end_date,
|
||||
locationCount: Number(meta.location_count),
|
||||
vehicleCount: Number(meta.vehicle_count),
|
||||
dayCount: Number(meta.day_count),
|
||||
totalLocationCount: Number(meta.total_location_count),
|
||||
excludedLocationCount: Number(meta.excluded_location_count),
|
||||
outsideMainlandCount: Number(meta.outside_mainland_count),
|
||||
tibetCount: Number(meta.tibet_count),
|
||||
batchModels: [...batchModelPlates.keys()].sort((left, right) => left.localeCompare(right, 'zh-CN')),
|
||||
vehicles,
|
||||
});
|
||||
});
|
||||
|
||||
router.get('/points', async (c) => {
|
||||
const {
|
||||
startDate,
|
||||
endDate,
|
||||
query,
|
||||
batchModel,
|
||||
metric,
|
||||
} = parseVehicleHeatmapQuery({
|
||||
startDate: c.req.query('startDate'),
|
||||
endDate: c.req.query('endDate'),
|
||||
query: c.req.query('query'),
|
||||
batchModel: c.req.query('batchModel'),
|
||||
metric: c.req.query('metric'),
|
||||
});
|
||||
if (startDate > endDate) return c.json({ error: '开始日期不能晚于结束日期' }, 400);
|
||||
|
||||
const records = await loadRecords(startDate, endDate, query, batchModel);
|
||||
const precision = vehicleGridPrecision(startDate, endDate, query, batchModel);
|
||||
const { points, max } = buildVehicleGrid(records, metric, precision);
|
||||
const summary = summarizeVehicleRecords(records);
|
||||
|
||||
return c.json({
|
||||
startDate,
|
||||
endDate,
|
||||
metric,
|
||||
locationCount: summary.locationCount,
|
||||
vehicleCount: summary.vehicleCount,
|
||||
dayCount: summary.dayCount,
|
||||
points,
|
||||
max,
|
||||
topVehicles: buildVehicleRanking(records),
|
||||
});
|
||||
});
|
||||
|
||||
router.get('/nearby', async (c) => {
|
||||
const { center, radiusKm } = parseNearbyQuery({
|
||||
lng: c.req.query('lng'),
|
||||
lat: c.req.query('lat'),
|
||||
radiusKm: c.req.query('radiusKm'),
|
||||
});
|
||||
if (!center) {
|
||||
return c.json({ error: '经纬度参数无效' }, 400);
|
||||
}
|
||||
|
||||
const { startDate, endDate, query, batchModel } = parseVehicleHeatmapQuery({
|
||||
startDate: c.req.query('startDate'),
|
||||
endDate: c.req.query('endDate'),
|
||||
query: c.req.query('query'),
|
||||
batchModel: c.req.query('batchModel'),
|
||||
});
|
||||
const records = await loadRecords(startDate, endDate, query, batchModel);
|
||||
const nearby = filterVehicleRecordsByRadius(records, center, radiusKm);
|
||||
const summary = summarizeVehicleRecords(nearby);
|
||||
|
||||
return c.json({
|
||||
center,
|
||||
radiusKm,
|
||||
locationCount: summary.locationCount,
|
||||
vehicleCount: summary.vehicleCount,
|
||||
topVehicles: buildVehicleRanking(nearby),
|
||||
});
|
||||
});
|
||||
|
||||
export default router;
|
||||
const app = createVehicleHeatmapRouter();
|
||||
export default app;
|
||||
|
||||
Reference in New Issue
Block a user