Phone App: connected service, charging cost, a tab picker and data export
Both READMEs claimed web parity with data export/import as the only
omission. That was three gaps out of date: the car screen had no
connected-service tab, no per-car charging-cost tab, and no way to say what
a car's page shows - all three of which the web has had since the car view
became a property of the car rather than of the browser.
The tab bar was the thing blocking the rest. It was a fixed list of eight
Tab(text: "Information") literals, so it could neither grow a tab nor read
an arrangement, and it sat outside the translation system that the rest of
the app has used since b6bb6b1. It now builds from the car's own tabOrder
and hiddenTabs, and labels come from car.tabs.* like the web's.
Rather than retype four subtrees of strings in three languages, the shared
ones - car.*, settings.advanced, forms.charging, forms.import and the
common keys the phone was missing - are copied out of the Web App's own
language files, with the phone's existing wording winning every collision.
Polish and Danish therefore arrive complete and cannot drift between the
two apps. Only five strings are genuinely phone-only: the reorder hint, the
saved-file message, the open action and two validation lines.
The connected-service tab mirrors ProviderPanel: headline readings, the
offer to take a provider odometer that is ahead of the stored one, the
vehicle record, and one collapsible card per capability, rendered from the
server's flattened key/value pairs so a provider adding a field surfaces it
without touching this app. Two deliberate differences. The raw-payload
disclosure is dropped - Toyota's eight sections are megabytes of JSON on a
phone screen, and the flattened fields carry the same content. And the
readings cannot be dragged here, though a stored metricOrder is still
honoured, so an arrangement made on the web carries over.
The view picker takes the same line on gestures. The web rearranges by
dragging the tab bar itself and the Information rows themselves; on a touch
screen that gesture belongs to the tab bar, so both arrangements are made
in the picker with a handle instead, and hiddenTabs, hiddenFields, tabOrder
and fieldOrder all save in one PUT. The key catalogues live in
car_view_sheet.dart and mirror hideableCarTabs / arrangeableCarTabs /
hideableCarFields in cars.go, because the server rejects anything else.
arrangeKeys applies a partial stored order the way the API documents it: an
unknown key is dropped and an unnamed one follows the arranged ones, which
is what puts a tab added in a later release at the end of somebody's page
rather than the middle of it.
Charging cost is the electric twin of Fuel and is built as one - the same
stats panel, tile and form shape, measured between full charges. It is the
per-car cost log, not the Charging section in the bottom bar, which remains
the charger network and OCPP control.
Export and import needed a phone answer to two browser affordances. The
export is written to the app's documents directory under the filename the
server's Content-Disposition names, and offered to whatever opens JSON via
open_filex - the same route attachments already take. The import goes
through the system file picker, validates the file locally, and confirms
with the number of cars the file actually holds, because the server always
creates new records and never merges.
The one field worth calling out on the client: _carPayload still leaves the
provider link and the view arrangement out, matching carPayload in
records.go, so saving the car form cannot silently unlink a car or undo an
arrangement.
Known gap, deliberately not closed here: the older sheets in
record_form_sheets.dart and most of car_detail_screen.dart still carry
hardcoded English. Everything added here and every tab label goes through
t(), but translating the rest of the car screen is its own change and would
have buried this one.
Verified by flutter analyze (clean), flutter test - 13 pass, 6 of them new,
covering arrangeKeys against partial, unknown and duplicate keys, the
charging models keeping uncomputed figures null rather than a plausible
zero, the new Car fields, and ProviderSnapshot parsing an unreachable
provider as an answer rather than a failure - and flutter build apk
--debug, which succeeds. The Kotlin Gradle plugin warnings in that build
are pre-existing.
Not verified: nothing was run against a live API Server or on a device, so
the new screens have not been driven end to end - only compiled, analyzed
and unit-tested.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
215c027ada
commit
e249c2f4d8
14 files changed
+3510
-203
No files matched your search
@@ -133,6 +133,29 @@ class ApiClient {
|
||||
|
||||
Future<void> deleteCar(String id) => _send("DELETE", "/cars/$id");
|
||||
|
||||
/// What this car's page shows and in which order — its own endpoint rather
|
||||
/// than part of the car PATCH, so saving the car form can never silently
|
||||
/// reveal a hidden tab or undo an arrangement. Every field is optional; only
|
||||
/// the ones passed are written.
|
||||
Future<Car> updateCarView(
|
||||
String id, {
|
||||
List<String>? hiddenTabs,
|
||||
List<String>? hiddenFields,
|
||||
List<String>? tabOrder,
|
||||
List<String>? fieldOrder,
|
||||
List<String>? metricOrder,
|
||||
}) async {
|
||||
final body = <String, dynamic>{
|
||||
if (hiddenTabs != null) "hiddenTabs": hiddenTabs,
|
||||
if (hiddenFields != null) "hiddenFields": hiddenFields,
|
||||
if (tabOrder != null) "tabOrder": tabOrder,
|
||||
if (fieldOrder != null) "fieldOrder": fieldOrder,
|
||||
if (metricOrder != null) "metricOrder": metricOrder,
|
||||
};
|
||||
final data = await _send("PUT", "/cars/$id/view", body: body);
|
||||
return Car.fromJson(Map<String, dynamic>.from(data));
|
||||
}
|
||||
|
||||
// --- sharing (owner-only) ---
|
||||
Future<List<CarShare>> listCarShares(String carId) async {
|
||||
final data = await _send("GET", "/cars/$carId/shares") as List;
|
||||
@@ -278,6 +301,31 @@ class ApiClient {
|
||||
|
||||
Future<void> deleteFuelEntry(String id) => _send("DELETE", "/fuel-entries/$id");
|
||||
|
||||
// --- charging sessions ---
|
||||
// The electric counterpart of the fuel entries, on identical terms: the
|
||||
// per-car list plus the derived summary, and CRUD on the flat collection.
|
||||
Future<List<ChargingSession>> listCarChargingSessions(String carId) async {
|
||||
final data = await _send("GET", "/cars/$carId/charging-sessions") as List;
|
||||
return data.map((e) => ChargingSession.fromJson(Map<String, dynamic>.from(e))).toList();
|
||||
}
|
||||
|
||||
Future<ChargingStats> getCarChargingStats(String carId) async {
|
||||
final data = await _send("GET", "/cars/$carId/charging-stats");
|
||||
return ChargingStats.fromJson(Map<String, dynamic>.from(data));
|
||||
}
|
||||
|
||||
Future<ChargingSession> createChargingSession(Map<String, dynamic> body) async {
|
||||
final data = await _send("POST", "/charging-sessions", body: body);
|
||||
return ChargingSession.fromJson(Map<String, dynamic>.from(data));
|
||||
}
|
||||
|
||||
Future<ChargingSession> updateChargingSession(String id, Map<String, dynamic> body) async {
|
||||
final data = await _send("PATCH", "/charging-sessions/$id", body: body);
|
||||
return ChargingSession.fromJson(Map<String, dynamic>.from(data));
|
||||
}
|
||||
|
||||
Future<void> deleteChargingSession(String id) => _send("DELETE", "/charging-sessions/$id");
|
||||
|
||||
// --- maintenance ---
|
||||
Future<List<MaintenanceEntry>> listCarMaintenance(String carId) async {
|
||||
final data = await _send("GET", "/cars/$carId/maintenance") as List;
|
||||
@@ -432,6 +480,90 @@ class ApiClient {
|
||||
Future<void> cancelAccountDeletion() => _send("POST", "/me/delete/cancel");
|
||||
Future<void> finalizeAccountDeletion() => _send("DELETE", "/me");
|
||||
|
||||
// --- data export / import ---
|
||||
|
||||
/// The whole account as a JSON file: the profile plus every car the user owns
|
||||
/// with its service records and parts. Cars merely shared with them are not
|
||||
/// included. Returns the bytes and the filename the server named it, which is
|
||||
/// dated — the phone has to write the file itself, so it needs both.
|
||||
Future<(List<int>, String)> exportData() async {
|
||||
final res = await http.get(_uri("/me/export"),
|
||||
headers: {if (token != null) "Authorization": "Bearer $token"});
|
||||
if (res.statusCode == 401) {
|
||||
onUnauthorized?.call();
|
||||
throw ApiException(401, "Session expired — please log in again.");
|
||||
}
|
||||
if (res.statusCode < 200 || res.statusCode >= 300) {
|
||||
throw ApiException(res.statusCode, _errorMessage(_tryDecode(res.body), res.reasonPhrase));
|
||||
}
|
||||
return (res.bodyBytes, _filenameFrom(res.headers["content-disposition"]));
|
||||
}
|
||||
|
||||
/// Adds the cars in a previously exported file. Always creates new records —
|
||||
/// nothing is merged with or overwritten, so importing the same file twice
|
||||
/// leaves two copies rather than one updated one.
|
||||
Future<ImportResult> importData(Map<String, dynamic> payload) async {
|
||||
final data = await _send("POST", "/me/import", body: payload);
|
||||
return ImportResult.fromJson(Map<String, dynamic>.from(data));
|
||||
}
|
||||
|
||||
static dynamic _tryDecode(String body) {
|
||||
try {
|
||||
return jsonDecode(body);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// The filename out of `attachment; filename="…"`, falling back to a plain
|
||||
/// name so the export is still saveable if the header is missing or unquoted.
|
||||
static String _filenameFrom(String? disposition) {
|
||||
if (disposition == null) return "drivervault-export.json";
|
||||
final m = RegExp(r'filename="?([^";]+)"?').firstMatch(disposition);
|
||||
final name = m?.group(1)?.trim() ?? "";
|
||||
return name.isEmpty ? "drivervault-export.json" : name;
|
||||
}
|
||||
|
||||
// --- vehicle providers (the connected-service tab) ---
|
||||
// Every call runs server-side under *this* user's manufacturer account, so a
|
||||
// car shared from someone else only shows provider data when that vehicle is
|
||||
// on this user's account too. A closed gate is a 200 with `unavailable` set
|
||||
// rather than an error: "we asked, and here is why there is nothing".
|
||||
|
||||
Future<List<VehicleProvider>> listVehicleProviders() async {
|
||||
final data = await _send("GET", "/vehicle-providers");
|
||||
final items = (data["providers"] ?? []) as List;
|
||||
return items.map((e) => VehicleProvider.fromJson(Map<String, dynamic>.from(e))).toList();
|
||||
}
|
||||
|
||||
Future<List<ProviderVehicle>> listProviderVehicles(String provider) async {
|
||||
final data = await _send("GET", "/vehicle-providers/${Uri.encodeComponent(provider)}/vehicles");
|
||||
final items = (data["vehicles"] ?? []) as List;
|
||||
return items.map((e) => ProviderVehicle.fromJson(Map<String, dynamic>.from(e))).toList();
|
||||
}
|
||||
|
||||
Future<ProviderSnapshot> getCarProvider(String carId) async {
|
||||
final data = await _send("GET", "/cars/$carId/provider");
|
||||
return ProviderSnapshot.fromJson(Map<String, dynamic>.from(data));
|
||||
}
|
||||
|
||||
/// Links this car to a vehicle on the caller's provider account; an empty
|
||||
/// [provider] unlinks it. Returns the updated car.
|
||||
Future<Car> linkCarProvider(String carId, {String provider = "", String vehicleId = ""}) async {
|
||||
final data = await _send("POST", "/cars/$carId/provider",
|
||||
body: {"provider": provider, "vehicleId": vehicleId});
|
||||
return Car.fromJson(Map<String, dynamic>.from(data));
|
||||
}
|
||||
|
||||
/// Re-applies the provider's data to the car. [include] selects what to take
|
||||
/// (identity, fuelType, dates, odometer); omitted means everything.
|
||||
Future<Car> syncCarProvider(String carId, {Map<String, bool>? include}) async {
|
||||
final data = await _send("POST", "/cars/$carId/provider/sync",
|
||||
body: {if (include != null) "include": include});
|
||||
final car = (data is Map && data["car"] != null) ? data["car"] : data;
|
||||
return Car.fromJson(Map<String, dynamic>.from(car));
|
||||
}
|
||||
|
||||
// --- integrations (per-user plugin settings, superadmin → org → user cascade) ---
|
||||
// getToyota/getAnkerSolix return the resolved view (effective/own/locked per
|
||||
// field, secrets and inherited values masked); saveToyota/saveAnkerSolix write
|
||||
|
||||
@@ -37,6 +37,15 @@ String formatDate(DateTime? d) {
|
||||
return DateFormat(pattern, _locale).format(d);
|
||||
}
|
||||
|
||||
/// A timestamp: the user's chosen date format with the wall clock beside it.
|
||||
/// Only the provider snapshot needs one — everything else in the app is
|
||||
/// date-only — but it follows the same settings as [formatDate] so the two never
|
||||
/// disagree on screen.
|
||||
String formatDateTime(DateTime? d) {
|
||||
if (d == null) return "—";
|
||||
return "${formatDate(d)} ${DateFormat.Hm(_locale).format(d)}";
|
||||
}
|
||||
|
||||
// 0 km is a reading — a car collected new — not a blank. See format.js.
|
||||
String formatKm(int? km) => km == null ? "—" : "${_num(km)} km";
|
||||
|
||||
@@ -66,6 +75,16 @@ String formatConsumption(double? value) =>
|
||||
String formatKmPerLiter(double? value) =>
|
||||
value == null ? "—" : "${value.toStringAsFixed(2)} km/L";
|
||||
|
||||
/// The charging figures. Same rule as the fuel ones: null is "could not be
|
||||
/// derived", which reads as "—" rather than a misleading zero.
|
||||
String formatKwh(double? value) => value == null ? "—" : "${value.toStringAsFixed(2)} kWh";
|
||||
|
||||
String formatKwhConsumption(double? value) =>
|
||||
value == null ? "—" : "${value.toStringAsFixed(1)} kWh/100km";
|
||||
|
||||
String formatKmPerKwh(double? value) =>
|
||||
value == null ? "—" : "${value.toStringAsFixed(2)} km/kWh";
|
||||
|
||||
const int _kmSoon = 1000;
|
||||
|
||||
enum StatusKey { unknown, ok, soon, overdue }
|
||||
|
||||
@@ -14,6 +14,12 @@ double? _asDoubleOrNull(dynamic v) => v is num ? v.toDouble() : null;
|
||||
DateTime? _asDate(dynamic v) =>
|
||||
v == null ? null : DateTime.tryParse(v.toString())?.toLocal();
|
||||
|
||||
/// A JSON array of strings — the key sets a car carries for what its page shows
|
||||
/// and in which order. Absent or null reads as empty, which every consumer takes
|
||||
/// to mean "nothing hidden" / "the default order".
|
||||
List<String> _asStrList(dynamic v) =>
|
||||
v is List ? v.map(_asStr).where((s) => s.isNotEmpty).toList() : const [];
|
||||
|
||||
/// The single optional file a record carries — a receipt, a scan, a photo of a
|
||||
/// part's box. Mirrors the API's embedded Attachment: the bytes are never in the
|
||||
/// JSON, only whether there are any and what they were stored as. Fetch them
|
||||
@@ -71,6 +77,25 @@ class Car {
|
||||
/// (or any code that constructs a Car without it) stay fully editable.
|
||||
final String access;
|
||||
|
||||
/// The manufacturer service this car came from ("toyota") and that service's
|
||||
/// own id for the vehicle (the VIN, for Toyota). Both blank for a car entered
|
||||
/// by hand. Written only by the link/import endpoints, never by a car edit —
|
||||
/// which is why _carPayload leaves them out.
|
||||
final String provider;
|
||||
final String providerVehicleId;
|
||||
|
||||
/// What this car's page does not show, and the order it lays out what it
|
||||
/// does. Properties of the car, so everyone it is shared with sees the same
|
||||
/// page. The hidden sets rather than the visible ones, so a tab or field added
|
||||
/// in a later release is on by default; the orders may be partial, and any key
|
||||
/// they leave out follows the ones they name. Written only through
|
||||
/// PUT /cars/{id}/view.
|
||||
final List<String> hiddenTabs;
|
||||
final List<String> hiddenFields;
|
||||
final List<String> tabOrder;
|
||||
final List<String> fieldOrder;
|
||||
final List<String> metricOrder;
|
||||
|
||||
Car({
|
||||
required this.id,
|
||||
required this.name,
|
||||
@@ -93,6 +118,13 @@ class Car {
|
||||
this.technicalCheckIntervalDays = 0,
|
||||
required this.currentKm,
|
||||
this.access = "owner",
|
||||
this.provider = "",
|
||||
this.providerVehicleId = "",
|
||||
this.hiddenTabs = const [],
|
||||
this.hiddenFields = const [],
|
||||
this.tabOrder = const [],
|
||||
this.fieldOrder = const [],
|
||||
this.metricOrder = const [],
|
||||
});
|
||||
|
||||
factory Car.fromJson(Map<String, dynamic> j) => Car(
|
||||
@@ -117,6 +149,13 @@ class Car {
|
||||
technicalCheckIntervalDays: _asInt(j["technicalCheckIntervalDays"]),
|
||||
currentKm: _asInt(j["currentKm"]),
|
||||
access: j["access"] == null ? "owner" : _asStr(j["access"]),
|
||||
provider: _asStr(j["provider"]),
|
||||
providerVehicleId: _asStr(j["providerVehicleId"]),
|
||||
hiddenTabs: _asStrList(j["hiddenTabs"]),
|
||||
hiddenFields: _asStrList(j["hiddenFields"]),
|
||||
tabOrder: _asStrList(j["tabOrder"]),
|
||||
fieldOrder: _asStrList(j["fieldOrder"]),
|
||||
metricOrder: _asStrList(j["metricOrder"]),
|
||||
);
|
||||
|
||||
bool get isOwner => access == "owner";
|
||||
@@ -385,6 +424,132 @@ class FuelStats {
|
||||
);
|
||||
}
|
||||
|
||||
/// One charge of an EV — the electric counterpart of [FuelEntry], and derived
|
||||
/// the same way: consumption is measured between full charges, so a top-up
|
||||
/// counts towards the next full one. The server computes every figure below the
|
||||
/// raw kWh/cost and omits any it could not derive.
|
||||
class ChargingSession with HasAttachment {
|
||||
final String id;
|
||||
final String car;
|
||||
final DateTime? date;
|
||||
final int km;
|
||||
final double kwh;
|
||||
final double cost;
|
||||
|
||||
/// Taken to the car's usual full point — the reference the efficiency windows
|
||||
/// are measured between.
|
||||
final bool fullCharge;
|
||||
|
||||
/// The car was charged before this without being logged, so the odometer span
|
||||
/// is not accounted for by the kWh on record. Any window containing it is
|
||||
/// left uncomputed rather than reported as implausibly efficient.
|
||||
final bool missedSession;
|
||||
|
||||
final String location;
|
||||
final String notes;
|
||||
|
||||
final double? pricePerKwh;
|
||||
final int? distanceKm;
|
||||
final double? kwhUsed;
|
||||
final double? consumptionKwh100;
|
||||
final double? kmPerKwh;
|
||||
final double? costPerKm;
|
||||
@override
|
||||
final String fileName;
|
||||
@override
|
||||
final bool hasFile;
|
||||
|
||||
ChargingSession({
|
||||
required this.id,
|
||||
required this.car,
|
||||
required this.date,
|
||||
required this.km,
|
||||
required this.kwh,
|
||||
required this.cost,
|
||||
this.fullCharge = true,
|
||||
this.missedSession = false,
|
||||
this.location = "",
|
||||
this.notes = "",
|
||||
this.pricePerKwh,
|
||||
this.distanceKm,
|
||||
this.kwhUsed,
|
||||
this.consumptionKwh100,
|
||||
this.kmPerKwh,
|
||||
this.costPerKm,
|
||||
this.fileName = "",
|
||||
this.hasFile = false,
|
||||
});
|
||||
|
||||
factory ChargingSession.fromJson(Map<String, dynamic> j) => ChargingSession(
|
||||
id: _asStr(j["id"]),
|
||||
car: _asStr(j["car"]),
|
||||
date: _asDate(j["date"]),
|
||||
km: _asInt(j["km"]),
|
||||
kwh: _asDouble(j["kwh"]),
|
||||
cost: _asDouble(j["cost"]),
|
||||
fullCharge: _asBool(j["fullCharge"]),
|
||||
missedSession: _asBool(j["missedSession"]),
|
||||
location: _asStr(j["location"]),
|
||||
notes: _asStr(j["notes"]),
|
||||
pricePerKwh: _asDoubleOrNull(j["pricePerKwh"]),
|
||||
distanceKm: _asIntOrNull(j["distanceKm"]),
|
||||
kwhUsed: _asDoubleOrNull(j["kwhUsed"]),
|
||||
consumptionKwh100: _asDoubleOrNull(j["consumptionKwh100"]),
|
||||
kmPerKwh: _asDoubleOrNull(j["kmPerKwh"]),
|
||||
costPerKm: _asDoubleOrNull(j["costPerKm"]),
|
||||
fileName: _asStr(j["fileName"]),
|
||||
hasFile: _asBool(j["hasFile"]),
|
||||
);
|
||||
}
|
||||
|
||||
/// A summary of a car's whole charging history. [trackedDistanceKm] is the
|
||||
/// distance covered by computable full-charge windows — the same caveat as
|
||||
/// [FuelStats.trackedDistanceKm].
|
||||
class ChargingStats {
|
||||
final int entries;
|
||||
final double totalKwh;
|
||||
final double totalCost;
|
||||
final int trackedDistanceKm;
|
||||
final double? avgConsumptionKwh100;
|
||||
final double? bestConsumptionKwh100;
|
||||
final double? worstConsumptionKwh100;
|
||||
final double? avgKmPerKwh;
|
||||
final double? avgPricePerKwh;
|
||||
final double? costPerKm;
|
||||
final DateTime? firstDate;
|
||||
final DateTime? lastDate;
|
||||
|
||||
const ChargingStats({
|
||||
this.entries = 0,
|
||||
this.totalKwh = 0,
|
||||
this.totalCost = 0,
|
||||
this.trackedDistanceKm = 0,
|
||||
this.avgConsumptionKwh100,
|
||||
this.bestConsumptionKwh100,
|
||||
this.worstConsumptionKwh100,
|
||||
this.avgKmPerKwh,
|
||||
this.avgPricePerKwh,
|
||||
this.costPerKm,
|
||||
this.firstDate,
|
||||
this.lastDate,
|
||||
});
|
||||
|
||||
factory ChargingStats.fromJson(Map<String, dynamic> j) => ChargingStats(
|
||||
entries: _asInt(j["entries"]),
|
||||
totalKwh: _asDouble(j["totalKwh"]),
|
||||
totalCost: _asDouble(j["totalCost"]),
|
||||
trackedDistanceKm: _asInt(j["trackedDistanceKm"]),
|
||||
avgConsumptionKwh100: _asDoubleOrNull(j["avgConsumptionKwh100"]),
|
||||
bestConsumptionKwh100: _asDoubleOrNull(j["bestConsumptionKwh100"]),
|
||||
worstConsumptionKwh100: _asDoubleOrNull(j["worstConsumptionKwh100"]),
|
||||
avgKmPerKwh: _asDoubleOrNull(j["avgKmPerKwh"]),
|
||||
avgPricePerKwh: _asDoubleOrNull(j["avgPricePerKwh"]),
|
||||
costPerKm: _asDoubleOrNull(j["costPerKm"]),
|
||||
firstDate: _asDate(j["firstDate"]),
|
||||
lastDate: _asDate(j["lastDate"]),
|
||||
);
|
||||
}
|
||||
|
||||
/// One workshop visit or repair — work done outside the routine service
|
||||
/// schedule (which lives in [ServiceRecord]). A broken alternator replaced at a
|
||||
/// garage belongs here; the annual oil change does not.
|
||||
@@ -891,3 +1056,208 @@ class AnkerControl {
|
||||
|
||||
double get meterKwh => meterWh / 1000.0;
|
||||
}
|
||||
|
||||
// --- vehicle providers (the connected-service tab) ---------------------------
|
||||
//
|
||||
// A provider is a manufacturer service a car can be linked to (MyToyota today).
|
||||
// Nothing below models an upstream schema: the API Server flattens whatever the
|
||||
// plugin returned into key/value pairs, so a provider adding a field surfaces it
|
||||
// here without a change to this file. See the API's vehicleproviders.go.
|
||||
|
||||
/// One registered provider and whether this user can currently use it.
|
||||
/// [detail] says, in one sentence, what to do about a closed gate.
|
||||
class VehicleProvider {
|
||||
final String id;
|
||||
final String label; // "MyToyota"
|
||||
final String service; // "Toyota Connected Europe"
|
||||
final bool connected;
|
||||
final String detail;
|
||||
|
||||
const VehicleProvider({
|
||||
required this.id,
|
||||
required this.label,
|
||||
this.service = "",
|
||||
this.connected = false,
|
||||
this.detail = "",
|
||||
});
|
||||
|
||||
factory VehicleProvider.fromJson(Map<String, dynamic> j) => VehicleProvider(
|
||||
id: _asStr(j["id"]),
|
||||
label: _asStr(j["label"]),
|
||||
service: _asStr(j["service"]),
|
||||
connected: _asBool(j["connected"]),
|
||||
detail: _asStr(j["detail"]),
|
||||
);
|
||||
}
|
||||
|
||||
/// One leaf of a provider payload, flattened to a dotted path.
|
||||
class ProviderField {
|
||||
final String key;
|
||||
final String value;
|
||||
const ProviderField({required this.key, required this.value});
|
||||
|
||||
factory ProviderField.fromJson(Map<String, dynamic> j) =>
|
||||
ProviderField(key: _asStr(j["key"]), value: _asStr(j["value"]));
|
||||
|
||||
static List<ProviderField> listFrom(dynamic v) => v is List
|
||||
? v.map((e) => ProviderField.fromJson(Map<String, dynamic>.from(e))).toList()
|
||||
: const [];
|
||||
}
|
||||
|
||||
/// One vehicle on the user's provider account.
|
||||
class ProviderVehicle {
|
||||
final String id; // the provider's own id (the VIN, for Toyota)
|
||||
final String vin;
|
||||
final String name;
|
||||
final String make;
|
||||
final String model;
|
||||
final int year;
|
||||
final String imageUrl;
|
||||
final List<ProviderField> fields;
|
||||
|
||||
/// Set when this user already has a car linked to this vehicle, so the UI can
|
||||
/// say so instead of offering to link it twice.
|
||||
final String linkedCarId;
|
||||
|
||||
const ProviderVehicle({
|
||||
required this.id,
|
||||
this.vin = "",
|
||||
this.name = "",
|
||||
this.make = "",
|
||||
this.model = "",
|
||||
this.year = 0,
|
||||
this.imageUrl = "",
|
||||
this.fields = const [],
|
||||
this.linkedCarId = "",
|
||||
});
|
||||
|
||||
factory ProviderVehicle.fromJson(Map<String, dynamic> j) => ProviderVehicle(
|
||||
id: _asStr(j["id"]),
|
||||
vin: _asStr(j["vin"]),
|
||||
name: _asStr(j["name"]),
|
||||
make: _asStr(j["make"]),
|
||||
model: _asStr(j["model"]),
|
||||
year: _asInt(j["year"]),
|
||||
imageUrl: _asStr(j["imageUrl"]),
|
||||
fields: ProviderField.listFrom(j["fields"]),
|
||||
linkedCarId: _asStr(j["linkedCarId"]),
|
||||
);
|
||||
|
||||
String get subtitle =>
|
||||
[make, model, year > 0 ? "$year" : ""].where((s) => s.isNotEmpty).join(" ");
|
||||
}
|
||||
|
||||
/// A headline reading lifted out of the sections — the few values worth showing
|
||||
/// large. [key] is a stable id the app localizes (car.provider.metrics.*).
|
||||
class ProviderMetric {
|
||||
final String key;
|
||||
final String value;
|
||||
final String unit;
|
||||
const ProviderMetric({required this.key, required this.value, this.unit = ""});
|
||||
|
||||
factory ProviderMetric.fromJson(Map<String, dynamic> j) => ProviderMetric(
|
||||
key: _asStr(j["key"]),
|
||||
value: _asStr(j["value"]),
|
||||
unit: _asStr(j["unit"]),
|
||||
);
|
||||
}
|
||||
|
||||
/// One capability's outcome. A section that fails carries its error and the rest
|
||||
/// still render: half a snapshot beats an error page.
|
||||
class ProviderSection {
|
||||
final String id;
|
||||
final String status; // ok | error | empty
|
||||
final String error;
|
||||
final List<ProviderField> fields;
|
||||
final bool truncated;
|
||||
|
||||
const ProviderSection({
|
||||
required this.id,
|
||||
this.status = "ok",
|
||||
this.error = "",
|
||||
this.fields = const [],
|
||||
this.truncated = false,
|
||||
});
|
||||
|
||||
factory ProviderSection.fromJson(Map<String, dynamic> j) => ProviderSection(
|
||||
id: _asStr(j["id"]),
|
||||
status: _asStr(j["status"]).isEmpty ? "ok" : _asStr(j["status"]),
|
||||
error: _asStr(j["error"]),
|
||||
fields: ProviderField.listFrom(j["fields"]),
|
||||
truncated: _asBool(j["truncated"]),
|
||||
);
|
||||
}
|
||||
|
||||
/// Everything a provider can currently tell us about one car.
|
||||
///
|
||||
/// [unavailable] replaces the payload when the provider cannot be reached for
|
||||
/// this car at all — not connected, or the vehicle is not on *this* user's
|
||||
/// account. It arrives as a 200, because "we asked and here is why there is
|
||||
/// nothing" is an answer rather than a failure.
|
||||
class ProviderSnapshot {
|
||||
final String provider;
|
||||
final String label;
|
||||
final String service;
|
||||
final bool unavailable;
|
||||
final String detail;
|
||||
final DateTime? fetchedAt;
|
||||
final ProviderVehicle? vehicle;
|
||||
final List<ProviderMetric> metrics;
|
||||
final List<ProviderSection> sections;
|
||||
|
||||
/// The odometer the provider reports when it is ahead of the car's stored
|
||||
/// reading — what the tab's "update odometer" offers. 0 when they agree.
|
||||
final int suggestedCurrentKm;
|
||||
|
||||
const ProviderSnapshot({
|
||||
this.provider = "",
|
||||
this.label = "",
|
||||
this.service = "",
|
||||
this.unavailable = false,
|
||||
this.detail = "",
|
||||
this.fetchedAt,
|
||||
this.vehicle,
|
||||
this.metrics = const [],
|
||||
this.sections = const [],
|
||||
this.suggestedCurrentKm = 0,
|
||||
});
|
||||
|
||||
factory ProviderSnapshot.fromJson(Map<String, dynamic> j) {
|
||||
final v = j["vehicle"];
|
||||
return ProviderSnapshot(
|
||||
provider: _asStr(j["provider"]),
|
||||
label: _asStr(j["label"]),
|
||||
service: _asStr(j["service"]),
|
||||
unavailable: _asBool(j["unavailable"]),
|
||||
detail: _asStr(j["detail"]),
|
||||
fetchedAt: _asDate(j["fetchedAt"]),
|
||||
vehicle: v is Map ? ProviderVehicle.fromJson(Map<String, dynamic>.from(v)) : null,
|
||||
metrics: j["metrics"] is List
|
||||
? (j["metrics"] as List)
|
||||
.map((e) => ProviderMetric.fromJson(Map<String, dynamic>.from(e)))
|
||||
.toList()
|
||||
: const [],
|
||||
sections: j["sections"] is List
|
||||
? (j["sections"] as List)
|
||||
.map((e) => ProviderSection.fromJson(Map<String, dynamic>.from(e)))
|
||||
.toList()
|
||||
: const [],
|
||||
suggestedCurrentKm: _asInt(j["suggestedCurrentKm"]),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// What POST /me/import created. Every count is of brand-new records — the
|
||||
/// import never merges with or overwrites anything already there.
|
||||
class ImportResult {
|
||||
final int cars;
|
||||
final int services;
|
||||
final int parts;
|
||||
const ImportResult({this.cars = 0, this.services = 0, this.parts = 0});
|
||||
|
||||
factory ImportResult.fromJson(Map<String, dynamic> j) => ImportResult(
|
||||
cars: _asInt(j["carsImported"]),
|
||||
services: _asInt(j["servicesImported"]),
|
||||
parts: _asInt(j["partsImported"]),
|
||||
);
|
||||
}
|
||||
@@ -1,12 +1,15 @@
|
||||
import "package:flutter/material.dart";
|
||||
|
||||
import "../api.dart";
|
||||
import "../i18n.dart";
|
||||
import "../main.dart";
|
||||
import "../models.dart";
|
||||
import "../format.dart";
|
||||
import "../theme.dart";
|
||||
import "../widgets/attachment_field.dart";
|
||||
import "car_form_sheet.dart";
|
||||
import "car_view_sheet.dart";
|
||||
import "provider_tab.dart";
|
||||
import "record_form_sheets.dart";
|
||||
|
||||
/// Serializes a car to the full update payload. The API's updateCar rewrites
|
||||
@@ -48,10 +51,17 @@ class _CarDetailData {
|
||||
final List<MaintenanceEntry> maintenance;
|
||||
final List<FuelEntry> fuel;
|
||||
final FuelStats fuelStats;
|
||||
final List<ChargingSession> charging;
|
||||
final ChargingStats chargingStats;
|
||||
final List<CarDocument> documents;
|
||||
final List<Part> parts;
|
||||
final List<Reminder> reminders;
|
||||
|
||||
/// The manufacturer services this user has connected. Only read to decide
|
||||
/// whether the connected-service tab is on offer for a car that has no link
|
||||
/// yet — the tab loads its own data once it is open.
|
||||
final List<VehicleProvider> providers;
|
||||
|
||||
_CarDetailData({
|
||||
required this.car,
|
||||
required this.services,
|
||||
@@ -59,9 +69,12 @@ class _CarDetailData {
|
||||
required this.maintenance,
|
||||
required this.fuel,
|
||||
required this.fuelStats,
|
||||
required this.charging,
|
||||
required this.chargingStats,
|
||||
required this.documents,
|
||||
required this.parts,
|
||||
required this.reminders,
|
||||
required this.providers,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -85,9 +98,15 @@ class _CarDetailScreenState extends State<CarDetailScreen> {
|
||||
apiClient.listCarMaintenance(widget.carId),
|
||||
apiClient.listCarFuelEntries(widget.carId),
|
||||
apiClient.getCarFuelStats(widget.carId),
|
||||
apiClient.listCarChargingSessions(widget.carId),
|
||||
apiClient.getCarChargingStats(widget.carId),
|
||||
apiClient.listCarDocuments(widget.carId),
|
||||
apiClient.listCarParts(widget.carId),
|
||||
apiClient.listCarReminders(widget.carId),
|
||||
// Only decides whether one tab is offered, so it must not be able to take
|
||||
// the whole page down with it — a provider plugin that is misconfigured
|
||||
// (or a server too old to know the endpoint) leaves the tab off instead.
|
||||
apiClient.listVehicleProviders().catchError((_) => <VehicleProvider>[]),
|
||||
]);
|
||||
return _CarDetailData(
|
||||
car: results[0] as Car,
|
||||
@@ -96,9 +115,12 @@ class _CarDetailScreenState extends State<CarDetailScreen> {
|
||||
maintenance: results[3] as List<MaintenanceEntry>,
|
||||
fuel: results[4] as List<FuelEntry>,
|
||||
fuelStats: results[5] as FuelStats,
|
||||
documents: results[6] as List<CarDocument>,
|
||||
parts: results[7] as List<Part>,
|
||||
reminders: results[8] as List<Reminder>,
|
||||
charging: results[6] as List<ChargingSession>,
|
||||
chargingStats: results[7] as ChargingStats,
|
||||
documents: results[8] as List<CarDocument>,
|
||||
parts: results[9] as List<Part>,
|
||||
reminders: results[10] as List<Reminder>,
|
||||
providers: results[11] as List<VehicleProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -304,8 +326,15 @@ class _CarDetailScreenState extends State<CarDetailScreen> {
|
||||
final latest = data.services.isNotEmpty ? data.services.first : null;
|
||||
final status = serviceStatus(latest, car);
|
||||
|
||||
final tabKeys = _tabKeys(car, data.providers);
|
||||
|
||||
return DefaultTabController(
|
||||
length: 8,
|
||||
// The tab set is a property of the car: the view picker switches
|
||||
// tabs off, and linking a provider adds one. Keying the controller
|
||||
// on it rebuilds the controller instead of leaving it addressing a
|
||||
// length that no longer exists.
|
||||
key: ValueKey(tabKeys.join("/")),
|
||||
length: tabKeys.length,
|
||||
child: Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text(car.name),
|
||||
@@ -316,6 +345,12 @@ class _CarDetailScreenState extends State<CarDetailScreen> {
|
||||
icon: const Icon(Icons.person_add_alt),
|
||||
onPressed: () => _shareCar(car),
|
||||
),
|
||||
if (car.canWrite)
|
||||
IconButton(
|
||||
tooltip: t("car.viewPicker.open"),
|
||||
icon: const Icon(Icons.tune),
|
||||
onPressed: () => _openViewPicker(car, data.providers),
|
||||
),
|
||||
if (car.canWrite)
|
||||
IconButton(
|
||||
tooltip: "Edit car",
|
||||
@@ -336,18 +371,11 @@ class _CarDetailScreenState extends State<CarDetailScreen> {
|
||||
_deleteCar(car, data.services.length, data.parts.length),
|
||||
),
|
||||
],
|
||||
// Same order as the web app's CarDetail tabs.
|
||||
bottom: const TabBar(
|
||||
bottom: TabBar(
|
||||
isScrollable: true,
|
||||
tabs: [
|
||||
Tab(text: "Information"),
|
||||
Tab(text: "Service history"),
|
||||
Tab(text: "Technical check history"),
|
||||
Tab(text: "Maintenance"),
|
||||
Tab(text: "Fuel"),
|
||||
Tab(text: "Documents"),
|
||||
Tab(text: "Parts catalog"),
|
||||
Tab(text: "Reminders"),
|
||||
for (final key in tabKeys)
|
||||
Tab(text: _tabLabel(key, car, data.providers)),
|
||||
],
|
||||
),
|
||||
),
|
||||
@@ -367,144 +395,7 @@ class _CarDetailScreenState extends State<CarDetailScreen> {
|
||||
),
|
||||
Expanded(
|
||||
child: TabBarView(
|
||||
children: [
|
||||
// Information tab
|
||||
_InfoTab(car: car, latest: latest),
|
||||
// Service history tab
|
||||
_TabList(
|
||||
empty: data.services.isEmpty ? "No service records yet." : null,
|
||||
onAdd: car.canWrite ? () => _addService(car) : null,
|
||||
addLabel: "Add service",
|
||||
children: data.services
|
||||
.map((s) => _ServiceTile(
|
||||
record: s,
|
||||
onEdit: car.canWrite ? () => _editService(car, s) : null,
|
||||
onDelete: car.canWrite ? () => _deleteService(s) : null,
|
||||
))
|
||||
.toList(),
|
||||
),
|
||||
// Technical check history tab
|
||||
_TabList(
|
||||
empty: data.technicalChecks.isEmpty ? "No technical checks yet." : null,
|
||||
onAdd: car.canWrite
|
||||
? () => _sheet(TechnicalCheckSheet(carId: car.id, car: car))
|
||||
: null,
|
||||
addLabel: "Add check",
|
||||
children: data.technicalChecks
|
||||
.map((c) => _TechnicalCheckTile(
|
||||
check: c,
|
||||
onEdit: car.canWrite
|
||||
? () => _sheet(
|
||||
TechnicalCheckSheet(carId: car.id, car: car, check: c))
|
||||
: null,
|
||||
onDelete: car.canWrite
|
||||
? () => _deleteRecord("technical check",
|
||||
() => apiClient.deleteTechnicalCheck(c.id))
|
||||
: null,
|
||||
))
|
||||
.toList(),
|
||||
),
|
||||
// Maintenance tab
|
||||
_TabList(
|
||||
empty: data.maintenance.isEmpty ? "No workshop visits yet." : null,
|
||||
onAdd:
|
||||
car.canWrite ? () => _sheet(MaintenanceSheet(carId: car.id)) : null,
|
||||
addLabel: "Log visit",
|
||||
children: data.maintenance
|
||||
.map((m) => _MaintenanceTile(
|
||||
entry: m,
|
||||
onEdit: car.canWrite
|
||||
? () => _sheet(MaintenanceSheet(carId: car.id, entry: m))
|
||||
: null,
|
||||
onDelete: car.canWrite
|
||||
? () => _deleteRecord("workshop visit",
|
||||
() => apiClient.deleteMaintenance(m.id))
|
||||
: null,
|
||||
))
|
||||
.toList(),
|
||||
),
|
||||
// Fuel tab — the stats panel sits above the refill list.
|
||||
_TabList(
|
||||
empty: null,
|
||||
onAdd: car.canWrite ? () => _sheet(FuelSheet(carId: car.id)) : null,
|
||||
addLabel: "Log refill",
|
||||
children: [
|
||||
_FuelStatsPanel(stats: data.fuelStats),
|
||||
const SizedBox(height: 8),
|
||||
if (data.fuel.isEmpty)
|
||||
const _Empty("No refills yet.")
|
||||
else
|
||||
...data.fuel.reversed.map((f) => _FuelTile(
|
||||
entry: f,
|
||||
onEdit: car.canWrite
|
||||
? () => _sheet(FuelSheet(carId: car.id, entry: f))
|
||||
: null,
|
||||
onDelete: car.canWrite
|
||||
? () => _deleteRecord(
|
||||
"refill", () => apiClient.deleteFuelEntry(f.id))
|
||||
: null,
|
||||
)),
|
||||
],
|
||||
),
|
||||
// Documents tab
|
||||
_TabList(
|
||||
empty: data.documents.isEmpty ? "No documents yet." : null,
|
||||
onAdd: car.canWrite ? () => _sheet(DocumentSheet(carId: car.id)) : null,
|
||||
addLabel: "Add document",
|
||||
children: data.documents
|
||||
.map((d) => _DocumentTile(
|
||||
doc: d,
|
||||
onEdit: car.canWrite
|
||||
? () => _sheet(DocumentSheet(carId: car.id, doc: d))
|
||||
: null,
|
||||
onDelete: car.canWrite
|
||||
? () => _deleteRecord(
|
||||
"document", () => apiClient.deleteDocument(d.id))
|
||||
: null,
|
||||
))
|
||||
.toList(),
|
||||
),
|
||||
// Parts catalog tab
|
||||
_TabList(
|
||||
empty: data.parts.isEmpty ? "No parts yet." : null,
|
||||
onAdd: car.canWrite ? () => _addPart(car) : null,
|
||||
addLabel: "Add part",
|
||||
children: data.parts
|
||||
.map((p) => _PartTile(
|
||||
part: p,
|
||||
onEdit: car.canWrite ? () => _editPart(car, p) : null,
|
||||
onDelete: car.canWrite ? () => _deletePart(p) : null,
|
||||
))
|
||||
.toList(),
|
||||
),
|
||||
// Reminders tab
|
||||
_TabList(
|
||||
empty: data.reminders.isEmpty ? "No reminders yet." : null,
|
||||
onAdd: car.canWrite
|
||||
? () => _sheet(ReminderSheet(carId: car.id, car: car))
|
||||
: null,
|
||||
addLabel: "Add reminder",
|
||||
children: data.reminders
|
||||
.map((r) => _ReminderTile(
|
||||
reminder: r,
|
||||
// Auto reminders are derived from a document or
|
||||
// service record, so they are read-only here —
|
||||
// edit the record they came from instead.
|
||||
onEdit: car.canWrite && !r.auto
|
||||
? () => _sheet(
|
||||
ReminderSheet(carId: car.id, car: car, reminder: r))
|
||||
: null,
|
||||
onDelete: car.canWrite && !r.auto
|
||||
? () => _deleteRecord(
|
||||
"reminder", () => apiClient.deleteReminder(r.id))
|
||||
: null,
|
||||
onComplete: car.canWrite && !r.auto && !r.done
|
||||
? () => _completeReminder(r)
|
||||
: null,
|
||||
))
|
||||
.toList(),
|
||||
),
|
||||
],
|
||||
children: [for (final key in tabKeys) _tabBody(key, data)],
|
||||
),
|
||||
),
|
||||
],
|
||||
@@ -515,6 +406,221 @@ class _CarDetailScreenState extends State<CarDetailScreen> {
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// --- which tabs this car shows -------------------------------------------
|
||||
|
||||
/// Whether the connected-service tab is on offer. It shows for a linked car,
|
||||
/// and also for an unlinked one as long as this user has some manufacturer
|
||||
/// account connected — that is where the tab offers to link it. A user with
|
||||
/// nothing connected never sees the tab at all.
|
||||
bool _showProviderTab(Car car, List<VehicleProvider> providers) =>
|
||||
car.provider.isNotEmpty || providers.any((p) => p.connected);
|
||||
|
||||
/// The linked provider's display name ("MyToyota"), falling back to the raw
|
||||
/// plugin name and then to the generic tab label.
|
||||
String _providerLabel(Car car, List<VehicleProvider> providers) {
|
||||
for (final p in providers) {
|
||||
if (p.id == car.provider) return p.label;
|
||||
}
|
||||
return car.provider.isEmpty ? t("car.tabs.connected") : car.provider;
|
||||
}
|
||||
|
||||
/// The tabs to show, in this car's arrangement: its stored order applied to
|
||||
/// the catalogue, minus the ones switched off, minus the connected service
|
||||
/// when it does not apply.
|
||||
List<String> _tabKeys(Car car, List<VehicleProvider> providers) =>
|
||||
arrangeKeys(kCarTabKeys, car.tabOrder)
|
||||
.where((key) => !car.hiddenTabs.contains(key))
|
||||
.where((key) => key != "provider" || _showProviderTab(car, providers))
|
||||
.toList();
|
||||
|
||||
String _tabLabel(String key, Car car, List<VehicleProvider> providers) =>
|
||||
key == "provider" ? _providerLabel(car, providers) : t("car.tabs.$key");
|
||||
|
||||
Future<void> _openViewPicker(Car car, List<VehicleProvider> providers) async {
|
||||
final updated = await showModalBottomSheet<Car>(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
builder: (_) => CarViewSheet(
|
||||
car: car,
|
||||
showProvider: _showProviderTab(car, providers),
|
||||
providerLabel: car.provider.isEmpty ? "" : _providerLabel(car, providers),
|
||||
),
|
||||
);
|
||||
if (updated != null) _reload();
|
||||
}
|
||||
|
||||
/// One tab's content, by key. The keys are the web app's, so the two apps
|
||||
/// cannot drift on what a stored arrangement means.
|
||||
Widget _tabBody(String key, _CarDetailData data) {
|
||||
final car = data.car;
|
||||
final latest = data.services.isNotEmpty ? data.services.first : null;
|
||||
|
||||
switch (key) {
|
||||
case "provider":
|
||||
return ProviderTab(car: car, onCarUpdated: (_) => _reload());
|
||||
|
||||
case "info":
|
||||
return _InfoTab(car: car, latest: latest);
|
||||
|
||||
case "services":
|
||||
return _TabList(
|
||||
empty: data.services.isEmpty ? "No service records yet." : null,
|
||||
onAdd: car.canWrite ? () => _addService(car) : null,
|
||||
addLabel: "Add service",
|
||||
children: data.services
|
||||
.map((s) => _ServiceTile(
|
||||
record: s,
|
||||
onEdit: car.canWrite ? () => _editService(car, s) : null,
|
||||
onDelete: car.canWrite ? () => _deleteService(s) : null,
|
||||
))
|
||||
.toList(),
|
||||
);
|
||||
|
||||
case "technical":
|
||||
return _TabList(
|
||||
empty: data.technicalChecks.isEmpty ? "No technical checks yet." : null,
|
||||
onAdd: car.canWrite ? () => _sheet(TechnicalCheckSheet(carId: car.id, car: car)) : null,
|
||||
addLabel: "Add check",
|
||||
children: data.technicalChecks
|
||||
.map((c) => _TechnicalCheckTile(
|
||||
check: c,
|
||||
onEdit: car.canWrite
|
||||
? () => _sheet(TechnicalCheckSheet(carId: car.id, car: car, check: c))
|
||||
: null,
|
||||
onDelete: car.canWrite
|
||||
? () => _deleteRecord(
|
||||
"technical check", () => apiClient.deleteTechnicalCheck(c.id))
|
||||
: null,
|
||||
))
|
||||
.toList(),
|
||||
);
|
||||
|
||||
case "maintenance":
|
||||
return _TabList(
|
||||
empty: data.maintenance.isEmpty ? "No workshop visits yet." : null,
|
||||
onAdd: car.canWrite ? () => _sheet(MaintenanceSheet(carId: car.id)) : null,
|
||||
addLabel: "Log visit",
|
||||
children: data.maintenance
|
||||
.map((m) => _MaintenanceTile(
|
||||
entry: m,
|
||||
onEdit: car.canWrite
|
||||
? () => _sheet(MaintenanceSheet(carId: car.id, entry: m))
|
||||
: null,
|
||||
onDelete: car.canWrite
|
||||
? () => _deleteRecord(
|
||||
"workshop visit", () => apiClient.deleteMaintenance(m.id))
|
||||
: null,
|
||||
))
|
||||
.toList(),
|
||||
);
|
||||
|
||||
// The stats panel sits above the refill list.
|
||||
case "fuel":
|
||||
return _TabList(
|
||||
empty: null,
|
||||
onAdd: car.canWrite ? () => _sheet(FuelSheet(carId: car.id)) : null,
|
||||
addLabel: "Log refill",
|
||||
children: [
|
||||
_FuelStatsPanel(stats: data.fuelStats),
|
||||
const SizedBox(height: 8),
|
||||
if (data.fuel.isEmpty)
|
||||
const _Empty("No refills yet.")
|
||||
else
|
||||
...data.fuel.reversed.map((f) => _FuelTile(
|
||||
entry: f,
|
||||
onEdit: car.canWrite ? () => _sheet(FuelSheet(carId: car.id, entry: f)) : null,
|
||||
onDelete: car.canWrite
|
||||
? () => _deleteRecord("refill", () => apiClient.deleteFuelEntry(f.id))
|
||||
: null,
|
||||
)),
|
||||
],
|
||||
);
|
||||
|
||||
// The electric twin of the fuel tab, laid out the same way.
|
||||
case "charging":
|
||||
return _TabList(
|
||||
empty: null,
|
||||
onAdd: car.canWrite ? () => _sheet(ChargingSheet(carId: car.id)) : null,
|
||||
addLabel: t("car.charging.add"),
|
||||
children: [
|
||||
_ChargingStatsPanel(stats: data.chargingStats),
|
||||
const SizedBox(height: 8),
|
||||
if (data.charging.isEmpty)
|
||||
_Empty(t("car.charging.empty"))
|
||||
else
|
||||
...data.charging.reversed.map((c) => _ChargingTile(
|
||||
entry: c,
|
||||
onEdit: car.canWrite
|
||||
? () => _sheet(ChargingSheet(carId: car.id, entry: c))
|
||||
: null,
|
||||
onDelete: car.canWrite
|
||||
? () => _deleteRecord(
|
||||
"charge", () => apiClient.deleteChargingSession(c.id))
|
||||
: null,
|
||||
)),
|
||||
],
|
||||
);
|
||||
|
||||
case "documents":
|
||||
return _TabList(
|
||||
empty: data.documents.isEmpty ? "No documents yet." : null,
|
||||
onAdd: car.canWrite ? () => _sheet(DocumentSheet(carId: car.id)) : null,
|
||||
addLabel: "Add document",
|
||||
children: data.documents
|
||||
.map((d) => _DocumentTile(
|
||||
doc: d,
|
||||
onEdit:
|
||||
car.canWrite ? () => _sheet(DocumentSheet(carId: car.id, doc: d)) : null,
|
||||
onDelete: car.canWrite
|
||||
? () => _deleteRecord("document", () => apiClient.deleteDocument(d.id))
|
||||
: null,
|
||||
))
|
||||
.toList(),
|
||||
);
|
||||
|
||||
case "parts":
|
||||
return _TabList(
|
||||
empty: data.parts.isEmpty ? "No parts yet." : null,
|
||||
onAdd: car.canWrite ? () => _addPart(car) : null,
|
||||
addLabel: "Add part",
|
||||
children: data.parts
|
||||
.map((p) => _PartTile(
|
||||
part: p,
|
||||
onEdit: car.canWrite ? () => _editPart(car, p) : null,
|
||||
onDelete: car.canWrite ? () => _deletePart(p) : null,
|
||||
))
|
||||
.toList(),
|
||||
);
|
||||
|
||||
case "reminders":
|
||||
return _TabList(
|
||||
empty: data.reminders.isEmpty ? "No reminders yet." : null,
|
||||
onAdd: car.canWrite ? () => _sheet(ReminderSheet(carId: car.id, car: car)) : null,
|
||||
addLabel: "Add reminder",
|
||||
children: data.reminders
|
||||
.map((r) => _ReminderTile(
|
||||
reminder: r,
|
||||
// Auto reminders are derived from a document or service
|
||||
// record, so they are read-only here — edit the record they
|
||||
// came from instead.
|
||||
onEdit: car.canWrite && !r.auto
|
||||
? () => _sheet(ReminderSheet(carId: car.id, car: car, reminder: r))
|
||||
: null,
|
||||
onDelete: car.canWrite && !r.auto
|
||||
? () => _deleteRecord("reminder", () => apiClient.deleteReminder(r.id))
|
||||
: null,
|
||||
onComplete: car.canWrite && !r.auto && !r.done
|
||||
? () => _completeReminder(r)
|
||||
: null,
|
||||
))
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
// Unreachable for the keys above; a key from a newer release reaching an
|
||||
// older build lands here rather than taking the page down.
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
}
|
||||
|
||||
/// A scrollable tab body: an optional "+ Add" button, an empty-state message, or
|
||||
@@ -591,13 +697,44 @@ class _StatusHeader extends StatelessWidget {
|
||||
|
||||
/// Information tab: the car's spec details (oil specs, odometer, interval, next
|
||||
/// due, VIN) in a scrollable card.
|
||||
///
|
||||
/// Which rows show and in which order belongs to the car, not to this device —
|
||||
/// everyone it is shared with sees the same page. Both are edited in the view
|
||||
/// picker (see [CarViewSheet]).
|
||||
class _InfoTab extends StatelessWidget {
|
||||
final Car car;
|
||||
final ServiceRecord? latest;
|
||||
const _InfoTab({required this.car, required this.latest});
|
||||
|
||||
/// Every row this tab can show, by the key the car's arrangement names it by.
|
||||
/// Keys mirror hideableCarFields in the API's cars.go and car.info.* in the
|
||||
/// translation files.
|
||||
Map<String, String> _values() => {
|
||||
"oilSpec": _orDash(car.oilSpec),
|
||||
"transmissionOil": _orDash(car.transmissionOilSpec),
|
||||
"differentialOil": _orDash(car.differentialOilSpec),
|
||||
"brakeFluid": _orDash(car.brakeFluidSpec),
|
||||
"coolant": _orDash(car.coolantSpec),
|
||||
"odometer": formatKm(car.currentKm),
|
||||
"serviceInterval":
|
||||
"${car.serviceIntervalDays} days · ${formatKm(car.serviceIntervalKm)}",
|
||||
"nextDue":
|
||||
"${formatDate(latest?.nextServiceDate)} · ${formatKm(latest?.nextServiceKm)}",
|
||||
"registrationPlate": _orDash(car.registration),
|
||||
"registrationCountry": _orDash(car.registrationCountry),
|
||||
"vin": _orDash(car.vin),
|
||||
"fuelType": _fuelLabel(car.fuelType),
|
||||
"buildDate": _dateOrDash(car.buildDate),
|
||||
"firstRegistration": _dateOrDash(car.firstRegistrationDate),
|
||||
};
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final values = _values();
|
||||
final keys = arrangeKeys(kCarInfoFieldKeys, car.fieldOrder)
|
||||
.where((key) => !car.hiddenFields.contains(key))
|
||||
.toList();
|
||||
|
||||
return ListView(
|
||||
padding: const EdgeInsets.fromLTRB(12, 12, 12, 80),
|
||||
children: [
|
||||
@@ -612,22 +749,22 @@ class _InfoTab extends StatelessWidget {
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
_kv(context, "Engine oil spec", _orDash(car.oilSpec)),
|
||||
_kv(context, "Transmission oil spec", _orDash(car.transmissionOilSpec)),
|
||||
_kv(context, "Differential oil spec", _orDash(car.differentialOilSpec)),
|
||||
_kv(context, "Brake fluid spec", _orDash(car.brakeFluidSpec)),
|
||||
_kv(context, "Coolant spec", _orDash(car.coolantSpec)),
|
||||
_kv(context, "Current odometer", formatKm(car.currentKm)),
|
||||
_kv(context, "Service interval", "${car.serviceIntervalDays} days · ${formatKm(car.serviceIntervalKm)}"),
|
||||
_kv(context, "Technical check interval",
|
||||
"${car.technicalCheckIntervalDays > 0 ? car.technicalCheckIntervalDays : 365} days"),
|
||||
_kv(context, "Next due", "${formatDate(latest?.nextServiceDate)} · ${formatKm(latest?.nextServiceKm)}"),
|
||||
_kv(context, "Registration plate", _orDash(car.registration)),
|
||||
_kv(context, "Registration country", _orDash(car.registrationCountry)),
|
||||
_kv(context, "VIN", _orDash(car.vin)),
|
||||
_kv(context, "Fuel type", _fuelLabel(car.fuelType)),
|
||||
_kv(context, "Build date", _dateOrDash(car.buildDate)),
|
||||
_kv(context, "First registration", _dateOrDash(car.firstRegistrationDate)),
|
||||
if (keys.isEmpty)
|
||||
Text(t("car.info.allHidden"),
|
||||
style: TextStyle(color: DriverVault.muted(context)))
|
||||
else
|
||||
for (final key in keys) ...[
|
||||
_kv(context, t("car.info.$key"), values[key] ?? "—"),
|
||||
// The roadworthiness cycle is the car's other interval, and
|
||||
// reads as a footnote to the service one rather than a row
|
||||
// of its own — so it follows it, and goes when it goes.
|
||||
if (key == "serviceInterval")
|
||||
_kv(
|
||||
context,
|
||||
t("car.info.technicalCheckInterval"),
|
||||
"${car.technicalCheckIntervalDays > 0 ? car.technicalCheckIntervalDays : 365} days",
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
@@ -1082,6 +1219,145 @@ class _FuelStatsPanel extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
/// The charging summary, the electric twin of [_FuelStatsPanel]. Same caveat on
|
||||
/// the tracked distance: it covers the full-charge windows only.
|
||||
class _ChargingStatsPanel extends StatelessWidget {
|
||||
final ChargingStats stats;
|
||||
const _ChargingStatsPanel({required this.stats});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (stats.entries == 0) return const SizedBox.shrink();
|
||||
return _RecordCard(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(t("car.charging.title"), style: const TextStyle(fontWeight: FontWeight.w600)),
|
||||
const SizedBox(height: 8),
|
||||
Wrap(
|
||||
spacing: 16,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
_stat(context, t("car.charging.average"),
|
||||
formatKwhConsumption(stats.avgConsumptionKwh100)),
|
||||
_stat(context, t("car.charging.best"),
|
||||
formatKwhConsumption(stats.bestConsumptionKwh100)),
|
||||
_stat(context, t("car.charging.worst"),
|
||||
formatKwhConsumption(stats.worstConsumptionKwh100)),
|
||||
_stat(context, t("car.charging.average"), formatKmPerKwh(stats.avgKmPerKwh)),
|
||||
_stat(context, t("car.charging.costPerKm"), formatMoney(stats.costPerKm)),
|
||||
_stat(context, t("car.charging.colPerKwh"), formatMoney(stats.avgPricePerKwh)),
|
||||
_stat(context, t("car.charging.totalKwh"), formatKwh(stats.totalKwh)),
|
||||
_stat(context, t("car.charging.totalSpent"), formatMoney(stats.totalCost)),
|
||||
_stat(context, t("car.charging.sessions"), "${stats.entries}"),
|
||||
_stat(context, t("car.charging.trackedDistance"), formatKm(stats.trackedDistanceKm)),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
// Without this the tracked distance reads as a mistake whenever the
|
||||
// history starts or ends on a partial charge.
|
||||
_sub(context, t("car.charging.subtitle")),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _stat(BuildContext context, String label, String value) => SizedBox(
|
||||
width: 150,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(label, style: TextStyle(fontSize: 11, color: DriverVault.muted(context))),
|
||||
Text(value,
|
||||
style: DriverVault.mono(context,
|
||||
size: 13,
|
||||
weight: FontWeight.w600,
|
||||
color: Theme.of(context).colorScheme.onSurface)),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class _ChargingTile extends StatelessWidget {
|
||||
final ChargingSession entry;
|
||||
final VoidCallback? onEdit;
|
||||
final VoidCallback? onDelete;
|
||||
const _ChargingTile({required this.entry, this.onEdit, this.onDelete});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return _RecordCard(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Text(formatDate(entry.date), style: const TextStyle(fontWeight: FontWeight.w600)),
|
||||
Row(children: [
|
||||
Text(formatKm(entry.km), style: const TextStyle(fontSize: 13)),
|
||||
if (onEdit != null || onDelete != null)
|
||||
_RowMenu(onEdit: onEdit, onDelete: onDelete),
|
||||
]),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
_sub(
|
||||
context,
|
||||
[
|
||||
formatKwh(entry.kwh),
|
||||
if (entry.cost > 0) formatMoney(entry.cost),
|
||||
if (entry.pricePerKwh != null)
|
||||
"${entry.pricePerKwh!.toStringAsFixed(3)}/kWh",
|
||||
].join(" · ")),
|
||||
const SizedBox(height: 6),
|
||||
Wrap(spacing: 6, runSpacing: 6, children: [
|
||||
_tag(context, entry.fullCharge ? t("forms.charging.fullCharge") : t("car.charging.partial"),
|
||||
muted: !entry.fullCharge),
|
||||
if (entry.missedSession) _tag(context, t("car.charging.gap"), warn: true),
|
||||
if (entry.location.isNotEmpty) _tag(context, entry.location, muted: true),
|
||||
]),
|
||||
// Consumption exists only on a full charge that closes a computable
|
||||
// window; anything else has nothing to report.
|
||||
if (entry.consumptionKwh100 != null) ...[
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
"${formatKwhConsumption(entry.consumptionKwh100)} · ${formatKmPerKwh(entry.kmPerKwh)}"
|
||||
" over ${formatKm(entry.distanceKm)}",
|
||||
style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w600),
|
||||
),
|
||||
],
|
||||
_AttachmentLine(path: "/charging-sessions", id: entry.id, record: entry),
|
||||
if (entry.notes.isNotEmpty) ...[
|
||||
const SizedBox(height: 6),
|
||||
Text(entry.notes, style: const TextStyle(fontSize: 12, fontStyle: FontStyle.italic)),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _tag(BuildContext context, String label, {bool muted = false, bool warn = false}) {
|
||||
final dark = DriverVault.isDark(context);
|
||||
final Color bg, fg;
|
||||
if (warn) {
|
||||
bg = dark ? DriverVault.warningSoftDark : DriverVault.warningSoft;
|
||||
fg = DriverVault.warning;
|
||||
} else if (muted) {
|
||||
bg = dark ? DriverVault.darkSunken : DriverVault.ink50;
|
||||
fg = DriverVault.muted(context);
|
||||
} else {
|
||||
bg = dark ? DriverVault.successSoftDark : DriverVault.successSoft;
|
||||
fg = DriverVault.success;
|
||||
}
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
|
||||
decoration: BoxDecoration(color: bg, borderRadius: BorderRadius.circular(6)),
|
||||
child: Text(label, style: TextStyle(fontSize: 11, color: fg, fontWeight: FontWeight.w600)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _FuelTile extends StatelessWidget {
|
||||
final FuelEntry entry;
|
||||
final VoidCallback? onEdit;
|
||||
|
||||
@@ -0,0 +1,332 @@
|
||||
import "package:flutter/material.dart";
|
||||
|
||||
import "../i18n.dart";
|
||||
import "../main.dart";
|
||||
import "../models.dart";
|
||||
import "../theme.dart";
|
||||
|
||||
/// Every tab a car's page can show, in the order they appear when the car has no
|
||||
/// arrangement of its own. Information sits second because the connected
|
||||
/// service, when there is one, is what you came to look at.
|
||||
///
|
||||
/// Mirrors ALL_TAB_KEYS in the web CarDetail and arrangeableCarTabs in the API's
|
||||
/// cars.go — the server rejects any key outside that set.
|
||||
const List<String> kCarTabKeys = [
|
||||
"provider",
|
||||
"info",
|
||||
"services",
|
||||
"technical",
|
||||
"maintenance",
|
||||
"fuel",
|
||||
"charging",
|
||||
"documents",
|
||||
"parts",
|
||||
"reminders",
|
||||
];
|
||||
|
||||
/// The tabs that can be switched off. "info" is deliberately absent: it is the
|
||||
/// car itself, and a page with no tabs left would be a dead end. It can still be
|
||||
/// moved, which is why the two lists are separate.
|
||||
const List<String> kHideableCarTabKeys = [
|
||||
"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.
|
||||
const List<String> kCarInfoFieldKeys = [
|
||||
"oilSpec",
|
||||
"transmissionOil",
|
||||
"differentialOil",
|
||||
"brakeFluid",
|
||||
"coolant",
|
||||
"odometer",
|
||||
"serviceInterval",
|
||||
"nextDue",
|
||||
"registrationPlate",
|
||||
"registrationCountry",
|
||||
"vin",
|
||||
"fuelType",
|
||||
"buildDate",
|
||||
"firstRegistration",
|
||||
];
|
||||
|
||||
/// Applies a car's stored arrangement to a catalogue of keys.
|
||||
///
|
||||
/// The stored order may be partial and may name keys this release does not know:
|
||||
/// anything unrecognised is dropped, and any key it leaves out follows the ones
|
||||
/// it names. That is what puts a tab or row added in a later release at the end
|
||||
/// of somebody's page rather than in the middle of it.
|
||||
List<String> arrangeKeys(List<String> catalogue, List<String> order) {
|
||||
final arranged = <String>[];
|
||||
for (final key in order) {
|
||||
if (catalogue.contains(key) && !arranged.contains(key)) arranged.add(key);
|
||||
}
|
||||
arranged.addAll(catalogue.where((k) => !arranged.contains(k)));
|
||||
return arranged;
|
||||
}
|
||||
|
||||
/// What this car's page shows: which tabs and Information rows are on, and the
|
||||
/// order of each. Mirrors the web's view picker, except that the web rearranges
|
||||
/// by dragging the tab bar and the rows themselves — a gesture the tab bar owns
|
||||
/// on a touch screen — so both arrangements are made here instead, with a handle.
|
||||
///
|
||||
/// Edited as a draft and saved in one write rather than on every checkbox:
|
||||
/// switching several off one at a time would make the page rearrange under the
|
||||
/// finger between taps. Pops the updated [Car] when it saved.
|
||||
class CarViewSheet extends StatefulWidget {
|
||||
final Car car;
|
||||
|
||||
/// Whether this car could show a connected-service tab at all. Offering to
|
||||
/// hide a tab nobody can see would just be confusing.
|
||||
final bool showProvider;
|
||||
|
||||
/// The provider's display name ("MyToyota"), used for that tab's label.
|
||||
final String providerLabel;
|
||||
|
||||
const CarViewSheet({
|
||||
super.key,
|
||||
required this.car,
|
||||
required this.showProvider,
|
||||
this.providerLabel = "",
|
||||
});
|
||||
|
||||
@override
|
||||
State<CarViewSheet> createState() => _CarViewSheetState();
|
||||
}
|
||||
|
||||
class _CarViewSheetState extends State<CarViewSheet> {
|
||||
late List<String> _tabOrder;
|
||||
late List<String> _fieldOrder;
|
||||
late Set<String> _visibleTabs;
|
||||
late Set<String> _visibleFields;
|
||||
bool _saving = false;
|
||||
String? _error;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
final car = widget.car;
|
||||
_tabOrder = arrangeKeys(kCarTabKeys, car.tabOrder);
|
||||
_fieldOrder = arrangeKeys(kCarInfoFieldKeys, car.fieldOrder);
|
||||
_visibleTabs = kHideableCarTabKeys.where((k) => !car.hiddenTabs.contains(k)).toSet();
|
||||
_visibleFields = kCarInfoFieldKeys.where((k) => !car.hiddenFields.contains(k)).toSet();
|
||||
}
|
||||
|
||||
/// Whether [key] is one of the rows on offer below: Information never is
|
||||
/// (it cannot be switched off), and the connected service only when this car
|
||||
/// could show one.
|
||||
bool _isRow(String key) =>
|
||||
key != "info" && (key != "provider" || widget.showProvider);
|
||||
|
||||
/// The tab rows on offer, in the car's arrangement.
|
||||
List<String> get _tabRows => _tabOrder.where(_isRow).toList();
|
||||
|
||||
String _tabLabel(String key) => key == "provider" && widget.providerLabel.isNotEmpty
|
||||
? widget.providerLabel
|
||||
: t("car.tabs.$key");
|
||||
|
||||
/// Applies a drag over the rows to the full arrangement, which holds keys the
|
||||
/// rows do not offer. The movable slots are refilled from the new row
|
||||
/// sequence and everything else keeps the position it already had, so
|
||||
/// rearranging the rows can never move Information — or a connected-service
|
||||
/// tab this car cannot show — out from under the user.
|
||||
void _moveTab(int oldIndex, int newIndex) {
|
||||
final rows = _tabRows;
|
||||
rows.insert(newIndex, rows.removeAt(oldIndex));
|
||||
setState(() {
|
||||
var next = 0;
|
||||
_tabOrder = [
|
||||
for (final key in _tabOrder) _isRow(key) ? rows[next++] : key,
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
void _moveField(int oldIndex, int newIndex) {
|
||||
setState(() => _fieldOrder.insert(newIndex, _fieldOrder.removeAt(oldIndex)));
|
||||
}
|
||||
|
||||
Future<void> _save() async {
|
||||
setState(() {
|
||||
_saving = true;
|
||||
_error = null;
|
||||
});
|
||||
try {
|
||||
final car = await apiClient.updateCarView(
|
||||
widget.car.id,
|
||||
hiddenTabs: kHideableCarTabKeys.where((k) => !_visibleTabs.contains(k)).toList(),
|
||||
hiddenFields: kCarInfoFieldKeys.where((k) => !_visibleFields.contains(k)).toList(),
|
||||
tabOrder: _tabOrder,
|
||||
fieldOrder: _fieldOrder,
|
||||
);
|
||||
if (mounted) Navigator.pop(context, car);
|
||||
} catch (e) {
|
||||
if (mounted) setState(() => _error = e.toString());
|
||||
} finally {
|
||||
if (mounted) setState(() => _saving = false);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final inset = MediaQuery.of(context).viewInsets.bottom;
|
||||
return Padding(
|
||||
padding: EdgeInsets.only(bottom: inset),
|
||||
child: DraggableScrollableSheet(
|
||||
expand: false,
|
||||
initialChildSize: 0.85,
|
||||
maxChildSize: 0.95,
|
||||
builder: (context, scrollController) => Column(
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(t("car.viewPicker.title"),
|
||||
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w700)),
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.close),
|
||||
onPressed: () => Navigator.pop(context),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: ListView(
|
||||
controller: scrollController,
|
||||
padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
|
||||
children: [
|
||||
Text(t("car.viewPicker.subtitle"),
|
||||
style: TextStyle(fontSize: 12, color: DriverVault.muted(context))),
|
||||
const SizedBox(height: 16),
|
||||
_heading(context, t("car.viewPicker.tabsHeading")),
|
||||
ReorderableListView(
|
||||
shrinkWrap: true,
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
buildDefaultDragHandles: false,
|
||||
onReorderItem: _moveTab,
|
||||
children: [
|
||||
for (var i = 0; i < _tabRows.length; i++)
|
||||
_row(
|
||||
context,
|
||||
index: i,
|
||||
key: _tabRows[i],
|
||||
label: _tabLabel(_tabRows[i]),
|
||||
on: _visibleTabs.contains(_tabRows[i]),
|
||||
onChanged: (v) => setState(() => v
|
||||
? _visibleTabs.add(_tabRows[i])
|
||||
: _visibleTabs.remove(_tabRows[i])),
|
||||
),
|
||||
],
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 6),
|
||||
child: Text(
|
||||
"${t("car.viewPicker.alwaysOn", params: {"tab": t("car.tabs.info")})}"
|
||||
" ${t("car.viewPicker.reorderHint")}",
|
||||
style: TextStyle(fontSize: 11, color: DriverVault.muted(context)),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
_heading(context, t("car.viewPicker.fieldsHeading")),
|
||||
ReorderableListView(
|
||||
shrinkWrap: true,
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
buildDefaultDragHandles: false,
|
||||
onReorderItem: _moveField,
|
||||
children: [
|
||||
for (var i = 0; i < _fieldOrder.length; i++)
|
||||
_row(
|
||||
context,
|
||||
index: i,
|
||||
key: _fieldOrder[i],
|
||||
label: t("car.info.${_fieldOrder[i]}"),
|
||||
on: _visibleFields.contains(_fieldOrder[i]),
|
||||
onChanged: (v) => setState(() => v
|
||||
? _visibleFields.add(_fieldOrder[i])
|
||||
: _visibleFields.remove(_fieldOrder[i])),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (_error != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 12),
|
||||
child: Text(_error!, style: const TextStyle(color: DriverVault.danger)),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
SafeArea(
|
||||
top: false,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 0, 16, 12),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.end,
|
||||
children: [
|
||||
TextButton(
|
||||
onPressed: _saving ? null : () => Navigator.pop(context),
|
||||
child: Text(t("common.cancel")),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
FilledButton(
|
||||
onPressed: _saving ? null : _save,
|
||||
child: Text(_saving ? t("common.saving") : t("common.save")),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _heading(BuildContext context, String text) => Padding(
|
||||
padding: const EdgeInsets.only(bottom: 4),
|
||||
child: Text(text.toUpperCase(),
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.w700,
|
||||
letterSpacing: 0.6,
|
||||
color: DriverVault.muted(context))),
|
||||
);
|
||||
|
||||
/// One switchable, draggable row. The handle is explicit rather than
|
||||
/// long-press-anywhere: the row's own tap target is the checkbox, and a
|
||||
/// long-press drag would fight it.
|
||||
Widget _row(
|
||||
BuildContext context, {
|
||||
required int index,
|
||||
required String key,
|
||||
required String label,
|
||||
required bool on,
|
||||
required ValueChanged<bool> onChanged,
|
||||
}) =>
|
||||
Padding(
|
||||
key: ValueKey(key),
|
||||
padding: const EdgeInsets.symmetric(vertical: 2),
|
||||
child: Row(
|
||||
children: [
|
||||
Checkbox(value: on, onChanged: (v) => onChanged(v ?? false)),
|
||||
Expanded(child: Text(label, style: const TextStyle(fontSize: 14))),
|
||||
ReorderableDragStartListener(
|
||||
index: index,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(8),
|
||||
child: Icon(Icons.drag_handle, color: DriverVault.muted(context)),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,630 @@
|
||||
import "package:flutter/material.dart";
|
||||
|
||||
import "../format.dart";
|
||||
import "../i18n.dart";
|
||||
import "../main.dart";
|
||||
import "../models.dart";
|
||||
import "../theme.dart";
|
||||
|
||||
/// The connected-service tab on a car: everything the manufacturer's own app
|
||||
/// knows about it, fetched live. Mirrors the web ProviderPanel.
|
||||
///
|
||||
/// Two things shape what is below. The data is read under *this* user's account
|
||||
/// — so a car shared from someone else shows nothing here unless the vehicle is
|
||||
/// on this user's account too, and the tab says so rather than failing. And the
|
||||
/// sections are whatever the plugin exposes, rendered from the server's
|
||||
/// flattened key/value pairs: nothing here knows a single upstream field name,
|
||||
/// so a provider adding a field surfaces it without a change to this file.
|
||||
///
|
||||
/// Unlike the web, the headline readings cannot be rearranged here — a drag on a
|
||||
/// touch screen is the tab bar's gesture. The stored arrangement is still
|
||||
/// honoured, so an order set on the web carries over.
|
||||
class ProviderTab extends StatefulWidget {
|
||||
final Car car;
|
||||
|
||||
/// Called with the updated car after a link, unlink or odometer sync, so the
|
||||
/// page holds one copy of it and the tab bar can pick up a new provider link.
|
||||
final void Function(Car) onCarUpdated;
|
||||
|
||||
const ProviderTab({super.key, required this.car, required this.onCarUpdated});
|
||||
|
||||
@override
|
||||
State<ProviderTab> createState() => _ProviderTabState();
|
||||
}
|
||||
|
||||
class _ProviderTabState extends State<ProviderTab> {
|
||||
ProviderSnapshot? _snap;
|
||||
bool _loading = false;
|
||||
bool _syncing = false;
|
||||
String? _error;
|
||||
|
||||
// The connect flow, for a car with no link yet (added by hand, or from before
|
||||
// the feature existed).
|
||||
List<VehicleProvider> _providers = const [];
|
||||
String _linkProvider = "";
|
||||
List<ProviderVehicle> _linkVehicles = const [];
|
||||
String _linkVehicleId = "";
|
||||
bool _linkLoading = false;
|
||||
bool _linking = false;
|
||||
|
||||
bool get _linked => widget.car.provider.isNotEmpty;
|
||||
|
||||
List<VehicleProvider> get _connectable =>
|
||||
_providers.where((p) => p.connected).toList();
|
||||
|
||||
String get _label {
|
||||
final fromSnap = _snap?.label ?? "";
|
||||
if (fromSnap.isNotEmpty) return fromSnap;
|
||||
for (final p in _providers) {
|
||||
if (p.id == widget.car.provider) return p.label;
|
||||
}
|
||||
return widget.car.provider.isEmpty ? t("car.tabs.connected") : widget.car.provider;
|
||||
}
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
if (_linked) {
|
||||
_load();
|
||||
} else {
|
||||
_loadProviders();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(ProviderTab old) {
|
||||
super.didUpdateWidget(old);
|
||||
// Linking from the connect card replaces the car, which is when the live
|
||||
// snapshot becomes fetchable at all.
|
||||
if (old.car.provider != widget.car.provider) {
|
||||
if (_linked) {
|
||||
_load();
|
||||
} else {
|
||||
setState(() => _snap = null);
|
||||
_loadProviders();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _load() async {
|
||||
setState(() {
|
||||
_loading = true;
|
||||
_error = null;
|
||||
});
|
||||
try {
|
||||
final snap = await apiClient.getCarProvider(widget.car.id);
|
||||
if (mounted) setState(() => _snap = snap);
|
||||
} catch (e) {
|
||||
if (mounted) setState(() => _error = e.toString());
|
||||
} finally {
|
||||
if (mounted) setState(() => _loading = false);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _loadProviders() async {
|
||||
try {
|
||||
final list = await apiClient.listVehicleProviders();
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_providers = list;
|
||||
_linkProvider = _connectable.isEmpty ? "" : _connectable.first.id;
|
||||
});
|
||||
await _loadLinkVehicles();
|
||||
} catch (e) {
|
||||
if (mounted) setState(() => _error = e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _loadLinkVehicles() async {
|
||||
setState(() {
|
||||
_linkVehicles = const [];
|
||||
_linkVehicleId = "";
|
||||
});
|
||||
if (_linkProvider.isEmpty) return;
|
||||
setState(() => _linkLoading = true);
|
||||
try {
|
||||
final list = await apiClient.listProviderVehicles(_linkProvider);
|
||||
if (!mounted) return;
|
||||
// Prefer the vehicle whose VIN matches the car — usually the only guess
|
||||
// needed.
|
||||
final vin = widget.car.vin.trim().toUpperCase();
|
||||
String pick = list.isEmpty ? "" : list.first.id;
|
||||
if (vin.isNotEmpty) {
|
||||
for (final v in list) {
|
||||
if (v.vin.toUpperCase() == vin) {
|
||||
pick = v.id;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
setState(() {
|
||||
_linkVehicles = list;
|
||||
_linkVehicleId = pick;
|
||||
});
|
||||
} catch (e) {
|
||||
if (mounted) setState(() => _error = e.toString());
|
||||
} finally {
|
||||
if (mounted) setState(() => _linkLoading = false);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _connect() async {
|
||||
if (_linkVehicleId.isEmpty) return;
|
||||
setState(() {
|
||||
_linking = true;
|
||||
_error = null;
|
||||
});
|
||||
try {
|
||||
final car = await apiClient.linkCarProvider(widget.car.id,
|
||||
provider: _linkProvider, vehicleId: _linkVehicleId);
|
||||
widget.onCarUpdated(car);
|
||||
} catch (e) {
|
||||
if (mounted) setState(() => _error = e.toString());
|
||||
} finally {
|
||||
if (mounted) setState(() => _linking = false);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _disconnect() async {
|
||||
final ok = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
content: Text(t("car.provider.unlinkConfirm", params: {"label": _label})),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(ctx, false), child: Text(t("common.cancel"))),
|
||||
FilledButton(
|
||||
style: FilledButton.styleFrom(backgroundColor: DriverVault.danger),
|
||||
onPressed: () => Navigator.pop(ctx, true),
|
||||
child: Text(t("car.provider.unlink")),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (ok != true) return;
|
||||
setState(() => _error = null);
|
||||
try {
|
||||
final car = await apiClient.linkCarProvider(widget.car.id);
|
||||
if (mounted) setState(() => _snap = null);
|
||||
widget.onCarUpdated(car);
|
||||
} catch (e) {
|
||||
if (mounted) setState(() => _error = e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
/// Only the odometer is written back: it is the one provider reading the rest
|
||||
/// of the app computes from (service intervals, km-triggered reminders), and
|
||||
/// the one the user would otherwise retype after every drive.
|
||||
Future<void> _applyOdometer() async {
|
||||
setState(() {
|
||||
_syncing = true;
|
||||
_error = null;
|
||||
});
|
||||
try {
|
||||
final car = await apiClient.syncCarProvider(widget.car.id, include: {
|
||||
"identity": false,
|
||||
"fuelType": false,
|
||||
"dates": false,
|
||||
"odometer": true,
|
||||
});
|
||||
widget.onCarUpdated(car);
|
||||
await _load();
|
||||
} catch (e) {
|
||||
if (mounted) setState(() => _error = e.toString());
|
||||
} finally {
|
||||
if (mounted) setState(() => _syncing = false);
|
||||
}
|
||||
}
|
||||
|
||||
/// The readings in the car's stored arrangement. A reading the arrangement
|
||||
/// does not name — one the provider only started reporting later — follows the
|
||||
/// arranged ones rather than appearing in the middle.
|
||||
List<ProviderMetric> get _metrics {
|
||||
final reported = _snap?.metrics ?? const <ProviderMetric>[];
|
||||
final order = widget.car.metricOrder;
|
||||
if (order.isEmpty) return reported;
|
||||
final rank = {for (var i = 0; i < order.length; i++) order[i]: i};
|
||||
final list = [...reported];
|
||||
// A stable sort, so two unarranged readings keep the order they came in.
|
||||
list.sort((a, b) => (rank[a.key] ?? order.length).compareTo(rank[b.key] ?? order.length));
|
||||
return list;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ListView(
|
||||
padding: const EdgeInsets.fromLTRB(12, 12, 12, 80),
|
||||
children: [
|
||||
if (_error != null) ...[
|
||||
_ErrorBanner(_error!),
|
||||
const SizedBox(height: 12),
|
||||
],
|
||||
if (_linked) ..._linkedBody(context) else ..._connectBody(context),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
// --- linked: the live snapshot -------------------------------------------
|
||||
|
||||
List<Widget> _linkedBody(BuildContext context) {
|
||||
final snap = _snap;
|
||||
return [
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(_label,
|
||||
style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w700)),
|
||||
Text(t("car.provider.subtitle", params: {"label": _label}),
|
||||
style: TextStyle(fontSize: 12, color: DriverVault.muted(context))),
|
||||
],
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
tooltip: _loading ? t("car.provider.refreshing") : t("car.provider.refresh"),
|
||||
icon: const Icon(Icons.refresh),
|
||||
onPressed: _loading ? null : _load,
|
||||
),
|
||||
if (widget.car.canWrite)
|
||||
IconButton(
|
||||
tooltip: t("car.provider.unlink"),
|
||||
icon: const Icon(Icons.link_off, color: DriverVault.danger),
|
||||
onPressed: _disconnect,
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
if (snap == null)
|
||||
const Center(child: Padding(padding: EdgeInsets.all(24), child: CircularProgressIndicator()))
|
||||
else if (snap.unavailable)
|
||||
_Card(
|
||||
child: Column(
|
||||
children: [
|
||||
Text(snap.detail,
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(color: DriverVault.warning)),
|
||||
const SizedBox(height: 6),
|
||||
Text(t("car.provider.own"),
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(fontSize: 11, color: DriverVault.muted(context))),
|
||||
],
|
||||
),
|
||||
)
|
||||
else ...[
|
||||
if (_metrics.isNotEmpty) _readings(context),
|
||||
if (snap.suggestedCurrentKm > 0 && widget.car.canWrite) _odometerOffer(context, snap),
|
||||
if (snap.vehicle != null) _vehicleCard(context, snap.vehicle!),
|
||||
...snap.sections.map((s) => _sectionCard(context, s)),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
"${t("car.provider.updated", params: {"time": formatDateTime(snap.fetchedAt)})}"
|
||||
" · ${t("car.provider.own")}",
|
||||
style: TextStyle(fontSize: 11, color: DriverVault.muted(context)),
|
||||
),
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
Widget _readings(BuildContext context) => _Card(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(t("car.provider.readings"),
|
||||
style: const TextStyle(fontWeight: FontWeight.w600)),
|
||||
const SizedBox(height: 8),
|
||||
Wrap(
|
||||
spacing: 16,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
for (final m in _metrics)
|
||||
SizedBox(
|
||||
width: 150,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(t("car.provider.metrics.${m.key}"),
|
||||
style: TextStyle(fontSize: 11, color: DriverVault.muted(context))),
|
||||
Text(m.unit.isEmpty ? m.value : "${m.value} ${m.unit}",
|
||||
style: DriverVault.mono(context,
|
||||
size: 13,
|
||||
weight: FontWeight.w600,
|
||||
color: Theme.of(context).colorScheme.onSurface)),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
Widget _odometerOffer(BuildContext context, ProviderSnapshot snap) => _Card(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(t("car.provider.odometerSuggest", params: {
|
||||
"label": _label,
|
||||
"km": formatKm(snap.suggestedCurrentKm),
|
||||
})),
|
||||
const SizedBox(height: 8),
|
||||
Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: FilledButton(
|
||||
onPressed: _syncing ? null : _applyOdometer,
|
||||
child: Text(_syncing
|
||||
? t("car.provider.updatingOdometer")
|
||||
: t("car.provider.updateOdometer")),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
Widget _vehicleCard(BuildContext context, ProviderVehicle v) => _Card(
|
||||
padding: EdgeInsets.zero,
|
||||
child: ExpansionTile(
|
||||
initiallyExpanded: true,
|
||||
shape: const Border(),
|
||||
collapsedShape: const Border(),
|
||||
title: Text(t("car.provider.vehicle"),
|
||||
style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w600)),
|
||||
childrenPadding: const EdgeInsets.fromLTRB(14, 0, 14, 12),
|
||||
children: [
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(v.name, style: const TextStyle(fontWeight: FontWeight.w700)),
|
||||
if (v.subtitle.isNotEmpty)
|
||||
Text(v.subtitle,
|
||||
style: TextStyle(fontSize: 12, color: DriverVault.muted(context))),
|
||||
if (v.vin.isNotEmpty)
|
||||
Text(v.vin,
|
||||
style: DriverVault.mono(context,
|
||||
size: 11, color: DriverVault.muted(context))),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (v.imageUrl.isNotEmpty)
|
||||
// The provider's own CDN, so it can fail on a phone with no
|
||||
// route to it — a broken image must not take the tab with it.
|
||||
Image.network(v.imageUrl,
|
||||
height: 64,
|
||||
fit: BoxFit.contain,
|
||||
errorBuilder: (_, __, ___) => const SizedBox.shrink()),
|
||||
],
|
||||
),
|
||||
if (v.fields.isNotEmpty) _fieldsExpander(context, t("car.provider.allFields"), v.fields),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
Widget _sectionCard(BuildContext context, ProviderSection sec) => _Card(
|
||||
padding: EdgeInsets.zero,
|
||||
child: ExpansionTile(
|
||||
shape: const Border(),
|
||||
collapsedShape: const Border(),
|
||||
title: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(t("car.provider.sections.${sec.id}"),
|
||||
style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w600)),
|
||||
),
|
||||
// A failed section says so in the collapsed header, but only as a
|
||||
// badge: the provider's own message can run to hundreds of
|
||||
// characters, which belongs in the body with the rest of it.
|
||||
if (sec.status == "error")
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
|
||||
decoration: BoxDecoration(
|
||||
color: DriverVault.isDark(context)
|
||||
? DriverVault.warningSoftDark
|
||||
: DriverVault.warningSoft,
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: Text(t("car.provider.sectionFailed"),
|
||||
style: const TextStyle(fontSize: 11, color: DriverVault.warning)),
|
||||
),
|
||||
],
|
||||
),
|
||||
childrenPadding: const EdgeInsets.fromLTRB(14, 0, 14, 12),
|
||||
children: [
|
||||
if (sec.status == "error")
|
||||
Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: Text(sec.error,
|
||||
style: const TextStyle(fontSize: 12, color: DriverVault.warning)),
|
||||
)
|
||||
else if (sec.status == "empty")
|
||||
Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: Text(t("car.provider.sectionEmpty"),
|
||||
style: TextStyle(fontSize: 12, color: DriverVault.muted(context))),
|
||||
)
|
||||
else ...[
|
||||
_fieldList(context, sec.fields),
|
||||
if (sec.truncated)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 6),
|
||||
child: Text(
|
||||
t("car.provider.truncated", params: {"n": sec.fields.length}),
|
||||
style: const TextStyle(fontSize: 11, color: DriverVault.warning),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
Widget _fieldsExpander(BuildContext context, String label, List<ProviderField> fields) =>
|
||||
Theme(
|
||||
// The nested expander would otherwise draw its own divider lines inside
|
||||
// the card it is already sitting in.
|
||||
data: Theme.of(context).copyWith(dividerColor: Colors.transparent),
|
||||
child: ExpansionTile(
|
||||
tilePadding: EdgeInsets.zero,
|
||||
title: Text(label,
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: DriverVault.brandOnTint(context))),
|
||||
childrenPadding: EdgeInsets.zero,
|
||||
children: [_fieldList(context, fields)],
|
||||
),
|
||||
);
|
||||
|
||||
Widget _fieldList(BuildContext context, List<ProviderField> fields) => Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
for (final f in fields)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 3),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
SizedBox(
|
||||
width: 140,
|
||||
child: Text(f.key,
|
||||
style: DriverVault.mono(context,
|
||||
size: 11, color: DriverVault.muted(context))),
|
||||
),
|
||||
Expanded(child: Text(f.value, style: const TextStyle(fontSize: 12))),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
// --- not linked: offer to connect this car to a vehicle -------------------
|
||||
|
||||
List<Widget> _connectBody(BuildContext context) {
|
||||
if (_connectable.isEmpty) {
|
||||
return [
|
||||
_Card(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(t("car.provider.connectTitle"),
|
||||
style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w700)),
|
||||
const SizedBox(height: 6),
|
||||
Text(t("car.provider.noProviders"),
|
||||
style: TextStyle(fontSize: 12, color: DriverVault.muted(context))),
|
||||
],
|
||||
),
|
||||
),
|
||||
];
|
||||
}
|
||||
return [
|
||||
_Card(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(t("car.provider.connectTitle"),
|
||||
style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w700)),
|
||||
const SizedBox(height: 4),
|
||||
Text(t("car.provider.connectHint"),
|
||||
style: TextStyle(fontSize: 12, color: DriverVault.muted(context))),
|
||||
const SizedBox(height: 12),
|
||||
if (_connectable.length > 1) ...[
|
||||
DropdownButtonFormField<String>(
|
||||
initialValue: _linkProvider.isEmpty ? null : _linkProvider,
|
||||
decoration: InputDecoration(
|
||||
labelText: t("forms.import.service"), border: const OutlineInputBorder()),
|
||||
items: [
|
||||
for (final p in _connectable)
|
||||
DropdownMenuItem(value: p.id, child: Text(p.label)),
|
||||
],
|
||||
onChanged: (v) {
|
||||
if (v == null) return;
|
||||
setState(() => _linkProvider = v);
|
||||
_loadLinkVehicles();
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
],
|
||||
if (_linkLoading)
|
||||
Text(t("forms.import.loadingVehicles"),
|
||||
style: TextStyle(fontSize: 12, color: DriverVault.muted(context)))
|
||||
else if (_linkVehicles.isEmpty)
|
||||
Text(t("forms.import.noVehicles"),
|
||||
style: TextStyle(fontSize: 12, color: DriverVault.muted(context)))
|
||||
else
|
||||
DropdownButtonFormField<String>(
|
||||
key: ValueKey("$_linkProvider/$_linkVehicleId"),
|
||||
initialValue: _linkVehicleId.isEmpty ? null : _linkVehicleId,
|
||||
isExpanded: true,
|
||||
decoration: InputDecoration(
|
||||
labelText: t("forms.import.selectVehicle"),
|
||||
border: const OutlineInputBorder()),
|
||||
items: [
|
||||
for (final v in _linkVehicles)
|
||||
DropdownMenuItem(
|
||||
value: v.id,
|
||||
child: Text(v.vin.isEmpty ? v.name : "${v.name} · ${v.vin}",
|
||||
overflow: TextOverflow.ellipsis),
|
||||
),
|
||||
],
|
||||
onChanged: (v) => setState(() => _linkVehicleId = v ?? ""),
|
||||
),
|
||||
if (widget.car.canWrite) ...[
|
||||
const SizedBox(height: 12),
|
||||
Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: FilledButton(
|
||||
onPressed: _linkVehicleId.isEmpty || _linking ? null : _connect,
|
||||
child: Text(_linking
|
||||
? t("car.provider.connecting")
|
||||
: t("car.provider.connectSubmit")),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/// The card chrome the rest of the car screen uses, repeated here so this tab
|
||||
/// sits flush with the others.
|
||||
class _Card extends StatelessWidget {
|
||||
final Widget child;
|
||||
final EdgeInsetsGeometry padding;
|
||||
const _Card({required this.child, this.padding = const EdgeInsets.all(14)});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Card(
|
||||
elevation: 0,
|
||||
margin: const EdgeInsets.only(bottom: 8),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
side: BorderSide(
|
||||
color: DriverVault.isDark(context) ? DriverVault.darkBorder : DriverVault.ink100),
|
||||
),
|
||||
child: Padding(padding: padding, child: child),
|
||||
);
|
||||
}
|
||||
|
||||
class _ErrorBanner extends StatelessWidget {
|
||||
final String message;
|
||||
const _ErrorBanner(this.message);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: DriverVault.isDark(context)
|
||||
? DriverVault.dangerSoftDark
|
||||
: DriverVault.dangerSoft,
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
child: Text(message,
|
||||
style: const TextStyle(color: DriverVault.danger, fontWeight: FontWeight.w500)),
|
||||
);
|
||||
}
|
||||
@@ -2,15 +2,16 @@ import "package:flutter/material.dart";
|
||||
|
||||
import "../api.dart";
|
||||
import "../format.dart";
|
||||
import "../i18n.dart";
|
||||
import "../main.dart";
|
||||
import "../models.dart";
|
||||
import "../theme.dart";
|
||||
import "../widgets/attachment_field.dart";
|
||||
|
||||
// The bottom-sheet forms for the record types behind the car's tabs: technical
|
||||
// checks, refills, workshop visits, documents and reminders. Each mirrors the
|
||||
// web app's matching modal, and pops `true` when it saved so the car detail
|
||||
// screen can reload.
|
||||
// checks, refills, charges, workshop visits, documents and reminders. Each
|
||||
// mirrors the web app's matching modal, and pops `true` when it saved so the car
|
||||
// detail screen can reload.
|
||||
|
||||
/// Serializes a picked day as UTC midnight, matching what the web app sends for
|
||||
/// the same field. These are date-only concepts, so the day the user tapped is
|
||||
@@ -502,6 +503,189 @@ class _FuelSheetState extends State<FuelSheet> {
|
||||
}
|
||||
}
|
||||
|
||||
// --- charging ---
|
||||
|
||||
/// Mirrors the web ChargingFormModal — one charge of an EV. The electric twin of
|
||||
/// [FuelSheet], and derived the same way: consumption is measured between full
|
||||
/// charges, so a top-up rolls into the next full one.
|
||||
class ChargingSheet extends StatefulWidget {
|
||||
final String carId;
|
||||
final ChargingSession? entry; // null => create
|
||||
const ChargingSheet({super.key, required this.carId, this.entry});
|
||||
|
||||
@override
|
||||
State<ChargingSheet> createState() => _ChargingSheetState();
|
||||
}
|
||||
|
||||
class _ChargingSheetState extends State<ChargingSheet> {
|
||||
late DateTime _date;
|
||||
late final TextEditingController _km, _kwh, _cost, _location, _notes;
|
||||
late bool _fullCharge, _missedSession;
|
||||
final _pending = PendingAttachment();
|
||||
bool _saving = false;
|
||||
String? _error;
|
||||
|
||||
bool get _isEdit => widget.entry != null;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
final e = widget.entry;
|
||||
_date = e?.date ?? DateTime.now();
|
||||
_km = TextEditingController(text: e == null ? "" : "${e.km}");
|
||||
_kwh = TextEditingController(text: (e != null && e.kwh > 0) ? "${e.kwh}" : "");
|
||||
_cost = TextEditingController(text: (e != null && e.cost > 0) ? "${e.cost}" : "");
|
||||
// A full charge is the common case and the one that makes the entry count
|
||||
// towards efficiency, so it is the default.
|
||||
_fullCharge = e?.fullCharge ?? true;
|
||||
_missedSession = e?.missedSession ?? false;
|
||||
_location = TextEditingController(text: e?.location ?? "");
|
||||
_notes = TextEditingController(text: e?.notes ?? "");
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
for (final c in [_km, _kwh, _cost, _location, _notes]) {
|
||||
c.dispose();
|
||||
}
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
String? get _pricePerKwh {
|
||||
final k = _numOrNull(_kwh);
|
||||
final c = _numOrNull(_cost);
|
||||
if (k == null || c == null || k == 0 || c == 0) return null;
|
||||
return (c / k).toStringAsFixed(3);
|
||||
}
|
||||
|
||||
Future<void> _save() async {
|
||||
final km = _int(_km);
|
||||
final kwh = _num(_kwh);
|
||||
if (_km.text.trim().isEmpty || km < 0) {
|
||||
setState(() => _error = t("forms.charging.odometerRequired"));
|
||||
return;
|
||||
}
|
||||
if (kwh <= 0) {
|
||||
setState(() => _error = t("forms.charging.kwhRequired"));
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
_saving = true;
|
||||
_error = null;
|
||||
});
|
||||
final payload = {
|
||||
"car": widget.carId,
|
||||
"date": _isoDate(_date),
|
||||
"km": km,
|
||||
"kwh": kwh,
|
||||
"cost": _num(_cost),
|
||||
"fullCharge": _fullCharge,
|
||||
"missedSession": _missedSession,
|
||||
"location": _location.text.trim(),
|
||||
"notes": _notes.text.trim(),
|
||||
};
|
||||
try {
|
||||
final saved = _isEdit
|
||||
? await apiClient.updateChargingSession(widget.entry!.id, payload)
|
||||
: await apiClient.createChargingSession(payload);
|
||||
if (!_pending.isEmpty) {
|
||||
try {
|
||||
await applyAttachment("/charging-sessions", saved.id, _pending);
|
||||
} catch (e) {
|
||||
throw ApiException(0, "Charge saved, but the receipt did not upload: $e");
|
||||
}
|
||||
}
|
||||
if (mounted) Navigator.pop(context, true);
|
||||
} catch (e) {
|
||||
setState(() => _error = e.toString());
|
||||
} finally {
|
||||
if (mounted) setState(() => _saving = false);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final ppk = _pricePerKwh;
|
||||
return _SheetScaffold(
|
||||
title: _isEdit ? t("forms.charging.editTitle") : t("forms.charging.addTitle"),
|
||||
error: _error,
|
||||
saving: _saving,
|
||||
saveLabel: t("forms.charging.submit"),
|
||||
onSave: _save,
|
||||
children: [
|
||||
Row(children: [
|
||||
Expanded(
|
||||
child: _dateField(context, "${t("forms.charging.date")} *", _date,
|
||||
(v) => setState(() => _date = v ?? _date),
|
||||
clearable: false),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: _field(_km, "${t("forms.charging.odometer")} *",
|
||||
keyboard: TextInputType.number, hint: "16138"),
|
||||
),
|
||||
]),
|
||||
Row(children: [
|
||||
Expanded(
|
||||
child: _field(_kwh, "${t("forms.charging.kwh")} *",
|
||||
keyboard: const TextInputType.numberWithOptions(decimal: true), hint: "42.5"),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: _field(_cost, t("forms.charging.cost"),
|
||||
keyboard: const TextInputType.numberWithOptions(decimal: true), hint: "85.00"),
|
||||
),
|
||||
]),
|
||||
if (ppk != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8),
|
||||
child: Text(t("forms.charging.pricePerKwh", params: {"price": ppk}),
|
||||
style: Theme.of(context).textTheme.bodySmall),
|
||||
),
|
||||
_group(
|
||||
context,
|
||||
t("forms.charging.battery"),
|
||||
[
|
||||
CheckboxListTile(
|
||||
value: _fullCharge,
|
||||
onChanged: (v) => setState(() => _fullCharge = v ?? false),
|
||||
title: Text(t("forms.charging.fullCharge")),
|
||||
contentPadding: EdgeInsets.zero,
|
||||
controlAffinity: ListTileControlAffinity.leading,
|
||||
dense: true,
|
||||
),
|
||||
CheckboxListTile(
|
||||
value: _missedSession,
|
||||
onChanged: (v) => setState(() => _missedSession = v ?? false),
|
||||
title: Text(t("forms.charging.missedSession")),
|
||||
contentPadding: EdgeInsets.zero,
|
||||
controlAffinity: ListTileControlAffinity.leading,
|
||||
dense: true,
|
||||
),
|
||||
],
|
||||
hint: t("forms.charging.batteryHint"),
|
||||
),
|
||||
Row(children: [
|
||||
Expanded(
|
||||
child: _field(_location, t("forms.charging.location"),
|
||||
hint: t("forms.charging.locationPlaceholder")),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(child: _field(_notes, t("forms.charging.notes"))),
|
||||
]),
|
||||
AttachmentField(
|
||||
path: "/charging-sessions",
|
||||
record: widget.entry,
|
||||
recordId: widget.entry?.id,
|
||||
pending: _pending,
|
||||
onChanged: () => setState(() {}),
|
||||
legend: t("forms.charging.attachmentLegend"),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// --- maintenance ---
|
||||
|
||||
/// Mirrors the web MaintenanceFormModal — a workshop visit or repair, i.e. work
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import "dart:convert";
|
||||
import "dart:io";
|
||||
import "dart:typed_data";
|
||||
|
||||
import "package:file_picker/file_picker.dart";
|
||||
import "package:flutter/material.dart";
|
||||
import "package:image_picker/image_picker.dart";
|
||||
import "package:open_filex/open_filex.dart";
|
||||
import "package:path_provider/path_provider.dart";
|
||||
|
||||
import "../biometric.dart";
|
||||
import "../i18n.dart";
|
||||
@@ -10,9 +15,9 @@ import "../models.dart";
|
||||
import "../format.dart";
|
||||
import "../theme.dart";
|
||||
|
||||
/// Full settings panel, mirroring the web Settings.vue (minus data export/import):
|
||||
/// account (name/email/password), appearance (theme/locale/date/font), profile
|
||||
/// (avatar/bio), privacy (sessions), and account deletion.
|
||||
/// Full settings panel, mirroring the web Settings.vue: account
|
||||
/// (name/email/password), appearance (theme/locale/date/font), profile
|
||||
/// (avatar/bio), privacy (sessions), data export/import, and account deletion.
|
||||
class SettingsScreen extends StatefulWidget {
|
||||
const SettingsScreen({super.key});
|
||||
@override
|
||||
@@ -136,6 +141,8 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
const SizedBox(height: 12),
|
||||
const _PrivacySection(),
|
||||
const SizedBox(height: 12),
|
||||
_DataSection(snack: _snack),
|
||||
const SizedBox(height: 12),
|
||||
_DangerSection(profile: _profile!, onChanged: _load, snack: _snack),
|
||||
const SizedBox(height: 24),
|
||||
],
|
||||
@@ -1138,6 +1145,185 @@ class _PrivacySection extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
// --- Data (export / import) -------------------------------------------------
|
||||
|
||||
/// Export downloads the account as JSON; import adds the cars from a file
|
||||
/// exported earlier. The web hands the browser a download and a file input; a
|
||||
/// phone has neither, so the export is written to the app's own directory and
|
||||
/// offered to whatever the phone opens JSON with, and the import goes through
|
||||
/// the system file picker.
|
||||
///
|
||||
/// The import always creates new records — nothing is merged or overwritten —
|
||||
/// so it asks first, with the number of cars the file actually holds.
|
||||
class _DataSection extends StatefulWidget {
|
||||
final void Function(String) snack;
|
||||
const _DataSection({required this.snack});
|
||||
@override
|
||||
State<_DataSection> createState() => _DataSectionState();
|
||||
}
|
||||
|
||||
class _DataSectionState extends State<_DataSection> {
|
||||
bool _exporting = false;
|
||||
bool _importing = false;
|
||||
String? _error;
|
||||
ImportResult? _result;
|
||||
|
||||
/// The last export written, kept so the card can offer to open it: the file
|
||||
/// lands in the app's documents directory, which the user has no other route
|
||||
/// to.
|
||||
File? _exported;
|
||||
|
||||
Future<void> _export() async {
|
||||
setState(() {
|
||||
_exporting = true;
|
||||
_error = null;
|
||||
_exported = null;
|
||||
});
|
||||
try {
|
||||
final (bytes, filename) = await apiClient.exportData();
|
||||
final dir = await getApplicationDocumentsDirectory();
|
||||
final file = File("${dir.path}/$filename");
|
||||
await file.writeAsBytes(bytes);
|
||||
if (!mounted) return;
|
||||
setState(() => _exported = file);
|
||||
widget.snack(t("settings.advanced.exported", params: {"file": filename}));
|
||||
} catch (e) {
|
||||
if (mounted) setState(() => _error = e.toString());
|
||||
} finally {
|
||||
if (mounted) setState(() => _exporting = false);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _openExport() async {
|
||||
final file = _exported;
|
||||
if (file == null) return;
|
||||
final res = await OpenFilex.open(file.path);
|
||||
if (res.type != ResultType.done && mounted) {
|
||||
widget.snack(t("settings.advanced.openFailed"));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _import() async {
|
||||
setState(() {
|
||||
_error = null;
|
||||
_result = null;
|
||||
});
|
||||
|
||||
final picked = await FilePicker.platform.pickFiles(
|
||||
type: FileType.custom,
|
||||
allowedExtensions: const ["json"],
|
||||
withData: true,
|
||||
);
|
||||
if (picked == null || picked.files.isEmpty) return;
|
||||
final file = picked.files.first;
|
||||
final bytes = file.bytes ?? (file.path != null ? await File(file.path!).readAsBytes() : null);
|
||||
if (bytes == null) {
|
||||
setState(() => _error = t("settings.advanced.notJson"));
|
||||
return;
|
||||
}
|
||||
|
||||
Map<String, dynamic> payload;
|
||||
try {
|
||||
payload = Map<String, dynamic>.from(jsonDecode(utf8.decode(bytes)) as Map);
|
||||
} catch (_) {
|
||||
setState(() => _error = t("settings.advanced.notJson"));
|
||||
return;
|
||||
}
|
||||
final cars = payload["cars"];
|
||||
if (cars is! List || cars.isEmpty) {
|
||||
setState(() => _error = t("settings.advanced.notExport"));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!mounted) return;
|
||||
final ok = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
content: Text(t("settings.advanced.confirmImport", params: {"count": cars.length})),
|
||||
actions: [
|
||||
TextButton(onPressed: () => Navigator.pop(ctx, false), child: Text(t("common.cancel"))),
|
||||
FilledButton(
|
||||
onPressed: () => Navigator.pop(ctx, true),
|
||||
child: Text(t("settings.advanced.importAction")),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (ok != true) return;
|
||||
|
||||
setState(() => _importing = true);
|
||||
try {
|
||||
final res = await apiClient.importData(payload);
|
||||
if (mounted) setState(() => _result = res);
|
||||
} catch (e) {
|
||||
if (mounted) setState(() => _error = e.toString());
|
||||
} finally {
|
||||
if (mounted) setState(() => _importing = false);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final muted = TextStyle(fontSize: 12, color: DriverVault.muted(context));
|
||||
return _Card(
|
||||
title: t("settings.advanced.title"),
|
||||
children: [
|
||||
Text(t("settings.advanced.exportTitle"),
|
||||
style: const TextStyle(fontWeight: FontWeight.w600)),
|
||||
Text(t("settings.advanced.exportBody"), style: muted),
|
||||
const SizedBox(height: 8),
|
||||
Row(
|
||||
children: [
|
||||
OutlinedButton.icon(
|
||||
onPressed: _exporting ? null : _export,
|
||||
icon: const Icon(Icons.download_outlined, size: 18),
|
||||
label: Text(_exporting
|
||||
? t("settings.advanced.preparing")
|
||||
: t("settings.advanced.exportAction")),
|
||||
),
|
||||
if (_exported != null) ...[
|
||||
const SizedBox(width: 8),
|
||||
TextButton(onPressed: _openExport, child: Text(t("settings.advanced.open"))),
|
||||
],
|
||||
],
|
||||
),
|
||||
const Divider(height: 24),
|
||||
Text(t("settings.advanced.importTitle"),
|
||||
style: const TextStyle(fontWeight: FontWeight.w600)),
|
||||
Text(t("settings.advanced.importBody"), style: muted),
|
||||
const SizedBox(height: 8),
|
||||
Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: OutlinedButton.icon(
|
||||
onPressed: _importing ? null : _import,
|
||||
icon: const Icon(Icons.upload_file_outlined, size: 18),
|
||||
label: Text(_importing
|
||||
? t("settings.advanced.importing")
|
||||
: t("settings.advanced.importAction")),
|
||||
),
|
||||
),
|
||||
if (_result != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 8),
|
||||
child: Text(
|
||||
t("settings.advanced.imported", params: {
|
||||
"cars": _result!.cars,
|
||||
"services": _result!.services,
|
||||
"parts": _result!.parts,
|
||||
}),
|
||||
style: const TextStyle(color: DriverVault.success, fontWeight: FontWeight.w600),
|
||||
),
|
||||
),
|
||||
if (_error != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 8),
|
||||
child: Text(_error!, style: const TextStyle(color: DriverVault.danger)),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Danger zone (account deletion) ----------------------------------------
|
||||
|
||||
class _DangerSection extends StatefulWidget {
|
||||
|
||||
Reference in new issue
Block a user