fix(stats): elect freshest forwarding source per terminal

This commit is contained in:
lingniu
2026-07-19 17:33:53 +08:00
parent a13ee8fc30
commit 263107d47a
3 changed files with 48 additions and 4 deletions

View File

@@ -620,6 +620,32 @@ WHERE s.stat_date = ?
ORDER BY s.vin
`
// The same physical terminal can be forwarded by more than one platform.
// Preserve each forwarding source for audit, but rank the terminal as one
// evidence group: accumulated samples choose the established terminal and the
// freshest forwarding source keeps its projected mileage current.
const projectSourceIdentitySampleCountSQL = `(
SELECT COALESCE(SUM(identity_source.sample_count), 0)
FROM vehicle_daily_mileage_source identity_source
WHERE identity_source.vin = s.vin
AND identity_source.stat_date = s.stat_date
AND identity_source.protocol = s.protocol
AND identity_source.quality_status = '` + QualityOK + `'
AND COALESCE(NULLIF(TRIM(identity_source.phone), ''), NULLIF(TRIM(identity_source.device_id), ''), identity_source.source_key)
= COALESCE(NULLIF(TRIM(s.phone), ''), NULLIF(TRIM(s.device_id), ''), s.source_key)
)`
const selectedSourceIdentitySampleCountSQL = `(
SELECT COALESCE(SUM(identity_source.sample_count), 0)
FROM vehicle_daily_mileage_source identity_source
WHERE identity_source.vin = s2.vin
AND identity_source.stat_date = s2.stat_date
AND identity_source.protocol = s2.protocol
AND identity_source.quality_status = '` + QualityOK + `'
AND COALESCE(NULLIF(TRIM(identity_source.phone), ''), NULLIF(TRIM(identity_source.device_id), ''), identity_source.source_key)
= COALESCE(NULLIF(TRIM(s2.phone), ''), NULLIF(TRIM(s2.device_id), ''), s2.source_key)
)`
const projectDailyMileageSQL = `
INSERT INTO vehicle_daily_mileage
(vin, stat_date, protocol, source_id, daily_mileage_km, latest_total_mileage_km)
@@ -650,8 +676,9 @@ ORDER BY CASE COALESCE(NULLIF(NULLIF(TRIM(ds.source_kind), ''), 'UNKNOWN'), CASE
ELSE 3
END,
COALESCE(ds.trust_priority, 100000),
s.sample_count DESC,
` + projectSourceIdentitySampleCountSQL + ` DESC,
s.latest_event_time DESC,
s.sample_count DESC,
s.source_key ASC
LIMIT 1
ON DUPLICATE KEY UPDATE
@@ -689,8 +716,9 @@ LEFT JOIN (
ELSE 3
END,
COALESCE(ds.trust_priority, 100000),
s2.sample_count DESC,
` + selectedSourceIdentitySampleCountSQL + ` DESC,
s2.latest_event_time DESC,
s2.sample_count DESC,
s2.source_key ASC
LIMIT 1
) selected_source