73 lines
2.5 KiB
Go
73 lines
2.5 KiB
Go
package handlers
|
|
|
|
import (
|
|
"net/http"
|
|
"sort"
|
|
"time"
|
|
)
|
|
|
|
type MileageResponse struct {
|
|
CurrentOdometer *int `json:"currentOdometer"`
|
|
KmPerYear *float64 `json:"kmPerYear"`
|
|
// YearsPer100k/Next100kEta answer "how long does it take to put another
|
|
// 100,000km on this car at my current rate" — a throughput figure, not
|
|
// tied to the odometer's current position (68,420km → 100,000km is a
|
|
// misleadingly small gap; this is always a full 100,000km from today).
|
|
YearsPer100k *float64 `json:"yearsPer100k"`
|
|
Next100kEta *string `json:"next100kEta"`
|
|
}
|
|
|
|
// milestoneDistance is the block of driving the "how long" estimate is
|
|
// measured over — a generic throughput unit, not a specific odometer target.
|
|
const milestoneDistance = 100_000
|
|
|
|
// Mileage reports the car's usage rate: an estimated km/year (derived from
|
|
// every known odometer+date pair across service and fuel entries, plus the
|
|
// car's own current reading) and how long, at that rate, it takes to add
|
|
// another 100,000km from today. Needs at least two data points to estimate
|
|
// a rate — with fewer, it just reports the current reading.
|
|
func (h *Handlers) Mileage(w http.ResponseWriter, r *http.Request) {
|
|
car, ok := h.loadOwnedCar(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
type odometerPoint struct {
|
|
EntryDate time.Time `db:"entry_date"`
|
|
Odometer int `db:"odometer"`
|
|
}
|
|
|
|
var points []odometerPoint
|
|
_ = h.dbSelect(r.Context(), &points, `
|
|
SELECT entry_date, odometer FROM service_entries WHERE car_id = ? AND odometer IS NOT NULL
|
|
UNION ALL
|
|
SELECT entry_date, odometer FROM fuel_entries WHERE car_id = ? AND odometer IS NOT NULL
|
|
`, car.ID, car.ID)
|
|
// best-effort: a query error just means we fall back to "current reading
|
|
// only" below, rather than failing the whole endpoint.
|
|
|
|
if car.Odometer != nil {
|
|
points = append(points, odometerPoint{EntryDate: today(), Odometer: *car.Odometer})
|
|
}
|
|
sort.Slice(points, func(i, j int) bool { return points[i].EntryDate.Before(points[j].EntryDate) })
|
|
|
|
resp := MileageResponse{CurrentOdometer: car.Odometer}
|
|
|
|
if len(points) >= 2 {
|
|
first, last := points[0], points[len(points)-1]
|
|
days := last.EntryDate.Sub(first.EntryDate).Hours() / 24
|
|
if days > 0 && last.Odometer > first.Odometer {
|
|
kmPerYear := float64(last.Odometer-first.Odometer) / days * 365
|
|
resp.KmPerYear = &kmPerYear
|
|
|
|
years := milestoneDistance / kmPerYear
|
|
resp.YearsPer100k = &years
|
|
|
|
eta := today().AddDate(0, 0, int(years*365)).Format(dateLayout)
|
|
resp.Next100kEta = &eta
|
|
}
|
|
}
|
|
|
|
writeJSON(w, http.StatusOK, resp)
|
|
}
|