diff --git a/README.md b/README.md index e57d5279..327db442 100644 --- a/README.md +++ b/README.md @@ -145,6 +145,9 @@ The Statistics view shows insight cards and charts for a period of its own: the | Parking locations | Number of distinct parking spots (rounded GPS) | | Electric share today | Estimated share of today's driving on electric power (PHEV only) | | Avg speed | Average moving speed across all GPS points in the period, excluding stopped moments | +| Range on a full battery | What the car would cover on a full battery at the way it was driven: the kilometres between one charge and the next per percent of battery used, times 100, over the period's charges (BEV only). Pairs too short to read, or far off the rest because a charge went unseen between them, are left out, and at least three are needed | +| Distance per charge | The distance usually driven from one charge to the next, as the middle value over the period's charges, so a charge nobody saw does not pull it up. A plug-in hybrid's includes petrol kilometres | +| Typical charge | The average battery level the period's finished charges started from and ended at | --- diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.json index 63da8496..82c99e40 100644 --- a/frontend/src/locales/en.json +++ b/frontend/src/locales/en.json @@ -128,7 +128,10 @@ "batteryVoltageTrend": "12V trend", "parkingLocations": "Parking locations", "electricShare": "Electric share today", - "avgSpeed": "Avg speed" + "avgSpeed": "Avg speed", + "fullBatteryRange": "Range on a full battery", + "distancePerCharge": "Distance per charge", + "chargeHabit": "Typical charge" }, "cardDesc": { "distanceInRange": "Distance the car counted over the selected period, from its own day counter, so it matches the energy used. A car that reports no such counter gets the total of its trips instead.", @@ -141,7 +144,10 @@ "batteryVoltageTrend": "Change in average 12V battery voltage from the start to the end of the selected period. Shows current voltage when less than two days of data are available.", "parkingLocations": "Number of distinct parking spots used across all trips in the selected period, based on rounded GPS coordinates.", "electricShare": "Estimated share of today's driving on electric power, derived from the distance since the last charge versus the total distance today. Only meaningful for PHEV, where the battery can be charged from the grid.", - "avgSpeed": "Average moving speed across all recorded GPS points in the selected period, excluding stopped moments." + "avgSpeed": "Average moving speed across all recorded GPS points in the selected period, excluding stopped moments.", + "fullBatteryRange": "How far the car goes on a full battery at the way you drive, worked out from the charges in the period: the kilometres driven per percent of battery used between one charge and the next, times 100. Pairs too short to read, and pairs far off the rest because a charge went unseen between them, are left out. It needs at least three usable pairs, and is only for a BEV, as a hybrid's distance includes petrol.", + "distancePerCharge": "The distance usually driven from the end of one charge to the end of the next, as the middle value over the charges in the period, so one very long stretch (a charge the app did not see) does not pull it up. It needs at least three charges after the first. A plug-in hybrid's distance includes petrol kilometres.", + "chargeHabit": "The average battery level the finished charges in the period started from and ended at, over those that reported both. It needs at least three charges." }, "chartDesc": { "evChart": "Daily average EV battery state-of-charge over the selected period.", diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.json index a14e8a3f..cab7a3b9 100644 --- a/frontend/src/locales/es.json +++ b/frontend/src/locales/es.json @@ -128,7 +128,10 @@ "batteryVoltageTrend": "Tendencia de 12 V", "parkingLocations": "Ubicaciones de estacionamiento", "electricShare": "Electric share hoy", - "avgSpeed": "Velocidad media" + "avgSpeed": "Velocidad media", + "fullBatteryRange": "Autonomía con la batería llena", + "distancePerCharge": "Distancia por carga", + "chargeHabit": "Carga habitual" }, "cardDesc": { "distanceInRange": "Distancia que el coche ha contado en el período seleccionado, según su propio contador diario, para que coincida con la energía consumida. Si el coche no tiene ese contador, se usa el total de sus viajes.", @@ -141,7 +144,10 @@ "batteryVoltageTrend": "Cambio en el voltaje medio de la batería de 12 V entre el inicio y el final del período seleccionado. Si hay menos de dos días de datos, muestra el voltaje actual.", "parkingLocations": "Número de lugares de estacionamiento distintos utilizados en todos los viajes en el período seleccionado, según coordenadas GPS redondeadas.", "electricShare": "Porcentaje estimado de la conducción reciente realizada con energía eléctrica. Se calcula a partir de la distancia recorrida desde la última carga y la distancia total. Solo es útil para PHEV, cuya batería se puede cargar desde la red.", - "avgSpeed": "Velocidad media durante el período seleccionado, calculada con todos los puntos GPS registrados y excluyendo las paradas." + "avgSpeed": "Velocidad media durante el período seleccionado, calculada con todos los puntos GPS registrados y excluyendo las paradas.", + "fullBatteryRange": "Cuánto recorre el coche con la batería llena según tu forma de conducir, calculado con las cargas del período: los kilómetros recorridos por cada porcentaje de batería usado entre una carga y la siguiente, por 100. Se descartan los pares demasiado cortos para leer y los que se alejan del resto porque entre ellos hubo una carga que no se vio. Hacen falta al menos tres pares utilizables, y solo vale para un BEV, porque la distancia de un híbrido incluye gasolina.", + "distancePerCharge": "La distancia que se recorre normalmente desde el final de una carga hasta el final de la siguiente, como valor central de las cargas del período, de modo que un tramo muy largo (una carga que la app no vio) no la sube. Hacen falta al menos tres cargas después de la primera. La distancia de un híbrido enchufable incluye kilómetros de gasolina.", + "chargeHabit": "El nivel medio de batería con el que empezaron y terminaron las cargas completadas del período, entre las que informaron ambos. Hacen falta al menos tres cargas." }, "chartDesc": { "evChart": "Nivel de carga medio diario de la batería eléctrica durante el período seleccionado.", diff --git a/frontend/src/locales/nl.json b/frontend/src/locales/nl.json index bb54f4d7..2b60ce70 100644 --- a/frontend/src/locales/nl.json +++ b/frontend/src/locales/nl.json @@ -128,7 +128,10 @@ "batteryVoltageTrend": "12V-trend", "parkingLocations": "Parkeerlocaties", "electricShare": "Elektrisch aandeel vandaag", - "avgSpeed": "Gem. snelheid" + "avgSpeed": "Gem. snelheid", + "fullBatteryRange": "Bereik op een volle accu", + "distancePerCharge": "Afstand per lading", + "chargeHabit": "Typische lading" }, "cardDesc": { "distanceInRange": "De afstand die de auto in de geselecteerde periode telde, volgens zijn eigen dagteller, zodat die past bij de verbruikte energie. Een auto zonder zo'n teller krijgt in plaats daarvan het totaal van zijn ritten.", @@ -141,7 +144,10 @@ "batteryVoltageTrend": "Verandering in gemiddelde 12V-accuspanning van het begin tot het einde van de geselecteerde periode. Toont de huidige spanning als er minder dan twee dagen aan data beschikbaar is.", "parkingLocations": "Aantal unieke parkeerplaatsen gebruikt over alle ritten in de geselecteerde periode, gebaseerd op afgeronde GPS-coordinaten.", "electricShare": "Geschat aandeel van de ritten vandaag op elektrisch vermogen, afgeleid van de afstand sinds de laatste laadbeurt versus de totale afstand vandaag. Alleen zichtbaar voor HEV en PHEV.", - "avgSpeed": "Gemiddelde rijsnelheid over alle geregistreerde GPS-punten in de geselecteerde periode, exclusief stilstaande momenten." + "avgSpeed": "Gemiddelde rijsnelheid over alle geregistreerde GPS-punten in de geselecteerde periode, exclusief stilstaande momenten.", + "fullBatteryRange": "Hoe ver de auto komt op een volle accu bij jouw rijstijl, uitgerekend uit de ladingen in de periode: de gereden kilometers per procent gebruikte accu tussen twee ladingen, maal 100. Paren die te kort zijn om te lezen, en paren die ver afwijken omdat er tussendoor een lading niet is gezien, tellen niet mee. Er zijn minstens drie bruikbare paren nodig, en het geldt alleen voor een BEV, omdat de afstand van een hybride ook benzinekilometers bevat.", + "distancePerCharge": "De afstand die meestal wordt gereden van het einde van de ene lading tot het einde van de volgende, als middelste waarde over de ladingen in de periode, zodat één heel lang stuk (een lading die de app niet zag) hem niet omhoog trekt. Er zijn minstens drie ladingen na de eerste nodig. De afstand van een plug-in hybride bevat ook benzinekilometers.", + "chargeHabit": "Het gemiddelde accuniveau waarmee de afgeronde ladingen in de periode begonnen en eindigden, over de ladingen die beide meldden. Er zijn minstens drie ladingen nodig." }, "chartDesc": { "evChart": "Dagelijks gemiddeld EV-accuniveau in de geselecteerde periode.", diff --git a/frontend/src/locales/pt-PT.json b/frontend/src/locales/pt-PT.json index 6c373372..d39a395e 100644 --- a/frontend/src/locales/pt-PT.json +++ b/frontend/src/locales/pt-PT.json @@ -128,7 +128,10 @@ "batteryVoltageTrend": "Tendência dos 12 V", "parkingLocations": "Locais de estacionamento", "electricShare": "Uso elétrico hoje", - "avgSpeed": "Velocidade média" + "avgSpeed": "Velocidade média", + "fullBatteryRange": "Autonomia com a bateria cheia", + "distancePerCharge": "Distância por carregamento", + "chargeHabit": "Carregamento típico" }, "cardDesc": { "distanceInRange": "Distância que o carro contou no período selecionado, pelo próprio contador diário, para corresponder à energia consumida. Se o carro não comunicar esse contador, é usado o total das suas viagens.", @@ -141,7 +144,10 @@ "batteryVoltageTrend": "Variação da tensão média da bateria de 12 V do início ao fim do período selecionado. Mostra a tensão atual quando há menos de dois dias de dados.", "parkingLocations": "Número de lugares de estacionamento distintos usados em todas as viagens do período selecionado, com base em coordenadas GPS arredondadas.", "electricShare": "Estimativa da parte da condução de hoje feita com energia elétrica, calculada a partir da distância desde o último carregamento em relação à distância total de hoje. Só faz sentido para PHEV, em que a bateria pode ser carregada na rede elétrica.", - "avgSpeed": "Velocidade média em movimento considerando todos os pontos GPS registados no período selecionado, sem contar os momentos parado." + "avgSpeed": "Velocidade média em movimento considerando todos os pontos GPS registados no período selecionado, sem contar os momentos parado.", + "fullBatteryRange": "Quanto o carro anda com a bateria cheia consoante a sua condução, calculado com os carregamentos do período: os quilómetros percorridos por ponto de bateria gasto entre um carregamento e o seguinte, vezes 100. Os pares demasiado curtos para ler, e os pares muito afastados do resto porque entre eles houve um carregamento que não foi visto, ficam de fora. São precisos pelo menos três pares utilizáveis, e só vale para um BEV, porque a distância de um híbrido inclui gasolina.", + "distancePerCharge": "A distância que normalmente se percorre do fim de um carregamento ao fim do seguinte, como valor do meio entre os carregamentos do período, para que um troço muito longo (um carregamento que a aplicação não viu) não a puxe para cima. São precisos pelo menos três carregamentos depois do primeiro. A distância de um híbrido plug-in inclui quilómetros de gasolina.", + "chargeHabit": "O nível médio de bateria com que os carregamentos concluídos do período começaram e terminaram, entre os que indicaram os dois. São precisos pelo menos três carregamentos." }, "chartDesc": { "evChart": "Nível de carga médio diário da bateria do EV no período selecionado.", diff --git a/frontend/src/locales/pt.json b/frontend/src/locales/pt.json index 531e82dd..98b15e32 100644 --- a/frontend/src/locales/pt.json +++ b/frontend/src/locales/pt.json @@ -128,7 +128,10 @@ "batteryVoltageTrend": "Tendência dos 12 V", "parkingLocations": "Locais de estacionamento", "electricShare": "Uso elétrico hoje", - "avgSpeed": "Velocidade média" + "avgSpeed": "Velocidade média", + "fullBatteryRange": "Autonomia com a bateria cheia", + "distancePerCharge": "Distância por recarga", + "chargeHabit": "Recarga típica" }, "cardDesc": { "distanceInRange": "Distância que o carro contou no período selecionado, pelo próprio contador diário, para corresponder à energia consumida. Se o carro não informa esse contador, é usado o total das suas viagens.", @@ -141,7 +144,10 @@ "batteryVoltageTrend": "Variação da tensão média da bateria de 12 V do início ao fim do período selecionado. Mostra a tensão atual quando há menos de dois dias de dados.", "parkingLocations": "Número de vagas de estacionamento distintas usadas em todas as viagens do período selecionado, com base em coordenadas GPS arredondadas.", "electricShare": "Estimativa da parte da condução de hoje feita com energia elétrica, calculada a partir da distância desde a última carga em relação à distância total de hoje. Só faz sentido para PHEV, em que a bateria pode ser carregada na rede elétrica.", - "avgSpeed": "Velocidade média em movimento considerando todos os pontos GPS registrados no período selecionado, sem contar os momentos parado." + "avgSpeed": "Velocidade média em movimento considerando todos os pontos GPS registrados no período selecionado, sem contar os momentos parado.", + "fullBatteryRange": "Quanto o carro anda com a bateria cheia do jeito que você dirige, calculado com as recargas do período: os quilômetros rodados por ponto de bateria gasto entre uma recarga e a seguinte, vezes 100. Pares curtos demais para ler, e pares muito fora do resto porque uma recarga não foi vista entre eles, ficam de fora. São necessários pelo menos três pares utilizáveis, e vale só para um BEV, porque a distância de um híbrido inclui gasolina.", + "distancePerCharge": "A distância que normalmente se roda do fim de uma recarga ao fim da seguinte, como valor do meio entre as recargas do período, para que um trecho muito longo (uma recarga que o app não viu) não a puxe para cima. São necessárias pelo menos três recargas depois da primeira. A distância de um híbrido plug-in inclui quilômetros de gasolina.", + "chargeHabit": "O nível médio de bateria com que as recargas concluídas do período começaram e terminaram, entre as que informaram os dois. São necessárias pelo menos três recargas." }, "chartDesc": { "evChart": "Nível de carga médio diário da bateria do EV no período selecionado.", diff --git a/frontend/src/stores/settingsShared.ts b/frontend/src/stores/settingsShared.ts index 72a081e7..f5bcb078 100644 --- a/frontend/src/stores/settingsShared.ts +++ b/frontend/src/stores/settingsShared.ts @@ -145,6 +145,9 @@ export type StatsInsightId = | 'parkingLocations' | 'electricShare' | 'avgSpeed' + | 'fullBatteryRange' + | 'distancePerCharge' + | 'chargeHabit' export type StatsChartId = 'evChart' | 'tyreChart' | 'hybridSocChart' | 'dailyKwhChart' | 'temperatureChart' @@ -165,6 +168,9 @@ export const ALL_STATS_INSIGHT_IDS: StatsInsightId[] = [ 'parkingLocations', 'electricShare', 'avgSpeed', + 'fullBatteryRange', + 'distancePerCharge', + 'chargeHabit', ] export const ALL_STATS_CHART_IDS: StatsChartId[] = [ diff --git a/frontend/src/utils/__tests__/chargeStatistics.spec.ts b/frontend/src/utils/__tests__/chargeStatistics.spec.ts new file mode 100644 index 00000000..8584b140 --- /dev/null +++ b/frontend/src/utils/__tests__/chargeStatistics.spec.ts @@ -0,0 +1,194 @@ +import { describe, it, expect } from 'vitest' +import type { ChargeSession } from '@/services/vehicleApi' +import { + chargeHabit, + chargePairs, + fullBatteryRangeKm, + typicalDistanceBetweenCharges, + type ChargePair, +} from '../chargeStatistics' + +let day = 0 + +// A finished charge: it ended at `endSoc`, with the odometer at `odometerKm`, `day` days after the last. +function session(overrides: Partial = {}): ChargeSession { + day += 1 + const date = `2026-10-${String(day).padStart(2, '0')}` + return { + startedAt: `${date}T20:00:00Z`, + endedAt: `${date}T23:00:00Z`, + startSocPercent: 30, + endSocPercent: 90, + chargingType: 'AC', + odometerKm: 1000, + latitude: null, + longitude: null, + startBatteryKwh: null, + endBatteryKwh: null, + batteryEnergyGainedKwh: null, + maxPowerKw: 7, + ...overrides, + } +} + +// Charges at these odometer readings, each one ending at 90 % and the next one starting at the level given. +function charges(...stops: [odometerKm: number, startSoc: number][]): ChargeSession[] { + day = 0 + return stops.map(([odometerKm, startSoc]) => + session({ odometerKm, startSocPercent: startSoc, endSocPercent: 90 }), + ) +} + +describe('chargePairs', () => { + it('pairs each charge with the next, and says how far and how much battery it took', () => { + const pairs = chargePairs(charges([1000, 30], [1180, 40], [1400, 25])) + + expect(pairs).toEqual([ + { distanceKm: 180, socUsedPercent: 50 }, + { distanceKm: 220, socUsedPercent: 65 }, + ]) + }) + + it('reads the sessions in time order, whichever way the API sends them', () => { + const newestFirst = charges([1000, 30], [1180, 40], [1400, 25]).reverse() + + expect(chargePairs(newestFirst)).toHaveLength(2) + expect(chargePairs(newestFirst)[0]!.distanceKm).toBe(180) + }) + + it('starts no pair from a charge still going', () => { + const list = charges([1000, 30], [1180, 40]) + list[0]!.endedAt = null + + expect(chargePairs(list)).toEqual([]) + }) + + it('keeps the distance of a pair whose levels are missing, without the battery it took', () => { + const list = charges([1000, 30], [1180, 40]) + list[0]!.endSocPercent = null + + expect(chargePairs(list)).toEqual([{ distanceKm: 180, socUsedPercent: null }]) + }) + + it('does not take a level that went up between two charges for a drive', () => { + const list = charges([1000, 30], [1180, 95]) + + expect(chargePairs(list)).toEqual([{ distanceKm: 180, socUsedPercent: null }]) + }) + + it('leaves out a pair with a missing odometer, or one that went backwards', () => { + const noOdometer = charges([1000, 30], [1180, 40]) + noOdometer[1]!.odometerKm = null + const backwards = charges([1000, 30], [900, 40]) + + expect(chargePairs(noOdometer)).toEqual([]) + expect(chargePairs(backwards)).toEqual([]) + }) + + it('has no pair with fewer than two charges', () => { + expect(chargePairs([])).toEqual([]) + expect(chargePairs(charges([1000, 30]))).toEqual([]) + }) +}) + +describe('typicalDistanceBetweenCharges', () => { + const pair = (distanceKm: number): ChargePair => ({ distanceKm, socUsedPercent: 50 }) + + it('is the middle of the distances', () => { + expect(typicalDistanceBetweenCharges([pair(150), pair(200), pair(260)])).toBe(200) + }) + + it('is not pulled up by a charge nobody saw, which makes one long pair', () => { + expect( + typicalDistanceBetweenCharges([pair(150), pair(160), pair(170), pair(180), pair(520)]), + ).toBe(170) + }) + + it('leaves out a split charge: a hop of a few kilometres is not a drive', () => { + expect(typicalDistanceBetweenCharges([pair(0), pair(1), pair(150), pair(200), pair(260)])).toBe( + 200, + ) + }) + + it('is null with fewer than three pairs', () => { + expect(typicalDistanceBetweenCharges([pair(150), pair(200)])).toBeNull() + }) +}) + +describe('fullBatteryRangeKm', () => { + const pair = (distanceKm: number, socUsedPercent: number | null): ChargePair => ({ + distanceKm, + socUsedPercent, + }) + + it('is the distance per percent of battery, times 100, added up over the pairs', () => { + // 150 km on 50 %, 180 km on 60 %, 120 km on 40 %: 3 km per percent, so 300 km on a full battery. + expect(fullBatteryRangeKm([pair(150, 50), pair(180, 60), pair(120, 40)])).toBeCloseTo(300) + }) + + it('counts a long stretch for more than a short one', () => { + // 400 km on 100 % (4 km per percent), 20 km on 10 % (2), 80 km on 20 % (4). + expect(fullBatteryRangeKm([pair(400, 100), pair(20, 10), pair(80, 20)])).toBeCloseTo( + (500 / 130) * 100, + ) + }) + + it('leaves out a pair far above the rest, which spans a charge nobody saw', () => { + // The 400 km on 20 % pair is 20 km per percent against 3 for the others. + expect( + fullBatteryRangeKm([pair(150, 50), pair(180, 60), pair(120, 40), pair(400, 20)]), + ).toBeCloseTo(300) + }) + + it('ignores a pair too short to read, or without its battery', () => { + expect( + fullBatteryRangeKm([ + pair(150, 50), + pair(180, 60), + pair(120, 40), + pair(5, 20), + pair(50, 4), + pair(100, null), + ]), + ).toBeCloseTo(300) + }) + + it('is null with fewer than three pairs to go on', () => { + expect(fullBatteryRangeKm([pair(150, 50), pair(180, 60)])).toBeNull() + }) + + it('is null when too many pairs are far off the middle to keep three', () => { + expect(fullBatteryRangeKm([pair(100, 50), pair(400, 50), pair(900, 50)])).toBeNull() + }) +}) + +describe('chargeHabit', () => { + it('is the average level charges start from and end at', () => { + day = 0 + const list = [ + session({ startSocPercent: 20, endSocPercent: 80 }), + session({ startSocPercent: 30, endSocPercent: 90 }), + session({ startSocPercent: 40, endSocPercent: 100 }), + ] + + expect(chargeHabit(list)).toEqual({ startPercent: 30, endPercent: 90 }) + }) + + it('leaves out a charge still going and one without its levels', () => { + day = 0 + const list = [ + session({ startSocPercent: 20, endSocPercent: 80 }), + session({ startSocPercent: 30, endSocPercent: 90 }), + session({ startSocPercent: 40, endSocPercent: 100 }), + session({ startSocPercent: 50, endSocPercent: 55, endedAt: null }), + session({ startSocPercent: null, endSocPercent: null }), + ] + + expect(chargeHabit(list)).toEqual({ startPercent: 30, endPercent: 90 }) + }) + + it('is null with fewer than three charges to go on', () => { + day = 0 + expect(chargeHabit([session(), session()])).toBeNull() + }) +}) diff --git a/frontend/src/utils/chargeStatistics.ts b/frontend/src/utils/chargeStatistics.ts new file mode 100644 index 00000000..91035635 --- /dev/null +++ b/frontend/src/utils/chargeStatistics.ts @@ -0,0 +1,129 @@ +import type { ChargeSession } from '@/services/vehicleApi' + +/** + * Two charges one after the other, and what happened between them: how far the car was driven (the + * odometer at the end of the older one to the odometer at the end of the newer one, which a charge + * does not move) and how much of the battery that took (the level the older ended at, less the + * level the newer started from). + */ +export interface ChargePair { + distanceKm: number + /** Null when either level is missing, and for a level that went up, which is not a drive. */ + socUsedPercent: number | null +} + +/** A hop shorter than this between two charges is a charge that was split, not a drive. */ +export const MIN_DISTANCE_BETWEEN_CHARGES_KM = 5 + +/** Below these the odometer's whole kilometres and the level's rounding are most of the figure. */ +export const MIN_RANGE_PAIR_DISTANCE_KM = 10 +export const MIN_RANGE_PAIR_SOC_USED = 10 + +/** + * How many charge pairs a figure needs before it is shown: one or two are an anecdote, and a + * single charge the car did not report would be most of it. + */ +export const MIN_PAIRS = 3 + +/** + * How far from the middle one pair's kilometres per percent may be and still count. A charge no + * poll caught between two reported ones gives a pair that spans two charges, with the battery + * having gained in the middle, so its kilometres per percent is far above the rest; the pair that + * far out is left out. + */ +export const RANGE_OUTLIER_FACTOR = 2 + +function finite(value: number | null): value is number { + return value !== null && Number.isFinite(value) +} + +function median(values: number[]): number { + const sorted = [...values].sort((a, b) => a - b) + const middle = Math.floor(sorted.length / 2) + return sorted.length % 2 === 1 ? sorted[middle]! : (sorted[middle - 1]! + sorted[middle]!) / 2 +} + +/** + * Each charge and the next one after it, oldest first. A charge still going has no end yet and + * starts no pair; the one after it does not either, as the car is not where it ended. + */ +export function chargePairs(sessions: ChargeSession[]): ChargePair[] { + const ordered = [...sessions].sort((a, b) => a.startedAt.localeCompare(b.startedAt)) + const pairs: ChargePair[] = [] + for (let i = 0; i < ordered.length - 1; i++) { + const older = ordered[i]! + const newer = ordered[i + 1]! + if (older.endedAt === null || !finite(older.odometerKm) || !finite(newer.odometerKm)) continue + const distanceKm = newer.odometerKm - older.odometerKm + if (distanceKm < 0) continue + + const used = + finite(older.endSocPercent) && finite(newer.startSocPercent) + ? older.endSocPercent - newer.startSocPercent + : null + pairs.push({ distanceKm, socUsedPercent: used !== null && used > 0 ? used : null }) + } + return pairs +} + +/** + * The distance a car typically goes from one charge to the next: the middle of the pairs, so that + * a charge nobody saw, which makes one long pair, does not drag it up. Null with too few pairs. + */ +export function typicalDistanceBetweenCharges(pairs: ChargePair[]): number | null { + const distances = pairs + .map((p) => p.distanceKm) + .filter((km) => km >= MIN_DISTANCE_BETWEEN_CHARGES_KM) + return distances.length >= MIN_PAIRS ? median(distances) : null +} + +/** + * How far the car would go on a full battery at the way it was driven: the kilometres it covered + * per percent of battery between charges, times 100. Only pairs long enough to read are used, the + * ones far off the middle are left out (see {@link RANGE_OUTLIER_FACTOR}), and what is left is + * added up rather than averaged, so a long stretch counts for more than a short one. Null with too + * few pairs. + */ +export function fullBatteryRangeKm(pairs: ChargePair[]): number | null { + const usable = pairs.filter( + (p): p is ChargePair & { socUsedPercent: number } => + p.socUsedPercent !== null && + p.socUsedPercent >= MIN_RANGE_PAIR_SOC_USED && + p.distanceKm >= MIN_RANGE_PAIR_DISTANCE_KM, + ) + if (usable.length < MIN_PAIRS) return null + + const middle = median(usable.map((p) => p.distanceKm / p.socUsedPercent)) + const kept = usable.filter((p) => { + const perPercent = p.distanceKm / p.socUsedPercent + return ( + perPercent >= middle / RANGE_OUTLIER_FACTOR && perPercent <= middle * RANGE_OUTLIER_FACTOR + ) + }) + if (kept.length < MIN_PAIRS) return null + + const distance = kept.reduce((sum, p) => sum + p.distanceKm, 0) + const used = kept.reduce((sum, p) => sum + p.socUsedPercent, 0) + return (distance / used) * 100 +} + +/** The levels charges usually start from and end at. */ +export interface ChargeHabit { + startPercent: number + endPercent: number +} + +/** The average level the finished charges started at and ended at; null with too few of them. */ +export function chargeHabit(sessions: ChargeSession[]): ChargeHabit | null { + const levels = sessions.filter( + (s) => s.endedAt !== null && finite(s.startSocPercent) && finite(s.endSocPercent), + ) + if (levels.length < MIN_PAIRS) return null + + const average = (pick: (s: ChargeSession) => number | null) => + levels.reduce((sum, s) => sum + (pick(s) ?? 0), 0) / levels.length + return { + startPercent: average((s) => s.startSocPercent), + endPercent: average((s) => s.endSocPercent), + } +} diff --git a/frontend/src/views/StatisticsView.vue b/frontend/src/views/StatisticsView.vue index 8a91d211..e860bc81 100644 --- a/frontend/src/views/StatisticsView.vue +++ b/frontend/src/views/StatisticsView.vue @@ -9,7 +9,7 @@ import { defaultStatsInsights, defaultStatsCharts } from '@/stores/settingsShare import type { StatsInsightId, StatsChartId } from '@/stores/settingsShared' import type { Quantity } from '@/utils/units' import { vehicleApi } from '@/services/vehicleApi' -import type { VehicleAggregateStats } from '@/services/vehicleApi' +import type { ChargeSession, VehicleAggregateStats } from '@/services/vehicleApi' import { LMap, LMarker } from '@vue-leaflet/vue-leaflet' import { DEFAULT_MAP_CENTER, fitToPoints, type LeafletMap } from '@/utils/leaflet' import { useLeafletMap } from '@/composables/useLeafletMap' @@ -34,7 +34,13 @@ import { litres, MIN_EFFICIENCY_DISTANCE_KM, } from '@/utils/energy' -import { burnsFuel, plugsIn } from '@/utils/vehicleType' +import { burnsFuel, mayPlugIn, plugsIn } from '@/utils/vehicleType' +import { + chargeHabit, + chargePairs, + fullBatteryRangeKm, + typicalDistanceBetweenCharges, +} from '@/utils/chargeStatistics' import { averageMovingSpeedKmh, averageTripKm as averageTripDistanceKm, @@ -65,6 +71,8 @@ const errorMessage = useErrorMessage() const { editMode, cardLongPress } = useEditMode() const loading = ref(false) const aggregateStats = ref(null) +// The period's charges, for the insights that read them. Empty for a car that cannot plug in. +const chargeSessions = ref([]) // The days the page shows, from its own period: the map and the charge history keep theirs. const period = computed(() => resolveStatsPeriod(uiSettings.statsPeriod)) @@ -74,20 +82,34 @@ const periodLabel = computed(() => formatPeriodRange(period.value)) const vin = computed(() => store.activeVin) const status = computed(() => store.currentStatus) +// The charges of the period, or none: a car that cannot plug in has none, and the insights that read +// them are not worth a page that fails to load, so an answer that does not come is no charges. +async function fetchChargeSessions(carVin: string, fromIso: string, toIso: string | undefined) { + if (!mayPlugIn(store.effectiveVehicleType)) return [] + try { + // A period ending today asks up to now, so a charge still going is listed (see ChargeHistoryView). + return await vehicleApi.chargeSessions(carVin, fromIso, toIso ?? new Date().toISOString()) + } catch { + return [] + } +} + async function load() { loading.value = true try { await store.fetchVehicles() if (!vin.value) return const query = periodQuery(period.value) - const [, , , , stats] = await Promise.all([ + const [, , , , stats, sessions] = await Promise.all([ store.fetchDailyStats(vin.value, query.fromDate, query.toDate), store.fetchTripSummaries(vin.value, query.fromIso, query.toIso), store.fetchStatus(vin.value), store.fetchConfig(vin.value), vehicleApi.stats(vin.value, query.fromIso, query.toIso), + fetchChargeSessions(vin.value, query.fromIso, query.toIso), ]) aggregateStats.value = stats + chargeSessions.value = sessions } finally { loading.value = false } @@ -124,6 +146,9 @@ const INSIGHT_ICONS: Record = { parkingLocations: 'location-dot', electricShare: 'leaf', avgSpeed: 'gauge-high', + fullBatteryRange: 'battery-full', + distancePerCharge: 'charging-station', + chargeHabit: 'plug', } // The period's days as chart points: per day, per week or per month, by how long it is. @@ -203,6 +228,12 @@ const batteryVoltageDisplay = computed(() => { const avgSpeedKmh = computed(() => averageMovingSpeedKmh(store.tripSummaries)) +// What the period's charges say, between each one and the next (see utils/chargeStatistics). +const pairs = computed(() => chargePairs(chargeSessions.value)) +const rangeOnFullBattery = computed(() => fullBatteryRangeKm(pairs.value)) +const distanceBetweenCharges = computed(() => typicalDistanceBetweenCharges(pairs.value)) +const usualCharge = computed(() => chargeHabit(chargeSessions.value)) + const electricShareToday = computed(() => { const s = status.value if (!s?.mileageSinceLastCharge || !s?.mileageOfTheDay || s.mileageOfTheDay === 0) return null @@ -374,6 +405,36 @@ const insightDefs = computed((): InsightDef[] => [ vehicleApplicable: true, applicable: hasSpeedReadings(store.tripSummaries), }, + { + id: 'fullBatteryRange' as StatsInsightId, + icon: INSIGHT_ICONS.fullBatteryRange, + title: t('statistics.insights.fullBatteryRange'), + description: t('statistics.cardDesc.fullBatteryRange'), + ...measuredInsight('distance', rangeOnFullBattery.value), + // Only a BEV: a hybrid's kilometres include petrol, so they say nothing about its battery. + vehicleApplicable: vehicleType.value === 'bev', + applicable: vehicleType.value === 'bev' && rangeOnFullBattery.value !== null, + }, + { + id: 'distancePerCharge' as StatsInsightId, + icon: INSIGHT_ICONS.distancePerCharge, + title: t('statistics.insights.distancePerCharge'), + description: t('statistics.cardDesc.distancePerCharge'), + ...measuredInsight('distance', distanceBetweenCharges.value), + vehicleApplicable: mayPlugIn(vehicleType.value), + applicable: mayPlugIn(vehicleType.value) && distanceBetweenCharges.value !== null, + }, + { + id: 'chargeHabit' as StatsInsightId, + icon: INSIGHT_ICONS.chargeHabit, + title: t('statistics.insights.chargeHabit'), + description: t('statistics.cardDesc.chargeHabit'), + value: usualCharge.value + ? `${formatNumber(usualCharge.value.startPercent, 0)}% → ${formatNumber(usualCharge.value.endPercent, 0)}%` + : null, + vehicleApplicable: mayPlugIn(vehicleType.value), + applicable: mayPlugIn(vehicleType.value) && usualCharge.value !== null, + }, ]) const insightDefMap = computed(() => new Map(insightDefs.value.map((d) => [d.id, d]))) diff --git a/frontend/src/views/__tests__/StatisticsView.spec.ts b/frontend/src/views/__tests__/StatisticsView.spec.ts index 5c659083..57aa31a2 100644 --- a/frontend/src/views/__tests__/StatisticsView.spec.ts +++ b/frontend/src/views/__tests__/StatisticsView.spec.ts @@ -7,6 +7,7 @@ import en from '@/locales/en.json' import StatisticsView from '../StatisticsView.vue' import { vehicleApi, + type ChargeSession, type DailyStat, type TelemetrySnapshot, type TripSummary, @@ -27,6 +28,7 @@ vi.mock('@/services/vehicleApi', () => ({ dailyStats: vi.fn<() => Promise>(), tripSummaries: vi.fn<() => Promise>(), stats: vi.fn<() => Promise>(), + chargeSessions: vi.fn<() => Promise>(), }, })) @@ -153,6 +155,7 @@ describe('StatisticsView', () => { climateOnSnapshots: 1, totalClimateSnapshots: 4, }) + vi.mocked(vehicleApi.chargeSessions).mockResolvedValue([]) }) afterEach(() => { @@ -212,6 +215,92 @@ describe('StatisticsView', () => { expect(shownInsights(wrapper)[insights.electricShare]).toBe('75%') }) + // What the charges of the period say: the card values come off utils/chargeStatistics, which has + // its own tests, so these look at what the page asks for and which cars it shows them to. + describe("the insights from the period's charges", () => { + // Four charges 180 km apart, each ending at 90 % and the next starting from 40 %: 50 % of the + // battery per 180 km, which is 360 km on a full one. + function charge(index: number): ChargeSession { + const day = String(10 + index) + return { + startedAt: `2026-10-${day}T20:00:00Z`, + endedAt: `2026-10-${day}T23:00:00Z`, + startSocPercent: 40, + endSocPercent: 90, + chargingType: 'AC', + odometerKm: 1000 + 180 * index, + latitude: null, + longitude: null, + startBatteryKwh: null, + endBatteryKwh: null, + batteryEnergyGainedKwh: null, + maxPowerKw: 7, + } + } + const fourCharges = [0, 1, 2, 3].map(charge) + + it("asks for the period's charges for a car that can plug in", async () => { + vi.mocked(vehicleApi.list).mockResolvedValue([car('bev')]) + + await mountView() + + const [vin, from, to] = vi.mocked(vehicleApi.chargeSessions).mock.calls[0]! + const [, tripsFrom] = vi.mocked(vehicleApi.tripSummaries).mock.calls[0]! + expect(vin).toBe('FAKEVN00000000001') + expect(from).toBe(tripsFrom) + expect(to).toBeTruthy() + }) + + it('does not ask a plain hybrid, which never charges from a plug', async () => { + await mountView() + + expect(vehicleApi.chargeSessions).not.toHaveBeenCalled() + }) + + it('shows the range on a full battery, the distance per charge and the usual charge on a BEV', async () => { + vi.mocked(vehicleApi.list).mockResolvedValue([car('bev')]) + vi.mocked(vehicleApi.chargeSessions).mockResolvedValue(fourCharges) + + const shown = shownInsights(await mountView()) + + expect(shown[insights.fullBatteryRange]).toBe('360.0 km') + expect(shown[insights.distancePerCharge]).toBe('180.0 km') + expect(shown[insights.chargeHabit]).toBe('40% → 90%') + }) + + it('leaves the range on a full battery to a BEV: a plug-in hybrid covers petrol kilometres too', async () => { + vi.mocked(vehicleApi.list).mockResolvedValue([car('phev')]) + vi.mocked(vehicleApi.chargeSessions).mockResolvedValue(fourCharges) + + const shown = shownInsights(await mountView()) + + expect(shown).not.toHaveProperty(insights.fullBatteryRange) + expect(shown[insights.distancePerCharge]).toBe('180.0 km') + expect(shown[insights.chargeHabit]).toBe('40% → 90%') + }) + + it('shows none of them with too few charges to go on', async () => { + vi.mocked(vehicleApi.list).mockResolvedValue([car('bev')]) + vi.mocked(vehicleApi.chargeSessions).mockResolvedValue(fourCharges.slice(0, 2)) + + const shown = shownInsights(await mountView()) + + expect(shown).not.toHaveProperty(insights.fullBatteryRange) + expect(shown).not.toHaveProperty(insights.distancePerCharge) + expect(shown).not.toHaveProperty(insights.chargeHabit) + }) + + it('still shows the rest of the page when the charges cannot be read', async () => { + vi.mocked(vehicleApi.list).mockResolvedValue([car('bev')]) + vi.mocked(vehicleApi.chargeSessions).mockRejectedValue(new ApiError(500, '/charge-sessions')) + + const shown = shownInsights(await mountView()) + + expect(shown[insights.distanceInRange]).toBe('60.0 km') + expect(shown).not.toHaveProperty(insights.distancePerCharge) + }) + }) + it('shows where the car parked once the insight is opened', async () => { const wrapper = await mountView()