fix(stats): calculate mileage without previous-day baseline
This commit is contained in:
@@ -273,17 +273,14 @@ WHERE vin = ? AND stat_date = ? AND protocol = ?
|
||||
type sourceBaseline struct {
|
||||
LatestTotalKM float64
|
||||
LatestEventTime time.Time
|
||||
QualityReason string
|
||||
}
|
||||
|
||||
func lookupPreviousSourceBaseline(ctx context.Context, query Queryer, vin string, statDate string, protocol envelope.Protocol, sourceKey string) (sourceBaseline, bool, error) {
|
||||
if query == nil || strings.TrimSpace(vin) == "" || strings.TrimSpace(statDate) == "" || strings.TrimSpace(sourceKey) == "" {
|
||||
return sourceBaseline{}, false, nil
|
||||
}
|
||||
previousDate, ok := previousStatDate(statDate)
|
||||
if !ok {
|
||||
return sourceBaseline{}, false, nil
|
||||
}
|
||||
rows, err := query.QueryContext(ctx, previousSourceBaselineSQL, vin, previousDate, string(protocol), sourceKey)
|
||||
rows, err := query.QueryContext(ctx, previousSourceBaselineSQL, vin, statDate, string(protocol), sourceKey)
|
||||
if err != nil {
|
||||
return sourceBaseline{}, false, err
|
||||
}
|
||||
@@ -305,6 +302,7 @@ func lookupPreviousSourceBaseline(ctx context.Context, query Queryer, vin string
|
||||
return sourceBaseline{
|
||||
LatestTotalKM: latestTotal.Float64,
|
||||
LatestEventTime: latestEvent.Time,
|
||||
QualityReason: "historical_source_baseline",
|
||||
}, latestTotal.Valid, nil
|
||||
}
|
||||
|
||||
@@ -334,25 +332,19 @@ func lookupCurrentSourceBaseline(ctx context.Context, query Queryer, vin string,
|
||||
return sourceBaseline{
|
||||
LatestTotalKM: firstTotal.Float64,
|
||||
LatestEventTime: firstEvent.Time,
|
||||
QualityReason: "current_day_first_sample",
|
||||
}, firstTotal.Valid, nil
|
||||
}
|
||||
|
||||
func previousStatDate(statDate string) (string, bool) {
|
||||
day, err := time.Parse("2006-01-02", strings.TrimSpace(statDate))
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
return day.AddDate(0, 0, -1).Format("2006-01-02"), true
|
||||
}
|
||||
|
||||
const previousSourceBaselineSQL = `
|
||||
SELECT latest_total_mileage_km, latest_event_time
|
||||
FROM vehicle_daily_mileage_source
|
||||
WHERE vin = ?
|
||||
AND stat_date = ?
|
||||
AND stat_date < ?
|
||||
AND protocol = ?
|
||||
AND source_key = ?
|
||||
ORDER BY latest_event_time DESC
|
||||
AND quality_status = '` + QualityOK + `'
|
||||
ORDER BY stat_date DESC, latest_event_time DESC
|
||||
LIMIT 1
|
||||
`
|
||||
|
||||
|
||||
Reference in New Issue
Block a user