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:
tajniak81
2026-08-17 22:17:52 +02:00
co-authored by Claude Opus 5
parent 2b6da642ad
commit 6191160f14
20 changed files with 1388 additions and 53 deletions
+10 -4
View File
@@ -23,7 +23,8 @@ internal/
│ ├── status.go # upstream health probes
│ ├── health.go respond.go panel.go
│ ├── cars.go records.go services.go parts.go shares.go me.go
│ ├── technical.go fuel.go maintenance.go documents.go reminders.go
│ ├── technical.go fuel.go charging.go maintenance.go documents.go
│ ├── reminders.go
│ ├── attachments.go # one optional file per record (shared handlers)
│ ├── integrations*.go # per-user Toyota / Anker Solix settings + OCPP control
│ └── dist/ # built panel, embedded via go:embed
@@ -111,6 +112,7 @@ other users `read` or `write` access. Every car/service/part handler is gated by
| `technical_checks` | roadworthiness inspections (przegląd techniczny / MOT / TÜV) | car, date, `result` (passed \| failed), cost, station, `valid_until`, notes |
| `parts` | per-car parts catalog | car, name, part_number, category, notes |
| `fuel_entries` | refuelling log (efficiency derived on read) | car, date, km, liters, cost, `full_tank`, `missed_fill`, station, notes |
| `charging_sessions` | EV charging log, the same shape as the refuelling one (kWh/100km derived on read) | car, date, km, kwh, cost, `full_charge`, `missed_session`, location, notes |
| `maintenance_entries` | workshop visits & repairs (outside routine service) | car, date, km, type, status, workshop, parts_used, labor_cost, parts_cost, invoice_number, warranty_until, notes |
| `car_documents` | paperwork (insurance, registration, road tax, …) | car, type, title, provider, reference, issue_date, expiry_date, cost, notes |
| `reminders` | date/odometer reminders (some auto-derived) | car, title, type, due_date, due_km, repeat_days, repeat_km, done, done_at, notes |
@@ -191,21 +193,25 @@ POST /api/vehicle-providers/{provider}/import
# which PATCH /api/me {carOrder} sets)
GET /api/cars POST /api/cars
GET /api/cars/{id} PATCH /api/cars/{id} DELETE /api/cars/{id}
PUT /api/cars/{id}/view # which tabs + Information rows this car shows, and their order
PUT /api/cars/{id}/view # which tabs + Information rows this car shows,
# and the order of the rows and the provider readings
GET /api/cars/{id}/provider POST /api/cars/{id}/provider
POST /api/cars/{id}/provider/sync
GET /api/cars/{id}/service-records GET /api/cars/{id}/technical-checks
GET /api/cars/{id}/parts GET /api/cars/{id}/fuel-entries GET /api/cars/{id}/fuel-stats
GET /api/cars/{id}/charging-sessions GET /api/cars/{id}/charging-stats
GET /api/cars/{id}/maintenance GET /api/cars/{id}/documents GET /api/cars/{id}/reminders
GET /api/cars/{id}/shares POST /api/cars/{id}/shares DELETE /api/cars/{id}/shares/{userId}
# per-record collections — each is GET(list) POST / GET PATCH DELETE {id}
/api/service-records /api/technical-checks /api/parts
/api/fuel-entries /api/maintenance /api/car-documents
/api/fuel-entries /api/charging-sessions /api/maintenance
/api/car-documents
/api/reminders (+ POST /api/reminders/{id}/complete)
# attachments — one optional file per record, on every collection that takes one.
# {records} = car-documents | service-records | technical-checks | maintenance | fuel-entries | parts
# {records} = car-documents | service-records | technical-checks | maintenance
# | fuel-entries | charging-sessions | parts
POST /api/{records}/{id}/file GET /api/{records}/{id}/file DELETE /api/{records}/{id}/file
```
+34 -5
View File
@@ -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
+32 -3
View File
@@ -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) {
+233
View File
@@ -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 ""
}
+57 -3
View File
@@ -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 {
+19 -1
View File
@@ -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)
+22 -14
View File
@@ -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 {
+21 -2
View File
@@ -46,9 +46,11 @@ var collectionsSchema = map[string][]fieldDef{
// release is on by default. Keys are validated in internal/api/cars.go.
fJSON("hidden_tabs", 2000),
fJSON("hidden_fields", 2000),
// The order the Information rows are laid out in, as field keys. Empty
// means the page's own default order.
// The order the Information rows are laid out in, as field keys, and the
// same for the connected service's headline readings. Empty means the
// page's own default order.
fJSON("field_order", 2000),
fJSON("metric_order", 2000),
// Owner of this car. Non-cascading: deleting a user must not wipe their cars.
fRelation("owner", "users", false, false),
},
@@ -94,6 +96,20 @@ var collectionsSchema = map[string][]fieldDef{
fText("notes", false),
attachment(), // the pump receipt
},
// Charging sessions for an electric car — the EV counterpart of fuel_entries,
// same shape so the two logs behave alike. Consumption is derived on read.
"charging_sessions": {
fRelation("car", "cars", true, true),
fDate("date", true),
fNumber("km"), // odometer when plugging in
fNumber("kwh"),
fNumber("cost"),
fBool("full_charge"),
fBool("missed_session"),
fText("location", false), // "Home", "Ionity Køge"
fText("notes", false),
attachment(), // the charge point's receipt
},
// Workshop visits and repairs (unplanned/one-off garage work with a labour bill).
"maintenance_entries": {
fRelation("car", "cars", true, true),
@@ -199,6 +215,7 @@ var createOrder = []string{
"parts",
"car_shares",
"fuel_entries",
"charging_sessions",
"maintenance_entries",
"car_documents",
"reminders",
@@ -216,6 +233,7 @@ var reconcileOrder = []string{
"parts",
"car_shares",
"fuel_entries",
"charging_sessions",
"maintenance_entries",
"car_documents",
"reminders",
@@ -226,6 +244,7 @@ var reconcileOrder = []string{
var indexes = map[string][]string{
"organizations": {"CREATE UNIQUE INDEX `idx_organizations_name` ON `organizations` (`name`)"},
"fuel_entries": {"CREATE INDEX `idx_fuel_entries_car_km` ON `fuel_entries` (`car`, `km`)"},
"charging_sessions": {"CREATE INDEX `idx_charging_sessions_car_km` ON `charging_sessions` (`car`, `km`)"},
"maintenance_entries": {"CREATE INDEX `idx_maintenance_entries_car_date` ON `maintenance_entries` (`car`, `date`)"},
"car_documents": {"CREATE INDEX `idx_car_documents_car_expiry` ON `car_documents` (`car`, `expiry_date`)"},
"reminders": {"CREATE INDEX `idx_reminders_car_due` ON `reminders` (`car`, `due_date`)"},
+103
View File
@@ -0,0 +1,103 @@
package models
import (
"math"
"testing"
"time"
)
// The charging figures are derived from the whole history on every read, so the
// window rules are the thing worth pinning down: what closes a window, what
// folds into it, and what makes one uncomputable.
func day(n int) time.Time { return time.Date(2026, 3, n, 8, 0, 0, 0, time.UTC) }
func TestComputeChargingDerivedWindows(t *testing.T) {
// A first full charge (no window before it), then 300 km on 45 kWh split
// across a partial top-up and the full charge that closes the window.
entries := []ChargingSession{
{Date: day(1), Km: 10000, Kwh: 50, Cost: 100, FullCharge: true},
{Date: day(3), Km: 10120, Kwh: 15, Cost: 45},
{Date: day(6), Km: 10300, Kwh: 30, Cost: 75, FullCharge: true},
}
ComputeChargingDerived(entries)
// The first full charge has nothing before it to measure against.
if entries[0].ConsumptionKwh100 != nil {
t.Errorf("first full charge got a consumption figure: %v", *entries[0].ConsumptionKwh100)
}
// A partial charge never closes a window — it folds into the next full one.
if entries[1].ConsumptionKwh100 != nil {
t.Errorf("partial charge got a consumption figure: %v", *entries[1].ConsumptionKwh100)
}
closing := entries[2]
if closing.DistanceKm == nil || *closing.DistanceKm != 300 {
t.Fatalf("distance = %v, want 300", closing.DistanceKm)
}
// 15 + 30 kWh over 300 km: the partial counts, the opening charge does not.
if closing.KwhUsed == nil || *closing.KwhUsed != 45 {
t.Fatalf("kwhUsed = %v, want 45", closing.KwhUsed)
}
assertFloat(t, "consumption", closing.ConsumptionKwh100, 15) // 45/300*100
assertFloat(t, "kmPerKwh", closing.KmPerKwh, 300.0/45.0) // 6.67
assertFloat(t, "costPerKm", closing.CostPerKm, (45+75)/300.0) // 0.40
assertFloat(t, "pricePerKwh", closing.PricePerKwh, 75.0/30.0) // 2.50
}
func TestComputeChargingDerivedMissedSession(t *testing.T) {
// The car was charged somewhere without being logged, so the kWh on record
// do not account for the distance: reporting a figure would be fiction.
entries := []ChargingSession{
{Date: day(1), Km: 10000, Kwh: 50, Cost: 100, FullCharge: true},
{Date: day(5), Km: 10400, Kwh: 40, Cost: 80, FullCharge: true, MissedSession: true},
}
ComputeChargingDerived(entries)
if entries[1].ConsumptionKwh100 != nil {
t.Errorf("window with a missed session got a figure: %v", *entries[1].ConsumptionKwh100)
}
// The price of that charge is still known — it is on the receipt.
assertFloat(t, "pricePerKwh", entries[1].PricePerKwh, 2)
}
func TestComputeChargingStats(t *testing.T) {
// Two computable windows of different lengths: 100 km at 20 kWh/100km and
// 300 km at 10 kWh/100km. The average has to be distance-weighted (40 kWh
// over 400 km = 10 kWh/100km), not the mean of the two figures (15).
entries := []ChargingSession{
{Date: day(1), Km: 10000, Kwh: 10, Cost: 20, FullCharge: true},
{Date: day(2), Km: 10100, Kwh: 20, Cost: 40, FullCharge: true},
{Date: day(4), Km: 10400, Kwh: 30, Cost: 60, FullCharge: true},
}
ComputeChargingDerived(entries)
st := ComputeChargingStats(entries)
if st.Entries != 3 || st.TotalKwh != 60 || st.TotalCost != 120 {
t.Fatalf("totals = %d entries, %v kWh, %v cost", st.Entries, st.TotalKwh, st.TotalCost)
}
if st.TrackedDistanceKm != 400 {
t.Fatalf("trackedDistance = %d, want 400", st.TrackedDistanceKm)
}
assertFloat(t, "avg", st.AvgConsumptionKwh100, 12.5) // 50 kWh over 400 km
assertFloat(t, "best", st.BestConsumptionKwh100, 10) // the 300 km window
assertFloat(t, "worst", st.WorstConsumptionKwh100, 20)
assertFloat(t, "avgPricePerKwh", st.AvgPricePerKwh, 2)
assertFloat(t, "costPerKm", st.CostPerKm, 0.25) // 100 spent over 400 km
}
func TestComputeChargingStatsEmpty(t *testing.T) {
st := ComputeChargingStats(nil)
if st.Entries != 0 || st.AvgConsumptionKwh100 != nil || st.FirstDate != nil {
t.Errorf("empty history summarised as %+v", st)
}
}
func assertFloat(t *testing.T, name string, got *float64, want float64) {
t.Helper()
if got == nil {
t.Fatalf("%s = nil, want %v", name, want)
}
if math.Abs(*got-want) > 1e-9 {
t.Fatalf("%s = %v, want %v", name, *got, want)
}
}
+196
View File
@@ -83,6 +83,12 @@ type Car struct {
// arranged ones rather than appearing in the middle.
FieldOrder []string `json:"fieldOrder"`
// MetricOrder is the same thing for the headline readings on the connected
// service's tab, as the reading keys ("odometer", "evRange", …). A reading
// the provider didn't report at the time it was arranged simply isn't in the
// list, and joins the end when it does turn up.
MetricOrder []string `json:"metricOrder"`
// Owner is the user id that owns this car. Access is the requesting user's
// permission on it — "owner", "write", or "read" — computed by the API at
// read time and never persisted (omitempty; not part of the write payload).
@@ -233,6 +239,75 @@ type FuelStats struct {
LastDate *time.Time `json:"lastDate,omitempty"`
}
// ChargingSession is one charge of an electric car — the EV counterpart of
// FuelEntry, and it works the same way: energy and money are recorded, and the
// efficiency is derived by the same reference-point method (see
// ComputeChargingDerived).
//
// A charge to the car's usual full point plays the role of the full tank. It has
// to, for the same reason: a session only says how much energy went in, not how
// much was left in the battery, so the distance a given number of kWh covered is
// only knowable between two charges that ended at the same state.
type ChargingSession struct {
ID string `json:"id"`
Car string `json:"car"` // relation -> Car.ID
Date time.Time `json:"date"` // date of the charge
Km int `json:"km"` // odometer when plugging in
Kwh float64 `json:"kwh"` // energy delivered
Cost float64 `json:"cost"` // total paid for this charge
// FullCharge marks a charge taken to the car's usual full point — the
// reference the efficiency windows are measured between.
FullCharge bool `json:"fullCharge"`
// MissedSession records that the car was charged before this without being
// logged — a top-up at a friend's socket, say. The odometer span is then not
// accounted for by the kWh on record, so any window containing it is left
// uncomputed rather than reported as implausibly efficient.
MissedSession bool `json:"missedSession"`
// Location is where it was charged ("Home", "Ionity Køge"). Free text: an
// operator list would go stale and this is only ever read by a person.
Location string `json:"location,omitempty"`
Notes string `json:"notes,omitempty"`
// The charge point's receipt.
Attachment
// Derived (not stored): filled in by the API on read.
PricePerKwh *float64 `json:"pricePerKwh,omitempty"`
DistanceKm *int `json:"distanceKm,omitempty"` // since the previous full charge
KwhUsed *float64 `json:"kwhUsed,omitempty"` // energy used over that distance
ConsumptionKwh100 *float64 `json:"consumptionKwh100,omitempty"` // kWh per 100 km
KmPerKwh *float64 `json:"kmPerKwh,omitempty"`
CostPerKm *float64 `json:"costPerKm,omitempty"`
Created string `json:"created,omitempty"`
Updated string `json:"updated,omitempty"`
}
// ChargingStats summarises a car's whole charging history.
type ChargingStats struct {
Entries int `json:"entries"`
TotalKwh float64 `json:"totalKwh"`
TotalCost float64 `json:"totalCost"`
// TrackedDistanceKm is the distance covered by computable windows, which is
// less than the odometer span whenever the history starts or ends on a
// partial charge. The averages below describe exactly this distance.
TrackedDistanceKm int `json:"trackedDistanceKm"`
AvgConsumptionKwh100 *float64 `json:"avgConsumptionKwh100,omitempty"`
BestConsumptionKwh100 *float64 `json:"bestConsumptionKwh100,omitempty"`
WorstConsumptionKwh100 *float64 `json:"worstConsumptionKwh100,omitempty"`
AvgKmPerKwh *float64 `json:"avgKmPerKwh,omitempty"`
AvgPricePerKwh *float64 `json:"avgPricePerKwh,omitempty"`
CostPerKm *float64 `json:"costPerKm,omitempty"`
FirstDate *time.Time `json:"firstDate,omitempty"`
LastDate *time.Time `json:"lastDate,omitempty"`
}
// MaintenanceEntry is one workshop visit or repair — work done on the car
// outside the routine service schedule (which lives in ServiceRecord). A broken
// alternator replaced at a garage belongs here; the annual oil change does not.
@@ -573,6 +648,127 @@ func ComputeFuelStats(entries []FuelEntry) FuelStats {
return st
}
// ComputeChargingDerived fills the derived efficiency fields on a car's charging
// history. `entries` must be ordered oldest-first by odometer.
//
// The same window method as ComputeFuelDerived, with charges to the usual full
// point as the endpoints: between two of them the car used exactly the energy
// put in over that span, since both ends are the same battery state. Partial
// charges in between fold into the window that closes them. A window is left
// uncomputed when a session inside it is flagged MissedSession, when the
// odometer did not advance, or when no energy was recorded.
func ComputeChargingDerived(entries []ChargingSession) {
for i := range entries {
if entries[i].Kwh > 0 && entries[i].Cost > 0 {
p := entries[i].Cost / entries[i].Kwh
entries[i].PricePerKwh = &p
}
}
lastFull := -1
for i := range entries {
if !entries[i].FullCharge {
continue
}
if lastFull < 0 {
// First full charge: nothing before it to measure against.
lastFull = i
continue
}
dist := entries[i].Km - entries[lastFull].Km
kwh, cost := 0.0, 0.0
usable := true
for j := lastFull + 1; j <= i; j++ {
if entries[j].MissedSession {
usable = false
}
kwh += entries[j].Kwh
cost += entries[j].Cost
}
if usable && dist > 0 && kwh > 0 {
d, k := dist, kwh
entries[i].DistanceKm = &d
entries[i].KwhUsed = &k
kwh100 := kwh / float64(dist) * 100
entries[i].ConsumptionKwh100 = &kwh100
kmpkwh := float64(dist) / kwh
entries[i].KmPerKwh = &kmpkwh
if cost > 0 {
cpk := cost / float64(dist)
entries[i].CostPerKm = &cpk
}
}
lastFull = i
}
}
// ComputeChargingStats summarises a charging history whose derived fields have
// already been filled in by ComputeChargingDerived. `entries` must be ordered
// oldest-first.
//
// Averages are distance-weighted, as with fuel: total energy over total distance
// across every computable window, so a long motorway run counts for more than a
// short trip across town — which is what actually happened to the battery.
func ComputeChargingStats(entries []ChargingSession) ChargingStats {
st := ChargingStats{Entries: len(entries)}
if len(entries) == 0 {
return st
}
var windowKwh, windowCost float64
for i := range entries {
e := &entries[i]
st.TotalKwh += e.Kwh
st.TotalCost += e.Cost
if e.ConsumptionKwh100 == nil {
continue
}
st.TrackedDistanceKm += *e.DistanceKm
windowKwh += *e.KwhUsed
if e.CostPerKm != nil {
windowCost += *e.CostPerKm * float64(*e.DistanceKm)
}
if st.BestConsumptionKwh100 == nil || *e.ConsumptionKwh100 < *st.BestConsumptionKwh100 {
v := *e.ConsumptionKwh100
st.BestConsumptionKwh100 = &v
}
if st.WorstConsumptionKwh100 == nil || *e.ConsumptionKwh100 > *st.WorstConsumptionKwh100 {
v := *e.ConsumptionKwh100
st.WorstConsumptionKwh100 = &v
}
}
if st.TrackedDistanceKm > 0 && windowKwh > 0 {
avg := windowKwh / float64(st.TrackedDistanceKm) * 100
st.AvgConsumptionKwh100 = &avg
kmpkwh := float64(st.TrackedDistanceKm) / windowKwh
st.AvgKmPerKwh = &kmpkwh
if windowCost > 0 {
cpk := windowCost / float64(st.TrackedDistanceKm)
st.CostPerKm = &cpk
}
}
if st.TotalKwh > 0 && st.TotalCost > 0 {
ppk := st.TotalCost / st.TotalKwh
st.AvgPricePerKwh = &ppk
}
first, last := entries[0].Date, entries[len(entries)-1].Date
if !first.IsZero() {
st.FirstDate = &first
}
if !last.IsZero() {
st.LastDate = &last
}
return st
}
// ComputeMaintenanceDerived fills the derived cost and warranty fields.
func (m *MaintenanceEntry) ComputeMaintenanceDerived(now time.Time) {
m.TotalCost = m.LaborCost + m.PartsCost
+27 -3
View File
@@ -281,8 +281,10 @@ const DESIRED = {
F.json("hidden_fields", 2000),
// The order the Information rows are laid out in, as field keys — the
// hidden ones included, so a row switched back on returns to where it was.
// Empty means the page's own default order.
// Empty means the page's own default order. metric_order is the same for
// the headline readings on the connected service's tab.
F.json("field_order", 2000),
F.json("metric_order", 2000),
// Owner of this car. Non-cascading on purpose: deleting a user must not
// wipe their cars (account deletion in me.go intentionally leaves cars).
// required:false at the DB level — the API always sets owner on create and
@@ -339,6 +341,25 @@ const DESIRED = {
F.text("notes"),
attachment(), // the pump receipt
],
// Charging sessions for an electric car. The EV counterpart of fuel_entries
// and deliberately the same shape: kWh where litres would be, a charge to the
// usual full point as the reference the windows are measured between, and
// consumption derived on read (models.ComputeChargingDerived).
charging_sessions: [
F.relation("car", "cars", true),
F.date("date", true),
F.number("km"), // odometer when plugging in
F.number("kwh"),
F.number("cost"),
// Charged to the car's usual full point — the reference point.
F.bool("full_charge"),
// The car was charged before this without being logged, so any window
// containing it is left uncomputed rather than reported as implausible.
F.bool("missed_session"),
F.text("location"), // "Home", "Ionity Koge"
F.text("notes"),
attachment(), // the charge point's receipt
],
// Workshop visits and repairs. Deliberately separate from service_records:
// that collection is the routine interval schedule (and drives next-service
// due), this one is unplanned/one-off garage work with a labour bill.
@@ -469,6 +490,7 @@ const INDEXES = {
// Every read of these is "…for this car", and the fuel history is walked in
// odometer order to build its efficiency windows.
fuel_entries: ["CREATE INDEX `idx_fuel_entries_car_km` ON `fuel_entries` (`car`, `km`)"],
charging_sessions: ["CREATE INDEX `idx_charging_sessions_car_km` ON `charging_sessions` (`car`, `km`)"],
maintenance_entries: ["CREATE INDEX `idx_maintenance_entries_car_date` ON `maintenance_entries` (`car`, `date`)"],
car_documents: ["CREATE INDEX `idx_car_documents_car_expiry` ON `car_documents` (`car`, `expiry_date`)"],
reminders: ["CREATE INDEX `idx_reminders_car_due` ON `reminders` (`car`, `due_date`)"],
@@ -504,6 +526,7 @@ async function main() {
"parts",
"car_shares",
"fuel_entries",
"charging_sessions",
"maintenance_entries",
"car_documents",
"reminders",
@@ -529,6 +552,7 @@ async function main() {
"parts",
"car_shares",
"fuel_entries",
"charging_sessions",
"maintenance_entries",
"car_documents",
"reminders",
@@ -539,8 +563,8 @@ async function main() {
console.log(
"\nDone. Collections ready: organizations, users, cars, service_records,\n" +
"technical_checks, parts, car_shares, fuel_entries, maintenance_entries,\n" +
"car_documents, reminders, control_audit.",
"technical_checks, parts, car_shares, fuel_entries, charging_sessions,\n" +
"maintenance_entries, car_documents, reminders, control_audit.",
);
console.log(
"Note: the legacy `sessions` collection is no longer used (auth moved to PocketBase\n" +
+16 -5
View File
@@ -32,6 +32,7 @@ web/ Vue 3 + Vite + Tailwind v4 source
App.vue layout shell + nav (Garage, Charging, Settings)
components/ Modal, AttachmentField, CarFormModal, ServiceFormModal,
TechnicalCheckFormModal, MaintenanceFormModal, FuelFormModal,
ChargingFormModal,
DocumentFormModal, ReminderFormModal, PartFormModal, ShareModal,
OrgManager, AdminUsers, Logo
views/ Login, Dashboard, CarDetail, Charging, Settings
@@ -94,9 +95,9 @@ Config (`server/.env`, copy from `.env.example`):
on touch.
- **What a car shows** — the gear button in a car's header picks both the
sections that car's page shows (connected service, service history, technical
checks, maintenance, fuel, documents, parts, reminders — Fuel off on an EV,
say) and which of the 14 Information rows it lists (no Differential oil on a
car without one). It belongs to the car, so everyone it is shared with sees
checks, maintenance, fuel cost, charging cost, documents, parts, reminders —
Fuel cost off on an EV and Charging cost off on a petrol car) and which of the
14 Information rows it lists (no Differential oil on a car without one). It belongs to the car, so everyone it is shared with sees
the same page; setting it needs write access. Stored as the *hidden* sets, so
anything added in a later release is on by default, and the Information tab
itself can't be switched off.
@@ -104,6 +105,10 @@ Config (`server/.env`, copy from `.env.example`):
into any order, saved on drop. Also a property of the car, and it covers the
hidden rows too, so switching one back on returns it to where it was. Same
native drag events as the garage, so also pointer-only.
- **Arranging the connected service's readings** — the headline readings on that
tab drag the same way. Only what the provider reported can be arranged, so a
reading that turns up later (an EV range on a car that was parked unplugged)
joins the end rather than displacing the arrangement.
- **Car detail** — all car spec fields (engine / transmission / differential oil,
brake fluid, coolant, VIN, fuel type, …) plus tabbed histories, each with an
optional file attachment and add/edit/delete gated by your access level:
@@ -121,8 +126,14 @@ Config (`server/.env`, copy from `.env.example`):
the certificate's valid-until, which drives the next-due date.
- **Maintenance** — workshop visits and repairs (type/status, workshop, parts,
labour + parts cost, invoice, warranty-until).
- **Fuel** — refills with a summary panel (average / best / worst consumption,
cost per km, price per litre), measured between full tanks.
- **Fuel cost** — refills with a summary panel (average / best / worst
consumption, cost per km, price per litre), measured between full tanks.
- **Charging cost** — the same log for an electric car: charges in kWh with
consumption in kWh/100km, km per kWh, cost per km and price per kWh,
measured between charges to the car's usual full point. Partial charges
still count towards the cost and roll into the next full one, and a charge
taken without logging it (flagged on the next session) leaves that window
uncomputed rather than reporting an implausible figure.
- **Documents** — insurance, registration, road tax, … with a renewal badge.
- **Parts** — the per-car parts catalog.
- **Reminders** — date/odometer, one-off or recurring; server-derived ones are
+11
View File
@@ -168,6 +168,16 @@ export const api = {
request(`/fuel-entries/${id}`, { method: "PATCH", body: JSON.stringify(body) }),
deleteFuel: (id) => request(`/fuel-entries/${id}`, { method: "DELETE" }),
// Charging — the EV counterpart of fuel, on the same terms: the kWh/100km
// figures and the charging-stats rollup are derived server-side from the full
// history, so nothing here is stored.
listCarCharging: (carId) => request(`/cars/${carId}/charging-sessions`),
getCarChargingStats: (carId) => request(`/cars/${carId}/charging-stats`),
createCharging: (body) => request("/charging-sessions", { method: "POST", body: JSON.stringify(body) }),
updateCharging: (id, body) =>
request(`/charging-sessions/${id}`, { method: "PATCH", body: JSON.stringify(body) }),
deleteCharging: (id) => request(`/charging-sessions/${id}`, { method: "DELETE" }),
// Maintenance log — workshop visits and repairs (not the service schedule).
listCarMaintenance: (carId) => request(`/cars/${carId}/maintenance`),
createMaintenance: (body) => request("/maintenance", { method: "POST", body: JSON.stringify(body) }),
@@ -190,6 +200,7 @@ export const api = {
technical: attachment("/technical-checks"),
maintenance: attachment("/maintenance"),
fuel: attachment("/fuel-entries"),
charging: attachment("/charging-sessions"),
parts: attachment("/parts"),
},
@@ -0,0 +1,147 @@
<script setup>
// One charging session. The EV counterpart of FuelFormModal and deliberately
// the same form: energy in place of litres, and a charge to the car's usual full
// point in place of the full tank, which is what makes the session count towards
// the kWh/100km figures.
import { ref, computed } from "vue";
import { api } from "../api";
import { applyAttachment } from "../lib/attachment.js";
import { t, tSplit } from "../i18n";
import AttachmentField from "./AttachmentField.vue";
import Modal from "./Modal.vue";
const props = defineProps({
carId: { type: String, required: true },
entry: { type: Object, default: null },
});
const emit = defineEmits(["saved", "close"]);
const isEdit = !!props.entry;
const saving = ref(false);
const error = ref("");
const form = ref({
date: props.entry ? toDateInput(props.entry.date) : new Date().toISOString().slice(0, 10),
km: props.entry?.km ?? "",
kwh: props.entry?.kwh ?? "",
cost: props.entry?.cost ?? "",
// A charge to the usual full point is the one that makes the session count
// towards efficiency, so it is the default — as the full tank is for fuel.
fullCharge: props.entry ? props.entry.fullCharge : true,
missedSession: props.entry ? props.entry.missedSession : false,
location: props.entry?.location ?? "",
notes: props.entry?.notes ?? "",
});
const file = ref(null);
const removeFile = ref(false);
function toDateInput(value) {
const d = new Date(value);
return isNaN(d) ? "" : d.toISOString().slice(0, 10);
}
const pricePerKwh = computed(() => {
const k = Number(form.value.kwh);
const c = Number(form.value.cost);
if (!k || !c) return null;
return (c / k).toFixed(3);
});
async function submit() {
saving.value = true;
error.value = "";
try {
const saved = await (isEdit
? api.updateCharging(props.entry.id, payload())
: api.createCharging(payload()));
emit("saved", await applyAttachment(api.files.charging, saved, {
file: file.value,
remove: removeFile.value,
}));
} catch (e) {
error.value = e.message;
} finally {
saving.value = false;
}
}
function payload() {
return {
car: props.carId,
date: new Date(form.value.date).toISOString(),
km: form.value.km ? Number(form.value.km) : 0,
kwh: form.value.kwh ? Number(form.value.kwh) : 0,
cost: form.value.cost ? Number(form.value.cost) : 0,
fullCharge: form.value.fullCharge,
missedSession: form.value.missedSession,
location: form.value.location.trim(),
notes: form.value.notes.trim(),
};
}
</script>
<template>
<Modal :title="isEdit ? t('forms.charging.editTitle') : t('forms.charging.addTitle')" @close="emit('close')">
<p v-if="error" class="mb-3 rounded-control bg-danger-soft px-3 py-2 text-sm font-medium text-danger">{{ error }}</p>
<form class="space-y-3" @submit.prevent="submit">
<div class="grid grid-cols-2 gap-2">
<div>
<label class="dh-label">{{ t("forms.charging.date") }}</label>
<input v-model="form.date" type="date" required class="dh-input data" />
</div>
<div>
<label class="dh-label">{{ t("forms.charging.odometer") }}</label>
<input v-model="form.km" type="number" min="1" required placeholder="16138" class="dh-input data" />
</div>
</div>
<div class="grid grid-cols-2 gap-2">
<div>
<label class="dh-label">{{ t("forms.charging.kwh") }}</label>
<input v-model="form.kwh" type="number" step="0.01" min="0.01" required placeholder="42.5" class="dh-input data" />
</div>
<div>
<label class="dh-label">{{ t("forms.charging.cost") }}</label>
<input v-model="form.cost" type="number" step="0.01" min="0" placeholder="85.00" class="dh-input data" />
</div>
</div>
<p v-if="pricePerKwh" class="text-xs text-muted">
{{ tSplit("forms.charging.pricePerKwh", "price").before
}}<span class="data text-strong">{{ pricePerKwh }}</span>{{ tSplit("forms.charging.pricePerKwh", "price").after }}
</p>
<fieldset class="rounded-control border border-subtle p-3">
<legend class="eyebrow px-1">{{ t("forms.charging.battery") }}</legend>
<label class="flex items-center gap-2 py-1 text-sm text-body">
<input type="checkbox" v-model="form.fullCharge" class="accent-[var(--accent)]" /> {{ t("forms.charging.fullCharge") }}
</label>
<label class="flex items-center gap-2 py-1 text-sm text-body">
<input type="checkbox" v-model="form.missedSession" class="accent-[var(--accent)]" /> {{ t("forms.charging.missedSession") }}
</label>
<p class="mt-1.5 text-xs text-muted">{{ t("forms.charging.batteryHint") }}</p>
</fieldset>
<div class="grid grid-cols-2 gap-2">
<div>
<label class="dh-label">{{ t("forms.charging.location") }}</label>
<input v-model="form.location" :placeholder="t('forms.charging.locationPlaceholder')" class="dh-input" />
</div>
<div>
<label class="dh-label">{{ t("forms.charging.notes") }}</label>
<input v-model="form.notes" class="dh-input" />
</div>
</div>
<AttachmentField v-model:file="file" v-model:remove="removeFile" :record="entry" :legend="t('forms.charging.attachmentLegend')" />
<div class="mt-4 flex justify-end gap-2">
<button type="button" class="dh-btn dh-btn-ghost" @click="emit('close')">{{ t("common.cancel") }}</button>
<button type="submit" :disabled="saving" class="dh-btn dh-btn-primary">
{{ saving ? t("common.saving") : isEdit ? t("common.saveChanges") : t("forms.charging.submit") }}
</button>
</div>
</form>
</Modal>
</template>
+100 -3
View File
@@ -179,6 +179,85 @@ function toggleCard(id) {
}
}
// --- Arranging the headline readings ---
//
// The readings drag into any order, saved on drop. Stored on the car, like the
// arrangement of the Information rows, rather than per device the way the
// collapsed cards above are: it is a layout choice everyone the car is shared
// with sees, not a reading habit of this browser.
//
// Only the readings the provider actually reported can be arranged, so the
// stored list is a subset; one that turns up later — an EV range on a car that
// was parked unplugged — follows the arranged ones.
const metrics = ref([]);
watch(
[() => snap.value?.metrics, () => props.car.metricOrder],
([reported, order]) => {
const rank = new Map((order || []).map((key, i) => [key, i]));
const list = [...(reported || [])];
list.sort((a, b) => {
const ra = rank.has(a.key) ? rank.get(a.key) : Infinity;
const rb = rank.has(b.key) ? rank.get(b.key) : Infinity;
return ra - rb; // equal ranks (both unarranged) keep the reported order
});
metrics.value = list;
},
{ immediate: true }
);
// Same native drag events as the garage and the Information rows, so also
// pointer-only, and it needs write access like every other choice on the car.
const canArrangeMetrics = computed(() => props.canWrite && metrics.value.length > 1);
const dragMetric = ref(""); // reading being dragged
const dropMetric = ref(""); // reading it is currently hovering over
let metricsMoved = false; // the row changed during this drag and isn't saved yet
function onMetricDragStart(key, e) {
dragMetric.value = key;
metricsMoved = false;
e.dataTransfer.effectAllowed = "move";
// Firefox only starts a drag once something is on the transfer.
e.dataTransfer.setData("text/plain", key);
}
// Reorder live as the pointer crosses readings, so the row shows the
// arrangement you are about to get. dragenter fires again for every child
// element inside the same reading, so only a genuinely new one moves anything.
function onMetricDragEnter(key) {
if (!dragMetric.value || key === dragMetric.value || dropMetric.value === key) return;
dropMetric.value = key;
const list = metrics.value;
const from = list.findIndex((m) => m.key === dragMetric.value);
const to = list.findIndex((m) => m.key === key);
if (from < 0 || to < 0) return;
list.splice(to, 0, ...list.splice(from, 1));
metricsMoved = true;
}
// Called from both drop and dragend: a reading released in the gap between two
// of them never produces a drop, and leaving that arrangement unsaved would
// quietly undo itself on the next load.
async function commitMetricOrder() {
dragMetric.value = "";
dropMetric.value = "";
if (!metricsMoved) return;
metricsMoved = false;
error.value = "";
try {
const car = await api.updateCarView(props.car.id, {
metricOrder: metrics.value.map((m) => m.key),
});
// Hand the car back up so the page holds one copy of it — the watch above
// then rebuilds this row from what was actually stored.
emit("car-updated", car);
} catch (e) {
// The arrangement didn't stick; say so and refetch rather than leaving the
// panel showing an order the server doesn't have.
error.value = e.message;
await load();
}
}
function metricLabel(key) {
return t(`car.provider.metrics.${key}`);
}
@@ -234,17 +313,35 @@ onMounted(async () => {
</div>
<template v-else>
<!-- Headline readings -->
<div v-if="snap.metrics?.length" class="dh-card mb-4 p-6">
<!-- Headline readings. They drag into any order with write access;
the arrangement belongs to the car. -->
<div v-if="metrics.length" class="dh-card mb-4 p-6">
<p class="eyebrow mb-3">{{ t("car.provider.readings") }}</p>
<dl class="grid grid-cols-2 gap-4 text-sm sm:grid-cols-4">
<div v-for="m in snap.metrics" :key="m.key">
<div
v-for="m in metrics"
:key="m.key"
:draggable="canArrangeMetrics"
:title="canArrangeMetrics ? t('car.provider.dragHint') : ''"
class="-m-2 rounded-control p-2 transition-shadow duration-150"
:class="[
canArrangeMetrics ? 'cursor-grab hover:bg-sunken active:cursor-grabbing' : '',
dragMetric === m.key ? 'opacity-50' : '',
dropMetric === m.key ? 'ring-2 ring-accent' : '',
]"
@dragstart="onMetricDragStart(m.key, $event)"
@dragenter.prevent="onMetricDragEnter(m.key)"
@dragover.prevent
@drop.prevent="commitMetricOrder"
@dragend="commitMetricOrder"
>
<dt class="eyebrow">{{ metricLabel(m.key) }}</dt>
<dd class="mt-0.5 data text-lg font-bold text-strong">
{{ m.value }}<span v-if="m.unit" class="ml-1 text-sm font-medium text-muted">{{ m.unit }}</span>
</dd>
</div>
</dl>
<p v-if="canArrangeMetrics" class="mt-3 text-xs text-muted">{{ t("car.provider.dragHint") }}</p>
</div>
<!-- The provider's odometer is ahead of the stored one: offer to take it. -->
+57 -3
View File
@@ -269,7 +269,8 @@
"services": "Servicehistorik",
"technical": "Synshistorik",
"maintenance": "Værksted",
"fuel": "Brændstof",
"fuel": "Brændstofudgifter",
"charging": "Opladningsudgifter",
"documents": "Dokumenter",
"parts": "Reservedelskatalog",
"reminders": "Påmindelser"
@@ -292,6 +293,7 @@
"updated": "Opdateret {time}",
"vehicle": "Køretøj",
"readings": "Aktuelle målinger",
"dragHint": "Træk en aflæsning for at ændre rækkefølgen.",
"noData": "{label} returnerede ingen data for denne bil.",
"raw": "Rå svar",
"allFields": "Alle oplyste felter",
@@ -402,7 +404,7 @@
},
"fuel": {
"title": "Brændstof",
"title": "Brændstofudgifter",
"subtitle": "Forbruget måles mellem fulde tanke.",
"add": "Registrér tankning",
"empty": "Ingen tankninger registreret endnu.",
@@ -430,6 +432,35 @@
"confirmDelete": "Slet denne tankning?"
},
"charging": {
"title": "Opladningsudgifter",
"subtitle": "Forbruget måles mellem fulde opladninger.",
"add": "Registrér opladning",
"empty": "Ingen opladninger registreret endnu.",
"average": "Gennemsnit",
"best": "Bedste",
"worst": "Værste",
"costPerKm": "Pris pr. km",
"sessions": "Opladninger",
"totalKwh": "Energi i alt",
"totalSpent": "Brugt i alt",
"trackedDistance": "Målt distance",
"avgPrice": "Gns. pris {price}/kWh",
"needTwoCharges": "Registrér mindst to fulde opladninger for at se forbrugstal.",
"colDate": "Dato",
"colKm": "Km",
"colKwh": "kWh",
"colCost": "Pris",
"colPerKwh": "Pr. kWh",
"colDistance": "Distance",
"colConsumption": "Forbrug",
"colLocation": "Ladepunkt",
"colFile": "Fil",
"partial": "delvis",
"gap": "hul",
"confirmDelete": "Slet denne opladning?"
},
"documents": {
"title": "Dokumenter",
"subtitle": "Forsikring, miljøattester og andre papirer med fornyelsesdatoer.",
@@ -472,7 +503,7 @@
"delete": {
"title": "Slet denne bil?",
"body": "Dette sletter {name} permanent sammen med alt, der er registreret på den — {services}, {maintenance}, {fuel}, {documents} og {parts}. Det kan ikke fortrydes.",
"body": "Dette sletter {name} permanent sammen med alt, der er registreret på den — {services}, {maintenance}, {fuel}, {charging}, {documents} og {parts}. Det kan ikke fortrydes.",
"services": {
"one": "{n} servicepost",
"other": "{n} serviceposter"
@@ -485,6 +516,10 @@
"one": "{n} tankning",
"other": "{n} tankninger"
},
"charging": {
"one": "{n} opladning",
"other": "{n} opladninger"
},
"documents": {
"one": "{n} dokument",
"other": "{n} dokumenter"
@@ -621,6 +656,25 @@
"submit": "Registrér tankning"
},
"charging": {
"addTitle": "Registrér opladning",
"editTitle": "Redigér opladning",
"date": "Dato",
"odometer": "Kilometerstand (km)",
"kwh": "Energi (kWh)",
"cost": "Pris",
"pricePerKwh": "Det er {price} pr. kWh.",
"battery": "Batteri",
"fullCharge": "Ladet helt op",
"missedSession": "En opladning før denne blev ikke registreret",
"batteryHint": "Forbruget måles mellem fulde opladninger. Delvise opladninger tæller stadig med i prisen og indgår i den næste fulde.",
"location": "Ladepunkt",
"locationPlaceholder": "Hjemme",
"notes": "Noter",
"attachmentLegend": "Kvittering",
"submit": "Gem opladning"
},
"maintenance": {
"addTitle": "Registrér værkstedsbesøg",
"editTitle": "Rediger værkstedsbesøg",
+57 -3
View File
@@ -344,7 +344,8 @@
"services": "Service history",
"technical": "Technical check history",
"maintenance": "Maintenance",
"fuel": "Fuel",
"fuel": "Fuel cost",
"charging": "Charging cost",
"documents": "Documents",
"parts": "Parts catalog",
"reminders": "Reminders"
@@ -367,6 +368,7 @@
"updated": "Updated {time}",
"vehicle": "Vehicle",
"readings": "Current readings",
"dragHint": "Drag a reading to rearrange them.",
"noData": "{label} returned no data for this car.",
"raw": "Raw response",
"allFields": "All reported fields",
@@ -477,7 +479,7 @@
},
"fuel": {
"title": "Fuel",
"title": "Fuel cost",
"subtitle": "Consumption is measured between full tanks.",
"add": "Log refill",
"empty": "No refills logged yet.",
@@ -505,6 +507,35 @@
"confirmDelete": "Delete this refill?"
},
"charging": {
"title": "Charging cost",
"subtitle": "Consumption is measured between full charges.",
"add": "Log charge",
"empty": "No charges logged yet.",
"average": "Average",
"best": "Best",
"worst": "Worst",
"costPerKm": "Cost per km",
"sessions": "Charges",
"totalKwh": "Total energy",
"totalSpent": "Total spent",
"trackedDistance": "Tracked distance",
"avgPrice": "Avg. price {price}/kWh",
"needTwoCharges": "Log at least two full charges to see consumption figures.",
"colDate": "Date",
"colKm": "Km",
"colKwh": "kWh",
"colCost": "Cost",
"colPerKwh": "Per kWh",
"colDistance": "Distance",
"colConsumption": "Consumption",
"colLocation": "Charge point",
"colFile": "File",
"partial": "partial",
"gap": "gap",
"confirmDelete": "Delete this charge?"
},
"documents": {
"title": "Documents",
"subtitle": "Insurance, pollution certificates and other paperwork with renewal dates.",
@@ -547,7 +578,7 @@
"delete": {
"title": "Delete this car?",
"body": "This permanently deletes {name} and everything logged against it — {services}, {maintenance}, {fuel}, {documents} and {parts}. This cannot be undone.",
"body": "This permanently deletes {name} and everything logged against it — {services}, {maintenance}, {fuel}, {charging}, {documents} and {parts}. This cannot be undone.",
"services": {
"one": "{n} service record",
"other": "{n} service records"
@@ -560,6 +591,10 @@
"one": "{n} refill",
"other": "{n} refills"
},
"charging": {
"one": "{n} charge",
"other": "{n} charges"
},
"documents": {
"one": "{n} document",
"other": "{n} documents"
@@ -696,6 +731,25 @@
"submit": "Log refill"
},
"charging": {
"addTitle": "Log charge",
"editTitle": "Edit charge",
"date": "Date",
"odometer": "Odometer (km)",
"kwh": "Energy (kWh)",
"cost": "Cost",
"pricePerKwh": "That is {price} per kWh.",
"battery": "Battery",
"fullCharge": "Charged to full",
"missedSession": "A charge before this one was not logged",
"batteryHint": "Consumption is measured between full charges. Partial charges still count towards the cost, and roll into the next full one.",
"location": "Charge point",
"locationPlaceholder": "Home",
"notes": "Notes",
"attachmentLegend": "Receipt",
"submit": "Save charge"
},
"maintenance": {
"addTitle": "Log workshop visit",
"editTitle": "Edit workshop visit",
+57 -3
View File
@@ -273,7 +273,8 @@
"services": "Historia serwisowa",
"technical": "Historia przeglądów",
"maintenance": "Naprawy",
"fuel": "Paliwo",
"fuel": "Koszty paliwa",
"charging": "Koszty ładowania",
"documents": "Dokumenty",
"parts": "Katalog części",
"reminders": "Przypomnienia"
@@ -296,6 +297,7 @@
"updated": "Zaktualizowano {time}",
"vehicle": "Pojazd",
"readings": "Aktualne odczyty",
"dragHint": "Przeciągnij odczyt, aby zmienić ich kolejność.",
"noData": "{label} nie zwróciło żadnych danych dla tego samochodu.",
"raw": "Surowa odpowiedź",
"allFields": "Wszystkie zgłoszone pola",
@@ -406,7 +408,7 @@
},
"fuel": {
"title": "Paliwo",
"title": "Koszty paliwa",
"subtitle": "Zużycie liczone jest między pełnymi bakami.",
"add": "Zapisz tankowanie",
"empty": "Brak zapisanych tankowań.",
@@ -434,6 +436,35 @@
"confirmDelete": "Usunąć to tankowanie?"
},
"charging": {
"title": "Koszty ładowania",
"subtitle": "Zużycie liczone jest między pełnymi ładowaniami.",
"add": "Zapisz ładowanie",
"empty": "Brak zapisanych ładowań.",
"average": "Średnio",
"best": "Najlepsze",
"worst": "Najgorsze",
"costPerKm": "Koszt na km",
"sessions": "Ładowania",
"totalKwh": "Łączna energia",
"totalSpent": "Łącznie wydano",
"trackedDistance": "Zmierzony dystans",
"avgPrice": "Śr. cena {price}/kWh",
"needTwoCharges": "Zapisz co najmniej dwa pełne ładowania, aby zobaczyć zużycie.",
"colDate": "Data",
"colKm": "Km",
"colKwh": "kWh",
"colCost": "Koszt",
"colPerKwh": "Za kWh",
"colDistance": "Dystans",
"colConsumption": "Zużycie",
"colLocation": "Ładowarka",
"colFile": "Plik",
"partial": "częściowe",
"gap": "przerwa",
"confirmDelete": "Usunąć to ładowanie?"
},
"documents": {
"title": "Dokumenty",
"subtitle": "Ubezpieczenie, zaświadczenia i inne dokumenty z terminami odnowienia.",
@@ -476,7 +507,7 @@
"delete": {
"title": "Usunąć ten samochód?",
"body": "To trwale usunie {name} i wszystko, co zostało w nim zapisane — {services}, {maintenance}, {fuel}, {documents} i {parts}. Tej operacji nie można cofnąć.",
"body": "To trwale usunie {name} i wszystko, co zostało w nim zapisane — {services}, {maintenance}, {fuel}, {charging}, {documents} i {parts}. Tej operacji nie można cofnąć.",
"services": {
"one": "{n} wpis serwisowy",
"few": "{n} wpisy serwisowe",
@@ -495,6 +526,10 @@
"many": "{n} tankowań",
"other": "{n} tankowania"
},
"charging": {
"one": "{n} ładowanie",
"other": "{n} ładowań"
},
"documents": {
"one": "{n} dokument",
"few": "{n} dokumenty",
@@ -635,6 +670,25 @@
"submit": "Zapisz tankowanie"
},
"charging": {
"addTitle": "Zapisz ładowanie",
"editTitle": "Edytuj ładowanie",
"date": "Data",
"odometer": "Przebieg (km)",
"kwh": "Energia (kWh)",
"cost": "Koszt",
"pricePerKwh": "To {price} za kWh.",
"battery": "Akumulator",
"fullCharge": "Naładowany do pełna",
"missedSession": "Wcześniejsze ładowanie nie zostało zapisane",
"batteryHint": "Zużycie liczone jest między pełnymi ładowaniami. Ładowania częściowe wliczają się do kosztów i doliczają do kolejnego pełnego.",
"location": "Ładowarka",
"locationPlaceholder": "Dom",
"notes": "Notatki",
"attachmentLegend": "Paragon",
"submit": "Zapisz ładowanie"
},
"maintenance": {
"addTitle": "Zapisz wizytę w warsztacie",
"editTitle": "Edytuj wizytę w warsztacie",
+18
View File
@@ -135,6 +135,24 @@ export function formatKmPerLiter(value) {
return Number(value).toFixed(2) + " km/L";
}
// The charging equivalents of the three above. Energy keeps two decimals like
// litres — a 7.35 kWh top-up is a real number off a charge point — and the
// consumption figure one, for the same reason tanks do.
export function formatKwh(value) {
if (value == null || value === "") return "—";
return Number(value).toFixed(2) + " kWh";
}
export function formatConsumptionKwh(value) {
if (value == null) return "—";
return Number(value).toFixed(1) + " kWh/100km";
}
export function formatKmPerKwh(value) {
if (value == null) return "—";
return Number(value).toFixed(2) + " km/kWh";
}
// Document renewal badge, driven by the server's expiry assessment so the client
// never re-derives the date maths.
const EXPIRY_STYLE = {
+171 -1
View File
@@ -9,6 +9,9 @@ import {
formatMoney,
formatConsumption,
formatKmPerLiter,
formatKwh,
formatConsumptionKwh,
formatKmPerKwh,
serviceStatus,
expiryStatus,
reminderStatus,
@@ -19,6 +22,7 @@ import ServiceFormModal from "../components/ServiceFormModal.vue";
import TechnicalCheckFormModal from "../components/TechnicalCheckFormModal.vue";
import PartFormModal from "../components/PartFormModal.vue";
import FuelFormModal from "../components/FuelFormModal.vue";
import ChargingFormModal from "../components/ChargingFormModal.vue";
import MaintenanceFormModal from "../components/MaintenanceFormModal.vue";
import DocumentFormModal from "../components/DocumentFormModal.vue";
import ReminderFormModal from "../components/ReminderFormModal.vue";
@@ -35,6 +39,8 @@ const technicalChecks = ref([]);
const parts = ref([]);
const fuel = ref([]);
const fuelStats = ref(null);
const charging = ref([]);
const chargingStats = ref(null);
const maintenance = ref([]);
const documents = ref([]);
const reminders = ref([]);
@@ -51,6 +57,8 @@ const showPart = ref(false);
const editingPart = ref(null);
const showFuel = ref(false);
const editingFuel = ref(null);
const showCharging = ref(false);
const editingCharging = ref(null);
const showMaintenance = ref(false);
const editingMaintenance = ref(null);
const showDocument = ref(false);
@@ -119,6 +127,7 @@ const TABS = computed(() =>
{ key: "technical", label: t("car.tabs.technical") },
{ key: "maintenance", label: t("car.tabs.maintenance") },
{ key: "fuel", label: t("car.tabs.fuel") },
{ key: "charging", label: t("car.tabs.charging") },
{ key: "documents", label: t("car.tabs.documents") },
{ key: "parts", label: t("car.tabs.parts") },
{ key: "reminders", label: t("car.tabs.reminders") },
@@ -142,7 +151,8 @@ watch(TABS, (tabs) => {
// the page rearrange under the pointer between clicks.
const showViewPicker = ref(false);
const HIDEABLE_TABS = [
"provider", "services", "technical", "maintenance", "fuel", "documents", "parts", "reminders",
"provider", "services", "technical", "maintenance", "fuel", "charging",
"documents", "parts", "reminders",
];
// The Information rows, in their default order. Keys mirror hideableCarFields
// in the API's cars.go — the server rejects anything else.
@@ -324,6 +334,8 @@ async function load() {
parts.value,
fuel.value,
fuelStats.value,
charging.value,
chargingStats.value,
maintenance.value,
documents.value,
reminders.value,
@@ -334,6 +346,8 @@ async function load() {
api.listCarParts(props.id),
api.listCarFuel(props.id),
api.getCarFuelStats(props.id),
api.listCarCharging(props.id),
api.getCarChargingStats(props.id),
api.listCarMaintenance(props.id),
api.listCarDocuments(props.id),
api.listCarReminders(props.id),
@@ -459,6 +473,42 @@ async function deleteFuel(id) {
}
}
// --- charging ---
//
// The same handling as fuel, for the same reasons: a session re-derives every
// window it touches and advances the car's odometer, so the whole set is
// refetched rather than the one list that was edited.
function openAddCharging() {
editingCharging.value = null;
showCharging.value = true;
}
function openEditCharging(c) {
editingCharging.value = c;
showCharging.value = true;
}
async function reloadCharging() {
[charging.value, chargingStats.value, car.value, reminders.value] = await Promise.all([
api.listCarCharging(props.id),
api.getCarChargingStats(props.id),
api.getCar(props.id),
api.listCarReminders(props.id),
]);
}
async function onChargingSaved() {
showCharging.value = false;
editingCharging.value = null;
await reloadCharging();
}
async function deleteCharging(id) {
if (!confirm(t("car.charging.confirmDelete"))) return;
try {
await api.deleteCharging(id);
await reloadCharging();
} catch (e) {
error.value = e.message;
}
}
// --- maintenance ---
function openAddMaintenance() {
editingMaintenance.value = null;
@@ -1057,6 +1107,118 @@ onMounted(load);
</div>
</section>
<!-- Charging cost. The EV counterpart of Fuel: energy in place of litres,
and a charge to the usual full point in place of the full tank. -->
<section v-else-if="activeTab === 'charging'">
<div class="mb-3 flex items-center justify-between">
<div>
<h2 class="text-lg font-bold tracking-[-0.02em] text-strong">{{ t("car.charging.title") }}</h2>
<p class="text-sm text-muted">{{ t("car.charging.subtitle") }}</p>
</div>
<button v-if="canWrite" class="dh-btn dh-btn-primary !px-3 !py-1.5" @click="openAddCharging">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" class="h-4 w-4"><path stroke-linecap="round" stroke-linejoin="round" d="M12 5v14M5 12h14" /></svg>
{{ t("car.charging.add") }}
</button>
</div>
<!-- Rollup -->
<div v-if="chargingStats && chargingStats.entries > 0" class="dh-card mb-4 p-6">
<dl class="grid grid-cols-2 gap-4 text-sm sm:grid-cols-4">
<div>
<dt class="eyebrow">{{ t("car.charging.average") }}</dt>
<dd class="mt-0.5 data text-lg font-bold text-strong">{{ formatConsumptionKwh(chargingStats.avgConsumptionKwh100) }}</dd>
<dd class="text-xs text-muted">{{ formatKmPerKwh(chargingStats.avgKmPerKwh) }}</dd>
</div>
<div>
<dt class="eyebrow">{{ t("car.charging.best") }}</dt>
<dd class="mt-0.5 data font-medium text-success">{{ formatConsumptionKwh(chargingStats.bestConsumptionKwh100) }}</dd>
</div>
<div>
<dt class="eyebrow">{{ t("car.charging.worst") }}</dt>
<dd class="mt-0.5 data font-medium text-danger">{{ formatConsumptionKwh(chargingStats.worstConsumptionKwh100) }}</dd>
</div>
<div>
<dt class="eyebrow">{{ t("car.charging.costPerKm") }}</dt>
<dd class="mt-0.5 data font-medium text-strong">{{ formatMoney(chargingStats.costPerKm) }}</dd>
</div>
<div>
<dt class="eyebrow">{{ t("car.charging.sessions") }}</dt>
<dd class="mt-0.5 data font-medium text-strong">{{ chargingStats.entries }}</dd>
</div>
<div>
<dt class="eyebrow">{{ t("car.charging.totalKwh") }}</dt>
<dd class="mt-0.5 data font-medium text-strong">{{ formatKwh(chargingStats.totalKwh) }}</dd>
</div>
<div>
<dt class="eyebrow">{{ t("car.charging.totalSpent") }}</dt>
<dd class="mt-0.5 data font-medium text-strong">{{ formatMoney(chargingStats.totalCost) }}</dd>
</div>
<div>
<dt class="eyebrow">{{ t("car.charging.trackedDistance") }}</dt>
<dd class="mt-0.5 data font-medium text-strong">{{ formatKm(chargingStats.trackedDistanceKm) }}</dd>
<dd class="text-xs text-muted">{{ t("car.charging.avgPrice", { price: formatMoney(chargingStats.avgPricePerKwh) }) }}</dd>
</div>
</dl>
<p v-if="!chargingStats.avgConsumptionKwh100" class="mt-4 text-xs text-muted">
{{ t("car.charging.needTwoCharges") }}
</p>
</div>
<div v-if="charging.length === 0" class="rounded-card border border-dashed border-default p-8 text-center text-muted">
{{ t("car.charging.empty") }}
</div>
<div v-else class="dh-card overflow-x-auto p-0">
<table class="min-w-full text-sm">
<thead class="bg-sunken text-left">
<tr class="[&>th]:eyebrow [&>th]:px-4 [&>th]:py-3">
<th>{{ t("car.charging.colDate") }}</th>
<th>{{ t("car.charging.colKm") }}</th>
<th class="!text-right">{{ t("car.charging.colKwh") }}</th>
<th class="!text-right">{{ t("car.charging.colCost") }}</th>
<th class="!text-right">{{ t("car.charging.colPerKwh") }}</th>
<th class="!text-right">{{ t("car.charging.colDistance") }}</th>
<th class="!text-right">{{ t("car.charging.colConsumption") }}</th>
<th>{{ t("car.charging.colLocation") }}</th>
<th>{{ t("car.charging.colFile") }}</th>
<th v-if="canWrite"></th>
</tr>
</thead>
<tbody class="divide-y divide-subtle">
<tr v-for="c in charging" :key="c.id" class="transition-colors hover:bg-sunken">
<td class="whitespace-nowrap px-4 py-3 data font-medium text-strong">
{{ formatDate(c.date) }}
<span v-if="!c.fullCharge" class="ml-1 text-xs font-normal text-muted">{{ t("car.charging.partial") }}</span>
<span v-if="c.missedSession" class="ml-1 text-xs font-normal text-warning">{{ t("car.charging.gap") }}</span>
</td>
<td class="whitespace-nowrap px-4 py-3 data text-body">{{ formatKm(c.km) }}</td>
<td class="whitespace-nowrap px-4 py-3 text-right data text-body">{{ formatKwh(c.kwh) }}</td>
<td class="whitespace-nowrap px-4 py-3 text-right data text-body">{{ c.cost ? formatMoney(c.cost) : t("common.empty") }}</td>
<td class="whitespace-nowrap px-4 py-3 text-right data text-muted">{{ formatMoney(c.pricePerKwh) }}</td>
<td class="whitespace-nowrap px-4 py-3 text-right data text-muted">{{ c.distanceKm ? formatKm(c.distanceKm) : t("common.empty") }}</td>
<td class="whitespace-nowrap px-4 py-3 text-right data font-medium" :class="c.consumptionKwh100 ? 'text-strong' : 'text-muted'">
{{ formatConsumptionKwh(c.consumptionKwh100) }}
</td>
<td class="px-4 py-3 text-body">
{{ c.location || t("common.empty") }}
<div v-if="c.notes" class="text-xs text-muted">{{ c.notes }}</div>
</td>
<td class="whitespace-nowrap px-4 py-3">
<button v-if="c.hasFile" class="text-xs font-medium text-brandtext hover:underline" @click="downloadAttachment('charging', c)">
{{ t("common.download") }}
</button>
<span v-else class="text-xs text-muted">{{ t("common.empty") }}</span>
</td>
<td v-if="canWrite" class="whitespace-nowrap px-4 py-3 text-right">
<button class="text-xs font-medium text-brandtext hover:underline" @click="openEditCharging(c)">{{ t("common.edit") }}</button>
<button class="ml-3 text-xs font-medium text-danger hover:underline" @click="deleteCharging(c.id)">{{ t("common.delete") }}</button>
</td>
</tr>
</tbody>
</table>
</div>
</section>
<!-- Documents -->
<section v-else-if="activeTab === 'documents'">
<div class="mb-3 flex items-center justify-between">
@@ -1250,6 +1412,13 @@ onMounted(load);
@saved="onFuelSaved"
@close="showFuel = false"
/>
<ChargingFormModal
v-if="showCharging"
:car-id="id"
:entry="editingCharging"
@saved="onChargingSaved"
@close="showCharging = false"
/>
<MaintenanceFormModal
v-if="showMaintenance"
:car-id="id"
@@ -1334,6 +1503,7 @@ onMounted(load);
services: t("car.delete.services", { n: services.length }),
maintenance: t("car.delete.maintenance", { n: maintenance.length }),
fuel: t("car.delete.fuel", { n: fuel.length }),
charging: t("car.delete.charging", { n: charging.length }),
documents: t("car.delete.documents", { n: documents.length }),
parts: t("car.delete.parts", { n: parts.length }),
}) }}