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
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user