package openplatform import ( "context" "fmt" "math" "sort" "strings" "time" ) // ReconciledMileageRange uses terminal odometers, including one preceding // observation per protocol. The same function serves single days and every // range page: neither the requested start date nor page size changes a result. func (r *MySQLRepository) ReconciledMileageRange(ctx context.Context, vins []string, start, end string, protocols []string) (map[string]DailyMileage, error) { if len(vins) == 0 { return map[string]DailyMileage{}, nil } if len(protocols) == 0 { protocols = []string{"GB32960", "YUTONG_MQTT", "JT808"} } placeholders := func(n int) string { return strings.TrimRight(strings.Repeat("?,", n), ",") } // Unknown-protocol legacy imports and GPS distance are not terminal odometers. eligible := func(alias string) string { return fmt.Sprintf(`%[1]s.quality_status IN ('OK','INVALID_DELTA') AND %[1]s.latest_total_mileage_km > 0 AND COALESCE(%[1]s.quality_reason,'') <> 'gps_coordinate_accumulation' AND %[1]s.source_ip NOT IN ('legacy-mysql.lingniu-prod','manual-lingniu-prod-day-mileage') AND %[1]s.latest_event_time IS NOT NULL AND %[1]s.latest_event_time < TIMESTAMP(%[1]s.stat_date)+INTERVAL 1 DAY`, alias) } filter := `vin IN (` + placeholders(len(vins)) + `) AND protocol IN (` + placeholders(len(protocols)) + `)` query := `WITH wanted AS ( SELECT DISTINCT vin,protocol,stat_date FROM vehicle_daily_mileage_source p WHERE ` + filter + ` AND stat_date BETWEEN ? AND ? AND ` + eligible("p") + ` UNION ALL SELECT vin,protocol,MAX(stat_date) AS stat_date FROM vehicle_daily_mileage_source p WHERE ` + filter + ` AND stat_date