feat(lbs): 大神真实 5km 即时匹配与接单心跳

- companions 新增 latitude/longitude/last_active_at 与 idx_comp_active;切换接单中立即刷新活跃时间

- 新增 /api/companions/heartbeat(鉴权)与 /api/companions/match(真实注册+审核通过+接单中+10分钟心跳,Haversine 5km 过滤与距离排序,不返回精确坐标)

- 工作台/接单大厅/雷达前台每 60s 心跳,离开停止;首页即时匹配改为服务端 LBS 匹配并展示真实距离

- 线上实测:2010 匹配排除自己,仅命中 280m 的 8 号;匿名命中 9 号 10m、8 号 280m;北京 5km 为 0;118 套件/771 用例全绿
这个提交包含在:
xcbyy
2026-10-22 18:44:02 +08:00
父节点 b573c1ed05
当前提交 001f81eaca
共有 11 个文件被更改,包括 425 次插入 和 19 次删除

查看文件

@@ -115,6 +115,9 @@ export async function initDatabase(): Promise<void> {
audit_status VARCHAR(32) DEFAULT '已通过',
id_card_masked VARCHAR(32),
tags JSON,
latitude DECIMAL(10,7) DEFAULT NULL,
longitude DECIMAL(10,7) DEFAULT NULL,
last_active_at DATETIME DEFAULT NULL,
apply_time DATETIME DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
`);
@@ -132,6 +135,15 @@ export async function initDatabase(): Promise<void> {
try {
await conn.query("ALTER TABLE companions ADD COLUMN voice_intro_url VARCHAR(255) NOT NULL DEFAULT '' AFTER voice_title");
} catch (_) {}
try {
await conn.query('ALTER TABLE companions ADD COLUMN latitude DECIMAL(10,7) DEFAULT NULL AFTER tags');
} catch (_) {}
try {
await conn.query('ALTER TABLE companions ADD COLUMN longitude DECIMAL(10,7) DEFAULT NULL AFTER latitude');
} catch (_) {}
try {
await conn.query('ALTER TABLE companions ADD COLUMN last_active_at DATETIME DEFAULT NULL AFTER longitude');
} catch (_) {}
// 4. 订单表
await conn.query(`
@@ -796,6 +808,7 @@ export async function initDatabase(): Promise<void> {
['arbitrations', 'idx_arb_order', 'order_id'],
['companions', 'idx_comp_user', 'user_id'],
['companions', 'idx_comp_status', 'status'],
['companions', 'idx_comp_active', 'status, last_active_at'],
['companions', 'idx_comp_audit', 'audit_status'],
['payment_refunds', 'idx_pr_order', 'order_id'],
];

查看文件

@@ -898,6 +898,96 @@ export class MysqlRepository {
});
}
/** 大神接单心跳:刷新最后活跃时间,并在有定位时更新最近坐标(坐标不对外返回) */
async updateCompanionHeartbeat(companionId: number, lat?: number | null, lng?: number | null): Promise<void> {
const id = Number(companionId) || 0;
if (id <= 0) return;
const nLat = Number(lat);
const nLng = Number(lng);
const hasGeo =
Number.isFinite(nLat) && Number.isFinite(nLng) &&
Math.abs(nLat) <= 90 && Math.abs(nLng) <= 180 &&
!(nLat === 0 && nLng === 0);
if (hasGeo) {
await pool.query(
'UPDATE companions SET last_active_at = NOW(), latitude = ?, longitude = ? WHERE id = ?',
[nLat, nLng, id]
);
} else {
await pool.query('UPDATE companions SET last_active_at = NOW() WHERE id = ?', [id]);
}
}
/**
* 即时匹配候选:真实注册、审核通过、当前接单中、10 分钟内有心跳。
* 传入用户坐标时按 Haversine 距离过滤 5km 并升序;不返回精确经纬度,只返回距离。
*/
async matchCompanions(opts: {
lat?: number | null;
lng?: number | null;
radiusKm?: number | null;
excludeUserId?: number;
limit?: number;
} = {}): Promise<any[]> {
const excludeUserId = Number(opts.excludeUserId) || 0;
const limit = Math.min(20, Math.max(1, Number(opts.limit) || 10));
const [rows]: any = await pool.query(`
SELECT id, user_id as userId, name, avatar, gender, age, track, rank_name as \`rank\`,
hourly_rate as hourlyRate, rating, order_count as orderCount, status,
last_active_at as lastActiveAt, latitude, longitude
FROM companions
WHERE user_id IS NOT NULL AND user_id > 0 AND user_id <> ?
AND audit_status = '已通过'
AND status = '接单中'
AND last_active_at IS NOT NULL
AND last_active_at >= DATE_SUB(NOW(), INTERVAL 10 MINUTE)
ORDER BY rating DESC, order_count DESC, id ASC
LIMIT 200
`, [excludeUserId]);
const fromLat = Number(opts.lat);
const fromLng = Number(opts.lng);
const hasFrom =
Number.isFinite(fromLat) && Number.isFinite(fromLng) &&
Math.abs(fromLat) <= 90 && Math.abs(fromLng) <= 180 &&
!(fromLat === 0 && fromLng === 0);
const radius = Math.min(50, Math.max(1, Number(opts.radiusKm) || 5));
const list = (rows || [])
.map((r: any) => {
const lat = r.latitude === null || r.latitude === undefined ? null : Number(r.latitude);
const lng = r.longitude === null || r.longitude === undefined ? null : Number(r.longitude);
const hasGeo = lat !== null && lng !== null && Number.isFinite(lat) && Number.isFinite(lng);
const distanceKm = hasFrom && hasGeo ? haversineKm(fromLat, fromLng, lat as number, lng as number) : null;
return {
id: String(r.id),
userId: Number(r.userId) || 0,
nickname: r.name || '',
avatar: r.avatar || '',
gender: r.gender || '',
age: Number(r.age) || 0,
track: r.track || '',
rankTag: r.rank || '',
price: Number(r.hourlyRate) || 0,
rating: Number(r.rating) || 0,
orderCount: Number(r.orderCount) || 0,
isOnline: true,
lastActiveAt: r.lastActiveAt,
distanceKm: distanceKm === null ? null : Number(distanceKm.toFixed(3)),
distanceText: distanceKm === null ? '同城' : formatDistanceText(distanceKm),
};
})
.filter((r: any) => (hasFrom ? r.distanceKm !== null && r.distanceKm <= radius : true));
list.sort((a: any, b: any) => {
if (a.distanceKm !== null && b.distanceKm !== null) return a.distanceKm - b.distanceKm;
if (a.distanceKm !== null) return -1;
if (b.distanceKm !== null) return 1;
return (b.rating - a.rating) || (b.orderCount - a.orderCount);
});
return list.slice(0, limit);
}
async getCompanionById(id: number | string): Promise<any> {
let c = await this.resolveCompanionRow(id);
// 是否为"非真实大神档案"的合成资料(用于对其隐藏虚构评分/价格/服务等)
@@ -1082,6 +1172,10 @@ export class MysqlRepository {
if (data.status !== undefined) {
fields.push('status = ?');
values.push(data.status);
// 切换为接单中时立即刷新活跃时间,避免必须等下一次心跳才进入匹配池
if (data.status === '接单中') {
fields.push('last_active_at = NOW()');
}
}
if (fields.length > 0) {