From 2a548e9ebc2a9aca0167b44138e9ef34f2fa6408 Mon Sep 17 00:00:00 2001 From: DEls Date: Sat, 29 Aug 2026 20:04:51 +0200 Subject: [PATCH] refactor(fuel): build rows from the shared variance pass MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit No behaviour change — deletes the duplicate group/sort/pairwise walk now that computeFuelLogStatuses does it. computeFuelVariance now has exactly one caller. Co-Authored-By: Claude Opus 5 --- src/app/dashboard/fuel/page.tsx | 47 +++++++++++++-------------------- 1 file changed, 19 insertions(+), 28 deletions(-) diff --git a/src/app/dashboard/fuel/page.tsx b/src/app/dashboard/fuel/page.tsx index 3bda595..c27ba49 100644 --- a/src/app/dashboard/fuel/page.tsx +++ b/src/app/dashboard/fuel/page.tsx @@ -1,6 +1,11 @@ import { pbAdmin } from "@/lib/pb"; -import { computeFuelVariance, parseFuelLimit } from "@/lib/fuel-variance"; -import { RATE_PER_LITRE } from "@/lib/metrics"; +import { parseFuelLimit } from "@/lib/fuel-variance"; +import { + computeFuelLogStatuses, + RATE_PER_LITRE, + type AttentionFuelLogLike, + type AttentionVehicleLike, +} from "@/lib/metrics"; import { FuelView, type FuelRow, type VehicleSummary } from "./fuel-view"; export const dynamic = "force-dynamic"; @@ -23,21 +28,13 @@ export default async function FuelPage() { }; } - // Build per-row data + sort each vehicle's logs by date so we can find - // the previous reading for variance computation. - const logsByVehicle = new Map(); - for (const log of fuelLogs) { - const list = logsByVehicle.get(log.vehicle) ?? []; - list.push(log); - logsByVehicle.set(log.vehicle, list); - } - for (const list of logsByVehicle.values()) { - list.sort((a, b) => { - const d = (a.date_logged ?? "").localeCompare(b.date_logged ?? ""); - if (d !== 0) return d; - return (a.odo_reading ?? 0) - (b.odo_reading ?? 0); - }); - } + // One shared variance pass; index it so the row map is a lookup. + const statusByLogId = new Map( + computeFuelLogStatuses({ + vehicles: vehicles as unknown as AttentionVehicleLike[], + fuelLogs: fuelLogs as unknown as AttentionFuelLogLike[], + }).map((s) => [s.logId, s]), + ); const rows: FuelRow[] = fuelLogs.map((log) => { const veh = log.expand?.vehicle @@ -56,17 +53,11 @@ export default async function FuelPage() { fuelLimits: "", }; - const peers = logsByVehicle.get(log.vehicle) ?? []; - const idx = peers.findIndex((p) => p.id === log.id); - const previous = idx > 0 ? peers[idx - 1] : undefined; - - const { variance, status, limitTarget, limitUnit } = computeFuelVariance( - log.litres, - log.odo_reading, - previous?.odo_reading, - previous?.litres, - vehicleRow.fuelLimits, - ); + const st = statusByLogId.get(log.id); + const variance = st?.variance ?? null; + const status = st?.status ?? "no-limit"; + const limitTarget = st?.limitTarget ?? null; + const limitUnit = st?.limitUnit ?? null; return { id: log.id,