Files
DriverVault/Phone App/lib/format.dart
T
tajniak81andClaude Opus 4.8 ee28b522c7 Bring the Phone App up to parity with the web app
Four rounds of web-app features never reached the phone: fuel, maintenance,
document and reminder tracking; attachments; the currency setting and the
locale split; and technical check history. The README claimed full parity
throughout, so the gap was invisible. Catch the phone up, mirroring the web
components field for field.

Car detail grows the web app's tabs, in its order: technical checks,
maintenance, fuel (with the summary panel), documents and reminders, beside
the existing service and parts lists. The derived figures are the server's
and are rendered as "—" wherever it sent null — a window with a missed fill
has no consumption, and a plausible-looking 0.0 there would be a lie.

Attachments hang off service records, technical checks, workshop visits,
refills, documents and parts on identical terms, so one field and one apply
helper cover all six rather than being copied per form. As on the web, the
form only collects intent: the file endpoints address a record that must
already exist, so a create-with-file is two calls, and a failure on the
second reports as an attachment error because the metadata is committed.

Two bugs fixed on the way:

- _carPayload omitted technicalCheckIntervalDays. The API rewrites every
  column from the body, so any car edit — including the one-tap odometer
  update — silently zeroed the car's inspection interval.
- main() never called initializeDateFormatting, so month names ignored the
  chosen language that the new Language picker exists to set.

Luxembourgish and Romansh are deliberately left off the language list: intl
ships no symbols for them and throws rather than falling back, which would
take out every date on screen. The browser has full ICU data and has no such
limit, so the web app can offer them. The server only validates a locale's
shape, so an unrenderable tag can still arrive from the web; format.dart
resolves through a supported-language check and falls back to en-US.

Labels for the language/region/currency lists are hand-kept because Dart has
no Intl.DisplayNames. The lists mirror validCurrencies in me.go.

file_picker is pinned to ^10: v8 compiles against android-34, which no longer
builds against the other plugins' compileSdk requirement of 36.

Adds the project's first test, covering the parts that fail silently rather
than loudly — null derived fields, the badge wording, and the locale guard.

The phone was not authorized over ADB, so the UI was not exercised on a
device: this is analyzer-, test- and build-clean, and every JSON field name
and route was cross-checked against models.go and server.go.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-17 15:15:01 +02:00

189 lines
7.9 KiB
Dart

