Cars: log what charging costs, and drag the provider readings
Three things, all on a car's page. A Charging cost tab, which is the Fuel cost tab written for an electric car: charges in kWh, consumption in kWh/100km beside km per kWh, cost per km and price per kWh, and the same summary panel over the whole history. It keeps the reference-point method too, and has to — a session records the energy that went in, not what was left in the battery, so a given number of kWh only maps to a distance between two charges that ended at the same state. A charge to the car's usual full point plays the part of the full tank; partial charges still count towards the cost and roll into the next full one; and a charge taken without logging it leaves its window uncomputed rather than reporting an implausibly good figure. Sessions live in their own collection, the figures are derived on read like the fuel ones, and logging a charge advances the odometer exactly as a refill does. The tab switches off from the gear like every other, so a petrol car need never see it. The headline readings on the connected-service tab now drag into any order, saved on drop. Stored on the car as metricOrder, like the Information rows, rather than per device the way the collapsed cards are: an arrangement is something everyone the car is shared with should see, where a folded card is one browser's reading habit. Only what the provider reported can be arranged, so a reading that turns up later joins the end rather than displacing the arrangement. Fuel is now Fuel cost, tab and heading, which is what the tab has always been about and what pairs it with Charging cost. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
2b6da642ad
commit
6191160f14
@@ -245,7 +245,7 @@ func (s *Server) updateCar(w http.ResponseWriter, r *http.Request) {
|
||||
// be a dead end.
|
||||
var hideableCarTabs = map[string]bool{
|
||||
"provider": true, "services": true, "technical": true, "maintenance": true,
|
||||
"fuel": true, "documents": true, "parts": true, "reminders": true,
|
||||
"fuel": true, "charging": true, "documents": true, "parts": true, "reminders": true,
|
||||
}
|
||||
|
||||
// hideableCarFields are the Information rows that can be switched off — every
|
||||
@@ -258,6 +258,21 @@ var hideableCarFields = map[string]bool{
|
||||
"vin": true, "fuelType": true, "buildDate": true, "firstRegistration": true,
|
||||
}
|
||||
|
||||
// arrangeableCarMetrics are the headline readings on the connected-service tab,
|
||||
// and so the keys a car's arrangement of them may name. Derived from the reading
|
||||
// specs in vehicleproviders.go rather than written out again, so the set cannot
|
||||
// drift from what that panel actually shows.
|
||||
var arrangeableCarMetrics = func() map[string]bool {
|
||||
out := make(map[string]bool, len(headlineMetricSpecs)+len(unmeasuredMetricKeys))
|
||||
for _, spec := range headlineMetricSpecs {
|
||||
out[spec.key] = true
|
||||
}
|
||||
for _, key := range unmeasuredMetricKeys {
|
||||
out[key] = true
|
||||
}
|
||||
return out
|
||||
}()
|
||||
|
||||
// normalizeKeys validates a list of tab or field keys against the keys that
|
||||
// exist, trimming blanks and duplicates. Unknown keys are rejected rather than
|
||||
// ignored: they can only come from a stale or wrong client, and dropping them
|
||||
@@ -280,10 +295,11 @@ func normalizeKeys(in []string, allowed map[string]bool, what string) ([]string,
|
||||
}
|
||||
|
||||
// PUT /api/cars/{id}/view — choose what this car's page shows: which tabs, which
|
||||
// rows of the Information tab, and the order those rows are laid out in. Body:
|
||||
// {hiddenTabs?: [...], hiddenFields?: [...], fieldOrder?: [...]}; only the lists
|
||||
// present are written, so a client can rearrange the rows without resending what
|
||||
// is hidden. Its own endpoint rather than fields on the car edit, so an ordinary
|
||||
// rows of the Information tab, and the order the Information rows and the
|
||||
// connected service's headline readings are laid out in. Body: {hiddenTabs?:
|
||||
// [...], hiddenFields?: [...], fieldOrder?: [...], metricOrder?: [...]}; only the
|
||||
// lists present are written, so a client can rearrange one group without
|
||||
// resending the others. Its own endpoint rather than fields on the car edit, so an ordinary
|
||||
// save of the car form — which sends every other field — can never reveal
|
||||
// something somebody deliberately switched off. Needs write access: the choice
|
||||
// belongs to the car, so it is the same permission as editing it.
|
||||
@@ -292,6 +308,7 @@ func (s *Server) updateCarView(w http.ResponseWriter, r *http.Request) {
|
||||
HiddenTabs *[]string `json:"hiddenTabs"`
|
||||
HiddenFields *[]string `json:"hiddenFields"`
|
||||
FieldOrder *[]string `json:"fieldOrder"`
|
||||
MetricOrder *[]string `json:"metricOrder"`
|
||||
}
|
||||
if err := decodeJSON(r, &in); err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
@@ -336,6 +353,18 @@ func (s *Server) updateCarView(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
payload["field_order"] = order
|
||||
}
|
||||
if in.MetricOrder != nil {
|
||||
// A partial list again, and here it is the normal case: the client can
|
||||
// only arrange the readings the provider actually reported, so one it
|
||||
// reports later — an EV range on a car that was parked unplugged — joins
|
||||
// at the end rather than displacing the arrangement.
|
||||
order, err := normalizeKeys(*in.MetricOrder, arrangeableCarMetrics, "reading")
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
payload["metric_order"] = order
|
||||
}
|
||||
if len(payload) == 0 {
|
||||
writeError(w, http.StatusBadRequest, "no changes provided")
|
||||
return
|
||||
|
||||
@@ -33,13 +33,16 @@ func TestNormalizeHiddenTabs(t *testing.T) {
|
||||
|
||||
// The hideable set is the contract the web app's HIDEABLE_TABS mirrors:
|
||||
// every tab the car page renders beside Information.
|
||||
for _, key := range []string{"provider", "services", "technical", "maintenance", "fuel", "documents", "parts", "reminders"} {
|
||||
for _, key := range []string{
|
||||
"provider", "services", "technical", "maintenance", "fuel", "charging",
|
||||
"documents", "parts", "reminders",
|
||||
} {
|
||||
if !hideableCarTabs[key] {
|
||||
t.Errorf("tab %q should be hideable", key)
|
||||
}
|
||||
}
|
||||
if len(hideableCarTabs) != 8 {
|
||||
t.Errorf("hideableCarTabs has %d entries, want the 8 tabs beside Information", len(hideableCarTabs))
|
||||
if len(hideableCarTabs) != 9 {
|
||||
t.Errorf("hideableCarTabs has %d entries, want the 9 tabs beside Information", len(hideableCarTabs))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,6 +102,32 @@ func TestNormalizeFieldOrder(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// The connected service's headline readings arrange the same way, against the
|
||||
// key set derived from what that panel renders.
|
||||
func TestNormalizeMetricOrder(t *testing.T) {
|
||||
got, err := normalizeKeys([]string{"evRangeWithAc", "odometer"}, arrangeableCarMetrics, "reading")
|
||||
if err != nil {
|
||||
t.Fatalf("normalizeKeys: %v", err)
|
||||
}
|
||||
assertKeys(t, got, []string{"evRangeWithAc", "odometer"})
|
||||
|
||||
// Every reading the panel can show has to be arrangeable, the two that are
|
||||
// not measures included.
|
||||
for _, key := range []string{
|
||||
"odometer", "fuelLevel", "fuelRange", "batteryLevel", "evRange",
|
||||
"evRangeWithAc", "chargingStatus", "location",
|
||||
} {
|
||||
if !arrangeableCarMetrics[key] {
|
||||
t.Errorf("reading %q should be arrangeable", key)
|
||||
}
|
||||
}
|
||||
|
||||
// A field key is not a reading key — a car's two arrangements are separate.
|
||||
if _, err := normalizeKeys([]string{"vin"}, arrangeableCarMetrics, "reading"); err == nil {
|
||||
t.Error("normalizeKeys accepted a field key as a reading, want an error")
|
||||
}
|
||||
}
|
||||
|
||||
func assertKeys(t *testing.T, got, want []string) {
|
||||
t.Helper()
|
||||
if len(got) != len(want) {
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sort"
|
||||
|
||||
"drivervault/apiserver/internal/models"
|
||||
)
|
||||
|
||||
// Charging tracking: a log of charges per car, plus the efficiency derived from
|
||||
// it. The EV counterpart of fuel.go, and deliberately the same shape — a car
|
||||
// that runs on electrons still has a cost per km, and the two tabs read alike.
|
||||
//
|
||||
// Nothing about consumption is stored — it is recomputed from the whole history
|
||||
// on every read (models.ComputeChargingDerived), so correcting a session three
|
||||
// months back fixes every window it touches with no rows to migrate.
|
||||
|
||||
// fetchChargingSessions loads a car's charges oldest-first and fills in the
|
||||
// derived efficiency fields. Ordering is by odometer rather than date because
|
||||
// the windows are spans of distance, and a session logged with the wrong date
|
||||
// would otherwise scramble the chain.
|
||||
func (s *Server) fetchChargingSessions(r *http.Request, carID string) ([]models.ChargingSession, error) {
|
||||
res, err := s.pb.List(r.Context(), colCharging, url.Values{
|
||||
"filter": {fmt.Sprintf("car='%s'", carID)},
|
||||
"sort": {"km"},
|
||||
"perPage": {"1000"},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var recs []chargingRecord
|
||||
if err := json.Unmarshal(res.Items, &recs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]models.ChargingSession, 0, len(recs))
|
||||
for _, rec := range recs {
|
||||
out = append(out, rec.toModel())
|
||||
}
|
||||
// PocketBase sorts numerically here, but re-sorting locally keeps the
|
||||
// invariant ComputeChargingDerived depends on explicit and cheap.
|
||||
sort.SliceStable(out, func(i, j int) bool { return out[i].Km < out[j].Km })
|
||||
models.ComputeChargingDerived(out)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// listCarChargingSessions serves GET /api/cars/{id}/charging-sessions, newest first.
|
||||
func (s *Server) listCarChargingSessions(w http.ResponseWriter, r *http.Request) {
|
||||
carID := r.PathValue("id")
|
||||
if !s.requireCarAccess(w, r, carID, accessRead) {
|
||||
return
|
||||
}
|
||||
entries, err := s.fetchChargingSessions(r, carID)
|
||||
if err != nil {
|
||||
writePBError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, reverseCharging(entries))
|
||||
}
|
||||
|
||||
// listChargingSessions serves GET /api/charging-sessions?car={id}.
|
||||
func (s *Server) listChargingSessions(w http.ResponseWriter, r *http.Request) {
|
||||
carID := r.URL.Query().Get("car")
|
||||
if !s.requireCarAccess(w, r, carID, accessRead) {
|
||||
return
|
||||
}
|
||||
entries, err := s.fetchChargingSessions(r, carID)
|
||||
if err != nil {
|
||||
writePBError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, reverseCharging(entries))
|
||||
}
|
||||
|
||||
// listCarChargingStats serves GET /api/cars/{id}/charging-stats.
|
||||
func (s *Server) listCarChargingStats(w http.ResponseWriter, r *http.Request) {
|
||||
carID := r.PathValue("id")
|
||||
if !s.requireCarAccess(w, r, carID, accessRead) {
|
||||
return
|
||||
}
|
||||
entries, err := s.fetchChargingSessions(r, carID)
|
||||
if err != nil {
|
||||
writePBError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, models.ComputeChargingStats(entries))
|
||||
}
|
||||
|
||||
// reverseCharging flips the oldest-first working order into the newest-first
|
||||
// order clients display.
|
||||
func reverseCharging(in []models.ChargingSession) []models.ChargingSession {
|
||||
out := make([]models.ChargingSession, len(in))
|
||||
for i, e := range in {
|
||||
out[len(in)-1-i] = e
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// withChargingDerived recomputes the whole history and returns the one session
|
||||
// the caller just wrote, so a create/update response carries the same derived
|
||||
// figures the list would show.
|
||||
func (s *Server) withChargingDerived(r *http.Request, carID, id string) (models.ChargingSession, error) {
|
||||
entries, err := s.fetchChargingSessions(r, carID)
|
||||
if err != nil {
|
||||
return models.ChargingSession{}, err
|
||||
}
|
||||
for _, e := range entries {
|
||||
if e.ID == id {
|
||||
return e, nil
|
||||
}
|
||||
}
|
||||
return models.ChargingSession{}, fmt.Errorf("charging session %s not found after write", id)
|
||||
}
|
||||
|
||||
func (s *Server) getChargingSession(w http.ResponseWriter, r *http.Request) {
|
||||
var rec chargingRecord
|
||||
if err := s.pb.GetOne(r.Context(), colCharging, r.PathValue("id"), &rec); err != nil {
|
||||
writePBError(w, err)
|
||||
return
|
||||
}
|
||||
if !s.requireCarAccess(w, r, rec.Car, accessRead) {
|
||||
return
|
||||
}
|
||||
entry, err := s.withChargingDerived(r, rec.Car, rec.ID)
|
||||
if err != nil {
|
||||
writePBError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, entry)
|
||||
}
|
||||
|
||||
func (s *Server) createChargingSession(w http.ResponseWriter, r *http.Request) {
|
||||
var in models.ChargingSession
|
||||
if err := decodeJSON(r, &in); err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
if err := validateChargingSession(in); err != "" {
|
||||
writeError(w, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
if !s.requireCarAccess(w, r, in.Car, accessWrite) {
|
||||
return
|
||||
}
|
||||
var rec chargingRecord
|
||||
if err := s.pb.Create(r.Context(), colCharging, chargingPayload(in), &rec); err != nil {
|
||||
writePBError(w, err)
|
||||
return
|
||||
}
|
||||
// A charge is also the freshest odometer reading there is, exactly as a
|
||||
// refill is; keeping the car in step means the km-based service and reminder
|
||||
// status stay honest without the user retyping the number on the car itself.
|
||||
s.advanceOdometer(r, in.Car, in.Km)
|
||||
|
||||
entry, err := s.withChargingDerived(r, rec.Car, rec.ID)
|
||||
if err != nil {
|
||||
writePBError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, entry)
|
||||
}
|
||||
|
||||
func (s *Server) updateChargingSession(w http.ResponseWriter, r *http.Request) {
|
||||
var in models.ChargingSession
|
||||
if err := decodeJSON(r, &in); err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
var existing chargingRecord
|
||||
if err := s.pb.GetOne(r.Context(), colCharging, r.PathValue("id"), &existing); err != nil {
|
||||
writePBError(w, err)
|
||||
return
|
||||
}
|
||||
if !s.requireCarAccess(w, r, existing.Car, accessWrite) {
|
||||
return
|
||||
}
|
||||
// The car is fixed by the record being edited; a body claiming another car
|
||||
// must not move the session across the access boundary just checked.
|
||||
in.Car = existing.Car
|
||||
if err := validateChargingSession(in); err != "" {
|
||||
writeError(w, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
var rec chargingRecord
|
||||
if err := s.pb.Update(r.Context(), colCharging, r.PathValue("id"), chargingPayload(in), &rec); err != nil {
|
||||
writePBError(w, err)
|
||||
return
|
||||
}
|
||||
s.advanceOdometer(r, rec.Car, in.Km)
|
||||
|
||||
entry, err := s.withChargingDerived(r, rec.Car, rec.ID)
|
||||
if err != nil {
|
||||
writePBError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, entry)
|
||||
}
|
||||
|
||||
func (s *Server) deleteChargingSession(w http.ResponseWriter, r *http.Request) {
|
||||
var existing chargingRecord
|
||||
if err := s.pb.GetOne(r.Context(), colCharging, r.PathValue("id"), &existing); err != nil {
|
||||
writePBError(w, err)
|
||||
return
|
||||
}
|
||||
if !s.requireCarAccess(w, r, existing.Car, accessWrite) {
|
||||
return
|
||||
}
|
||||
if err := s.pb.Delete(r.Context(), colCharging, r.PathValue("id")); err != nil {
|
||||
writePBError(w, err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// validateChargingSession returns a human-readable reason the session is
|
||||
// unusable, or "" when it is fine.
|
||||
func validateChargingSession(c models.ChargingSession) string {
|
||||
switch {
|
||||
case c.Car == "":
|
||||
return "car is required"
|
||||
case c.Date.IsZero():
|
||||
return "date is required"
|
||||
case c.Km <= 0:
|
||||
return "odometer (km) is required"
|
||||
case c.Kwh <= 0:
|
||||
return "kwh must be greater than zero"
|
||||
case c.Cost < 0:
|
||||
return "cost cannot be negative"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -68,12 +68,14 @@ type carRecord struct {
|
||||
Created string `json:"created"`
|
||||
Updated string `json:"updated"`
|
||||
|
||||
// Switched-off tabs and Information fields, plus the arrangement of the
|
||||
// Information rows. Raw because PocketBase hands back whatever a json field
|
||||
// holds — null on a car nobody has configured — which is not a []string.
|
||||
// Switched-off tabs and Information fields, plus the arrangements of the
|
||||
// Information rows and the connected service's readings. Raw because
|
||||
// PocketBase hands back whatever a json field holds — null on a car nobody
|
||||
// has configured — which is not a []string.
|
||||
HiddenTabs json.RawMessage `json:"hidden_tabs"`
|
||||
HiddenFields json.RawMessage `json:"hidden_fields"`
|
||||
FieldOrder json.RawMessage `json:"field_order"`
|
||||
MetricOrder json.RawMessage `json:"metric_order"`
|
||||
}
|
||||
|
||||
func (rec carRecord) toModel() models.Car {
|
||||
@@ -103,6 +105,7 @@ func (rec carRecord) toModel() models.Car {
|
||||
HiddenTabs: decodeStringList(rec.HiddenTabs),
|
||||
HiddenFields: decodeStringList(rec.HiddenFields),
|
||||
FieldOrder: decodeStringList(rec.FieldOrder),
|
||||
MetricOrder: decodeStringList(rec.MetricOrder),
|
||||
Owner: rec.Owner,
|
||||
Created: rec.Created,
|
||||
Updated: rec.Updated,
|
||||
@@ -359,6 +362,57 @@ func fuelPayload(f models.FuelEntry) map[string]any {
|
||||
}
|
||||
}
|
||||
|
||||
// --- charging sessions ---
|
||||
|
||||
type chargingRecord struct {
|
||||
ID string `json:"id"`
|
||||
Car string `json:"car"`
|
||||
Date string `json:"date"`
|
||||
Km int `json:"km"`
|
||||
Kwh float64 `json:"kwh"`
|
||||
Cost float64 `json:"cost"`
|
||||
FullCharge bool `json:"full_charge"`
|
||||
MissedSession bool `json:"missed_session"`
|
||||
Location string `json:"location"`
|
||||
Notes string `json:"notes"`
|
||||
File string `json:"file"`
|
||||
Created string `json:"created"`
|
||||
Updated string `json:"updated"`
|
||||
}
|
||||
|
||||
func (rec chargingRecord) toModel() models.ChargingSession {
|
||||
return models.ChargingSession{
|
||||
ID: rec.ID,
|
||||
Car: rec.Car,
|
||||
Date: parsePBDate(rec.Date),
|
||||
Km: rec.Km,
|
||||
Kwh: rec.Kwh,
|
||||
Cost: rec.Cost,
|
||||
FullCharge: rec.FullCharge,
|
||||
MissedSession: rec.MissedSession,
|
||||
Location: rec.Location,
|
||||
Notes: rec.Notes,
|
||||
Attachment: attachmentOf(rec.File),
|
||||
Created: rec.Created,
|
||||
Updated: rec.Updated,
|
||||
}
|
||||
}
|
||||
|
||||
// chargingPayload omits the file field — see attachmentOf.
|
||||
func chargingPayload(c models.ChargingSession) map[string]any {
|
||||
return map[string]any{
|
||||
"car": c.Car,
|
||||
"date": formatPBDate(c.Date),
|
||||
"km": c.Km,
|
||||
"kwh": c.Kwh,
|
||||
"cost": c.Cost,
|
||||
"full_charge": c.FullCharge,
|
||||
"missed_session": c.MissedSession,
|
||||
"location": c.Location,
|
||||
"notes": c.Notes,
|
||||
}
|
||||
}
|
||||
|
||||
// --- maintenance entries ---
|
||||
|
||||
type maintenanceRecord struct {
|
||||
|
||||
@@ -85,6 +85,13 @@
|
||||
// GET /api/fuel-entries/{id} PATCH /api/fuel-entries/{id}
|
||||
// DELETE /api/fuel-entries/{id}
|
||||
//
|
||||
// # charging tracking (EV counterpart of fuel; efficiency derived on read)
|
||||
// GET /api/cars/{id}/charging-sessions
|
||||
// GET /api/cars/{id}/charging-stats
|
||||
// GET /api/charging-sessions POST /api/charging-sessions
|
||||
// GET /api/charging-sessions/{id} PATCH /api/charging-sessions/{id}
|
||||
// DELETE /api/charging-sessions/{id}
|
||||
//
|
||||
// # maintenance log (workshop visits + repairs; distinct from service records)
|
||||
// GET /api/cars/{id}/maintenance
|
||||
// GET /api/maintenance POST /api/maintenance
|
||||
@@ -99,7 +106,7 @@
|
||||
//
|
||||
// # attachments — one optional file per record, same three verbs everywhere.
|
||||
// # {records} is car-documents | service-records | technical-checks | maintenance
|
||||
// # | fuel-entries | parts
|
||||
// # | fuel-entries | charging-sessions | parts
|
||||
// POST /api/{records}/{id}/file
|
||||
// GET /api/{records}/{id}/file
|
||||
// DELETE /api/{records}/{id}/file
|
||||
@@ -136,6 +143,7 @@ const (
|
||||
colShares = "car_shares"
|
||||
colOrgs = "organizations"
|
||||
colFuel = "fuel_entries"
|
||||
colCharging = "charging_sessions"
|
||||
colMaintenance = "maintenance_entries"
|
||||
colDocuments = "car_documents"
|
||||
colReminders = "reminders"
|
||||
@@ -360,6 +368,8 @@ func (s *Server) Handler() http.Handler {
|
||||
mux.HandleFunc("GET /api/cars/{id}/parts", s.listCarParts)
|
||||
mux.HandleFunc("GET /api/cars/{id}/fuel-entries", s.listCarFuelEntries)
|
||||
mux.HandleFunc("GET /api/cars/{id}/fuel-stats", s.listCarFuelStats)
|
||||
mux.HandleFunc("GET /api/cars/{id}/charging-sessions", s.listCarChargingSessions)
|
||||
mux.HandleFunc("GET /api/cars/{id}/charging-stats", s.listCarChargingStats)
|
||||
mux.HandleFunc("GET /api/cars/{id}/maintenance", s.listCarMaintenance)
|
||||
mux.HandleFunc("GET /api/cars/{id}/documents", s.listCarDocuments)
|
||||
mux.HandleFunc("GET /api/cars/{id}/reminders", s.listCarReminders)
|
||||
@@ -398,6 +408,13 @@ func (s *Server) Handler() http.Handler {
|
||||
mux.HandleFunc("PATCH /api/fuel-entries/{id}", s.updateFuelEntry)
|
||||
mux.HandleFunc("DELETE /api/fuel-entries/{id}", s.deleteFuelEntry)
|
||||
|
||||
// Charging sessions.
|
||||
mux.HandleFunc("GET /api/charging-sessions", s.listChargingSessions)
|
||||
mux.HandleFunc("POST /api/charging-sessions", s.createChargingSession)
|
||||
mux.HandleFunc("GET /api/charging-sessions/{id}", s.getChargingSession)
|
||||
mux.HandleFunc("PATCH /api/charging-sessions/{id}", s.updateChargingSession)
|
||||
mux.HandleFunc("DELETE /api/charging-sessions/{id}", s.deleteChargingSession)
|
||||
|
||||
// Maintenance log.
|
||||
mux.HandleFunc("GET /api/maintenance", s.listMaintenance)
|
||||
mux.HandleFunc("POST /api/maintenance", s.createMaintenance)
|
||||
@@ -429,6 +446,7 @@ func (s *Server) Handler() http.Handler {
|
||||
s.attachmentRoutes(mux, "/api/technical-checks", colTechnicalChecks, s.getTechnicalCheck)
|
||||
s.attachmentRoutes(mux, "/api/maintenance", colMaintenance, s.getMaintenance)
|
||||
s.attachmentRoutes(mux, "/api/fuel-entries", colFuel, s.getFuelEntry)
|
||||
s.attachmentRoutes(mux, "/api/charging-sessions", colCharging, s.getChargingSession)
|
||||
s.attachmentRoutes(mux, "/api/parts", colParts, s.getPart)
|
||||
|
||||
return s.withMiddleware(mux)
|
||||
|
||||
@@ -633,25 +633,33 @@ type metricSpec struct {
|
||||
distance bool // convert an imperial reading to kilometres
|
||||
}
|
||||
|
||||
// headlineMetricSpecs are the measured readings, in the order they are reported
|
||||
// when a car has no arrangement of its own. Package-level so the set of keys a
|
||||
// car's arrangement may name (arrangeableCarMetrics, in cars.go) is derived from
|
||||
// it and the two cannot drift apart.
|
||||
var headlineMetricSpecs = []metricSpec{
|
||||
{key: "odometer", keys: []string{"odometer", "mileage", "totalMileage", "odometerReading", "distanceTotal"}, unit: "km", distance: true},
|
||||
{key: "fuelLevel", keys: []string{"fuelLevel", "fuelPercentage", "fuelRemainingPercent"}, unit: "%"},
|
||||
{key: "fuelRange", keys: []string{"fuelRange", "rangeRemaining", "drivingRange", "fuelRangeTotal"}, unit: "km", distance: true},
|
||||
{key: "batteryLevel", keys: []string{"batteryLevel", "chargeRemainingAmount", "stateOfCharge", "socLevel"}, unit: "%"},
|
||||
{key: "evRange", keys: []string{"evRange", "electricRange", "batteryRange"}, unit: "km", distance: true},
|
||||
// Range with the climate control running, which Toyota reports beside the
|
||||
// plain one. Its own reading rather than a fallback for evRange: the two
|
||||
// are different numbers and the gap between them is the point — a driver
|
||||
// deciding whether to run the A/C wants to see both.
|
||||
{key: "evRangeWithAc", keys: []string{"evRangeWithAc"}, unit: "km", distance: true},
|
||||
}
|
||||
|
||||
// unmeasuredMetricKeys are the headline readings that are not measures — a state
|
||||
// and a pair of coordinates — picked out separately below.
|
||||
var unmeasuredMetricKeys = []string{"chargingStatus", "location"}
|
||||
|
||||
// headlineMetrics lifts the readings worth showing large out of the section
|
||||
// payloads. Everything not listed here still reaches the UI as a flattened
|
||||
// field — this is about prominence, not about filtering.
|
||||
func headlineMetrics(trees []any) []providerMetric {
|
||||
specs := []metricSpec{
|
||||
{key: "odometer", keys: []string{"odometer", "mileage", "totalMileage", "odometerReading", "distanceTotal"}, unit: "km", distance: true},
|
||||
{key: "fuelLevel", keys: []string{"fuelLevel", "fuelPercentage", "fuelRemainingPercent"}, unit: "%"},
|
||||
{key: "fuelRange", keys: []string{"fuelRange", "rangeRemaining", "drivingRange", "fuelRangeTotal"}, unit: "km", distance: true},
|
||||
{key: "batteryLevel", keys: []string{"batteryLevel", "chargeRemainingAmount", "stateOfCharge", "socLevel"}, unit: "%"},
|
||||
{key: "evRange", keys: []string{"evRange", "electricRange", "batteryRange"}, unit: "km", distance: true},
|
||||
// Range with the climate control running, which Toyota reports beside the
|
||||
// plain one. Its own reading rather than a fallback for evRange: the two
|
||||
// are different numbers and the gap between them is the point — a driver
|
||||
// deciding whether to run the A/C wants to see both.
|
||||
{key: "evRangeWithAc", keys: []string{"evRangeWithAc"}, unit: "km", distance: true},
|
||||
}
|
||||
|
||||
out := []providerMetric{}
|
||||
for _, spec := range specs {
|
||||
for _, spec := range headlineMetricSpecs {
|
||||
for _, tree := range trees {
|
||||
n, unit, ok := findMeasure(tree, spec.keys...)
|
||||
if !ok {
|
||||
|
||||
Reference in New Issue
Block a user