import "package:flutter/material.dart";
import "package:intl/intl.dart";
import "main.dart";
import "models.dart";
import "theme.dart";
/// The languages intl actually ships symbols for. It throws rather than falling
/// back on the rest, and the API only validates a locale's *shape*
/// (`^[a-z]{2}-[A-Z]{2}$`), so an unsupported tag can legitimately arrive here —
/// set from the web, which has the browser's full ICU data behind it. Guarding
/// once keeps that from throwing out of every date on screen.
final _supportedLanguages = DateFormat.allLocalesWithSymbols().toSet();
/// The user's locale when intl can render it, else a safe default. Only the
/// language subtag is checked: intl resolves an unknown *region* by falling back
/// to the language ("en-PL" formats as "en"), but an unknown language throws.
String get _locale =>
_supportedLanguages.contains(appSettings.language) ? appSettings.locale : "en-US";
/// Every number we render goes through here so the grouping separator follows
/// the user's chosen region rather than the device's own locale — otherwise the
/// odometer disagrees with the dates and costs beside it.
String _num(num value) => NumberFormat.decimalPattern(_locale).format(value);
/// Formats a date per the signed-in user's chosen date format (appSettings),
/// mirroring the web app's format.js. Month names follow the locale's language.
String formatDate(DateTime? d) {
if (d == null) return "—";
final pattern = switch (appSettings.dateFormat) {
"DMY_NUM" => "dd-MM-yyyy",
"DMY" => "dd MMM yyyy",
"MDY" => "MMM dd, yyyy",
_ => "yyyy-MM-dd", // YMD
};
return DateFormat(pattern, _locale).format(d);
}
String formatKm(int? km) => (km == null || km == 0) ? "—" : "${_num(km)} km";
// The fuel figures. The server sends null for anything it could not derive (a
// window with a missed fill, a first-ever tank), which reads as "—" rather than
// a misleading zero.
String formatLiters(double? value) => value == null ? "—" : "${value.toStringAsFixed(2)} L";
/// Amounts are stored as plain numbers; the user's currency setting only decides
/// how they are displayed. Nothing is converted — a figure entered as 40 reads as
/// 40 in whichever currency is selected.
///
/// No explicit fraction digits: the currency's own minor unit pins them, which
/// keeps the 2 decimals the fuel figures were written for while still rendering
/// yen without phantom sen.
String formatMoney(double? value) {
if (value == null) return "—";
return NumberFormat.simpleCurrency(locale: _locale, name: appSettings.currency).format(value);
}
/// One decimal: the interesting differences between tanks live in tenths, and
/// rounding to whole litres collapses a best of 6.8 and a worst of 7.0 into the
/// same number.
String formatConsumption(double? value) =>
value == null ? "—" : "${value.toStringAsFixed(1)} L/100km";
String formatKmPerLiter(double? value) =>
value == null ? "—" : "${value.toStringAsFixed(2)} km/L";
const int _kmSoon = 1000;
enum StatusKey { unknown, ok, soon, overdue }
class Status {
final StatusKey key;
final String label;
const Status(this.key, this.label);
/// Soft tint background for the status pill — DriverVault semantic colours,
/// re-cut for dark surfaces.
Color bg(bool dark) => switch (key) {
StatusKey.overdue => dark ? DriverVault.dangerSoftDark : DriverVault.dangerSoft,
StatusKey.soon => dark ? DriverVault.warningSoftDark : DriverVault.warningSoft,
StatusKey.ok => dark ? DriverVault.successSoftDark : DriverVault.successSoft,
StatusKey.unknown => dark ? DriverVault.darkSunken : DriverVault.ink50,
};
Color fg(bool dark) => switch (key) {
StatusKey.overdue => DriverVault.danger,
StatusKey.soon => DriverVault.warning,
StatusKey.ok => DriverVault.success,
StatusKey.unknown => dark ? DriverVault.darkTextMuted : DriverVault.ink500,
};
}
int _rank(StatusKey k) => switch (k) {
StatusKey.unknown => 0,
StatusKey.ok => 1,
StatusKey.soon => 2,
StatusKey.overdue => 3,
};
Status _dateSignal(DateTime? nextDate) {
if (nextDate == null) return const Status(StatusKey.unknown, "No data");
final today = DateTime.now();
final days = DateTime(nextDate.year, nextDate.month, nextDate.day)
.difference(DateTime(today.year, today.month, today.day))
.inDays;
if (days < 0) return Status(StatusKey.overdue, "Service Overdue ${days.abs()}d");
if (days <= 30) return Status(StatusKey.soon, "Due in ${days}d");
return Status(StatusKey.ok, "OK · ${days}d");
}
Status _kmSignal(int currentKm, int? nextKm) {
if (currentKm == 0 || nextKm == null) return const Status(StatusKey.unknown, "No km");
final remaining = nextKm - currentKm;
if (remaining < 0) return Status(StatusKey.overdue, "Service Overdue ${_num(remaining.abs())} km");
if (remaining <= _kmSoon) return Status(StatusKey.soon, "In ${_num(remaining)} km");
return Status(StatusKey.ok, "${_num(remaining)} km left");
}
/// Maps the server's expiry/reminder state names onto the badge palette. The
/// client never re-derives the date maths — it only chooses the wording.
StatusKey _expiryKey(String state) => switch (state) {
"expired" => StatusKey.overdue,
"expiring_soon" => StatusKey.soon,
"valid" => StatusKey.ok,
_ => StatusKey.unknown, // no_expiry
};
/// Renewal badge for a dated document or certificate, driven by the server's
/// expiry assessment.
Status expiryStatus(ExpiryAssessment e) {
final days = e.days;
final label = switch (e.state) {
"expired" => "Expired ${(days ?? 0).abs()}d ago",
"expiring_soon" => days == 0 ? "Expires today" : "Renew in ${days}d",
"valid" => "Valid · ${days}d",
_ => "No expiry",
};
return Status(_expiryKey(e.state), label);
}
/// Reminder badge. The server has already picked the worse of the date and
/// odometer signals; this only chooses the wording, leading with whichever
/// trigger is actually closest to firing.
Status reminderStatus(Reminder r) {
final key = switch (r.status) {
"overdue" => StatusKey.overdue,
"due_soon" => StatusKey.soon,
"upcoming" => StatusKey.ok,
_ => StatusKey.unknown, // done | no_trigger
};
final days = r.daysLeft;
final km = r.kmLeft;
if (r.status == "done") return const Status(StatusKey.unknown, "Done");
if (r.status == "no_trigger") return const Status(StatusKey.unknown, "No trigger");
final parts = <String>[];
if (r.status == "overdue") {
if (days != null && days < 0) parts.add("${days.abs()}d");
if (km != null && km < 0) parts.add("${_num(km.abs())} km");
return Status(key, parts.isEmpty ? "Overdue" : "Overdue ${parts.join(" · ")}");
}
if (days != null && days >= 0) parts.add(days == 0 ? "today" : "${days}d");
if (km != null && km >= 0) parts.add("${_num(km)} km");
return Status(key, parts.isEmpty ? "Upcoming" : "Due in ${parts.join(" · ")}");
}
/// Warranty badge for a maintenance entry. Unlike the others this one has no
/// server-side assessment — only the raw active/days-left pair — so the wording
/// is chosen from those directly.
Status? warrantyStatus(MaintenanceEntry m) {
final days = m.warrantyDaysLeft;
if (m.warrantyActive == null || days == null) return null;
if (!m.warrantyActive!) return Status(StatusKey.unknown, "Warranty expired ${days.abs()}d ago");
if (days <= 30) return Status(StatusKey.soon, "Warranty ends in ${days}d");
return Status(StatusKey.ok, "Under warranty · ${days}d");
}
/// Combines the date- and km-based signals, returning the worse of the two —
/// the same logic as the web app and the spreadsheet idea.
Status serviceStatus(ServiceRecord? latest, Car car) {
final date = _dateSignal(latest?.nextServiceDate);
final km = _kmSignal(car.currentKm, latest?.nextServiceKm);
final worse = _rank(km.key) > _rank(date.key) ? km : date;
if (date.key == StatusKey.unknown && km.key != StatusKey.unknown) return km;
if (km.key == StatusKey.unknown && date.key != StatusKey.unknown) return date;
return worse;
}