Files
DriverVault/Phone App/README.md
T
tajniak81andClaude Opus 5 12ec10a797 Phone App: more than one server, and a session for each
The web app can be pointed at two DriverVault stacks and switch between them in
a click. The phone had one address and one session: reaching a second garage
meant retyping the API base in Server settings and signing in again, losing the
first server's token on the way — the same act, undone, every time you switched
back.

So lib/servers.dart is the web's servers.js ported rather than reinvented, down
to the storage keys: cc_servers holds the list, cc_active_server the one being
read, cc_session_<id> the token minted by that server and no other. The two apps
describe the same thing the same way, and the upgrade path falls out of it —
cc_token, cc_user and cc_server_url are read once at boot and folded onto the
home entry, so the build carrying this signs nobody out.

Home is the address the build ships with (kDefaultApiBase, still overridable per
device from the login screen) and cannot be removed: it is what a dropped session
falls back to. Any other server is added by address, with /api appended if the
path is left off, because a server a phone can reach is internet-facing already.

The part worth reading twice is which session a rejection ends. ApiClient no
longer holds a base or a token — it pins the active server's id, base and token
at the moment a request goes out, so a 401 arriving after a switch clears the
session of the server that actually refused it rather than whichever one is
active by then. The fallback is the web's: a remote server timing out drops its
own token, the app returns to home while home is still signed in, and only when
nothing is left to fall back to does the login screen come back. Log out still
clears every server at once, since leaving the app means leaving all of them.

Switching rebuilds the shell, keyed on the active id, because record ids belong
to the server that issued them — a garage, a charging page and a settings panel
still holding the other server's rows would each have to be told to forget them
separately. The appearance prefs come across with the profile of whoever owns
the account on the server now active.

Where the picker lives is the one place the phone cannot copy the web. There is
no app rail here, so it became the first button in the Garage header, beside the
theme toggle and log out, which is that same cluster. It names the active server
once there is a choice and goes straight to adding the second when there isn't;
the eyebrow reads GARAGE · Work for the reason the rail names it — two garages
otherwise look identical. The login screen gets its own way in, because a remote
session can expire and land you there with that server still active, and a
picker reachable only from inside the app would leave nowhere to go.

One judgment call inside the sheet: saving a connected server at a new address
saves and stops, rather than falling through to the sign-in it now needs. The
token was minted by the PocketBase behind the old address and is dropped with
it, but the credentials to replace it were never asked for, so treating the save
as a login would report an empty password as the error.

The strings are copied out of Web App/web/src/i18n/ like the rest of the shared
wording. Two are not the web's: home reads "the address this app ships with"
rather than "served with this app", since the phone has no origin to be served
from, and sameOrigin has no meaning here at all and was dropped.

Biometric sign-in stays global. It was never per-server and replays its stored
credentials against whichever server is active; making it per-server is a change
of its own, and the login screen now names the server it is about to sign into.

Nothing changes on the API Server. On Android there is no origin to allow, so
the CORS list the web app has to satisfy to reach a second server doesn't enter
into it.

Verified: flutter analyze is clean and flutter test passes, 35 tests to 46. The
new ones cover the registry — a bare origin gaining its /api, a fresh install
knowing one unnamed server on the built-in address, the legacy keys landing on
home and being cleared, two servers holding their tokens apart, a rename keeping
a session where a move drops it, removing the active server falling back to a
home that is still signed in, home refusing to be removed, and a restart reading
the list, the active id and every session back.

Not verified: none of it has been run. There is no device or emulator on this
machine and no API Server to answer, so the picker, the add sheet, a real
connect, the 401 fallback and the shell rebuild on a switch exist only as code
the analyzer is happy with — the tests reach the registry, not a screen. No APK
was built. The legacy migration was exercised against mocked SharedPreferences,
which is not a phone that had the old build on it: that is the first thing to
check on a device, since the failure mode is a silent sign-out.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-23 21:47:01 +02:00

255 lines
16 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# DriverVault — Phone App (Flutter)
A Flutter client for the DriverVault maintenance tracker. Talks **only** to the
API Server (same contract and auth as the web app — a PocketBase token relayed by
the server, not a JWT the server mints). At full feature parity with the web app.
Project name `drivervault_phone`, package id `com.drivervault.phoneapp`.
**Android is the supported target** — the older Flutter-web build path is
deprecated.
## Features
Once signed in, `RootShell` hosts the app behind a persistent **bottom
navigation bar** — Garage, Charging, Settings, and Users for admins — in an
`IndexedStack`, so each section keeps its state as you switch tabs.
- **Login** — email/password against `/api/auth/login`, password show/hide, and a
collapsible **Server settings** section holding the address of the server the
form signs into — plus the way back to the others once more than one has been
added (see *More than one server*).
- **Biometric / face sign-in + app lock** — see the dedicated section below.
- **Garage (dashboard)** — car list with next-due status badges (date + km,
worst-of), a "shared" chip on cars owned by someone else, pull-to-refresh and
an **Add car** FAB. The header carries the **server picker** (see below), the
theme toggle and log out.
- **Car detail** — all spec fields (incl. VIN and transmission / differential /
brake / coolant specs), a **share** sheet (owner only), quick odometer update,
edit car, and delete car (type-to-confirm; cascades). Actions are gated by the
caller's access level (read-only vs write vs owner).
**Which tabs a car shows, and in what order, belongs to the car** — the same
arrangement the web app reads, so everyone it is shared with sees the same
page. Edit it under the **tune** icon: switch tabs, Information rows, Service
history columns and the parts a service can change on or off, and drag any of
the first three lists by its handle to reorder it. (The parts have no order —
they are a checkbox list inside one column, and their position says nothing a
tab's or a column's does.) (The web rearranges by dragging the tab bar and the
column headings themselves; on a touch screen those gestures belong to the tab
bar and the scroll, so every arrangement is made in the picker instead.) Two
things cannot be switched off: Information — a page with no tabs left would be
a dead end — and the service Date, since a history with the day taken out
stops being one. Both can still be moved. The tabs, in their default order:
- **Connected service** — everything the manufacturer's own app knows about
this car, read live under *your* account: headline readings (odometer, fuel
or battery, range, charging state, position), the vehicle record, and one
card per capability the plugin exposes, rendered from the server's flattened
key/value pairs so a provider adding a field surfaces it without an app
change. Offers to take the provider's odometer when it is ahead of the
stored one. A car with no link yet gets a **connect** card instead, and the
tab is hidden entirely for a user with no manufacturer account connected.
Because the read runs under your own credentials, a car shared from someone
else shows data here only if that vehicle is on your account too — it says
so rather than failing.
- **Service history** — date/odometer plus which parts were changed, with the
next-due date/km derived by the server. The web lays those out as table
columns; a phone has no width for a seven-column table, so a card renders the
same columns as pieces — consecutive short ones share a wrapping line, and
the parts, the notes and the file each take a line of their own. It reads the
car's own hidden set and order, so a column switched off on either app is off
on both, and the arrangement decides the grouping: move Notes between Km and
Next date and the short columns split around it. Every part a service can
have changed shares the one **parts** column — they are a growing list, and a
column apiece would widen the web's table without end — and both that column
and the form's Changed parts section come from `lib/service_parts.dart`, the
twin of the web's `lib/serviceParts.js`. Which of them this car records is
the car's own choice as well: a part switched off leaves the form's
checkboxes and the cards' chips together, and nothing is written to the
records, so switching it back on brings the old chips back.
- **Technical check history** — the mandatory roadworthiness inspections
(przegląd techniczny, MOT, TÜV). Result, cost, station, and the certificate's
valid-until, which overrides the car's interval when present. A failed check
derives no next date.
- **Maintenance** — workshop visits and repairs outside the routine schedule:
type/status, workshop, parts used, labour + parts cost, invoice number and a
warranty-until badge.
- **Fuel** — refills with a summary panel (average / best / worst consumption,
cost per km, price per litre). Consumption is measured between full tanks, so
partial fills roll into the next full one and a flagged missed fill leaves its
window uncomputed rather than reporting a fictional figure.
- **Charging cost** — charges with a summary panel (average / best / worst
kWh/100km, cost per km, price per kWh). The electric twin of Fuel, and
derived the same way: consumption is measured between full charges, so a
top-up rolls into the next full one. Distinct from the **Charging** section
in the bottom bar, which is the charger network and OCPP control.
- **Documents** — insurance, registration, road tax and the rest, with a
renewal badge driven by the server's expiry assessment.
- **Parts catalog** — the per-car parts list.
- **Reminders** — date- and/or odometer-triggered, one-off or recurring, with a
**Mark done** action. Reminders the server derived from a document or service
record are shown read-only.
- **Attachments** — one optional file per service record, technical check,
workshop visit, refill, charge, document and part (PDF or image, up to 10MB). Picked
with `file_picker`, fetched back through the API Server — never a public URL —
and opened with the phone's own viewer via `open_filex`.
- **Charging** — mirrors the web `Charging.vue`, split into two tabs. **Public**
is a discovery map with a demo session and nearby stations: presentational
placeholders, because there is no public-charging API yet (same as the web).
**Home** carries the one real piece — an OCPP control card that drives your
own charger through the Anker Solix control endpoints, once you pick Own/Proxy
CSMS under Settings → Integrations.
- **Settings** — account (name / email verification / password), appearance
(theme + dark mode, **language**, **region**, date format, **currency**, font
size), profile (avatar via `image_picker`, bio), **integrations** (Toyota,
Anker Solix), **Security** (biometric toggle), **Organization** (create your
own — which makes you its admin — or rename/delete the one you administer),
**data export/import**, and the account-deletion state machine. Export writes
the account JSON into the app's own documents directory and offers to open it;
import picks a previously exported file and always creates new records, so it
asks first, with the number of cars the file actually holds. Auth relays PocketBase's own stateless
tokens, so there is no per-device session list to show or revoke.
- **Users (admin)** — user management tab (list / create / role / reset password
/ delete), shown only for the admin role. A blocked control says why rather
than only greying out: long-press a locked role picker, and the overflow menu
carries the reason under the action. Superadmins also choose which
organization a new account lands in (or none at all); an admin gets no picker,
because the server puts their members in their own organization regardless.
Sharing/ownership: `Car.access` drives `isOwner` / `canWrite` / `isReadOnly`
getters that gate the UI, mirroring the server's access checks.
## Language, region & currency
Language and region are two pickers over the one stored BCP-47 tag (`en-US`), so
the pair can be mixed — English in Poland, say. Currency is display-only: nothing
is converted, so changing it reinterprets existing amounts rather than
recalculating them. All three lists mirror the API's (`validCurrencies` and the
locale pattern in `internal/api/me.go`), with two deliberate differences from the
web app:
- **Luxembourgish (`lb`) and Romansh (`rm`) are not offered.** `intl` ships no
date/number symbols for them and *throws* rather than falling back, which would
take out every date on screen. The browser has full ICU data behind it and has
no such limit, so the web app can list them.
- **Labels are hand-kept** (endonyms for languages, English for regions and
currencies) because Dart has no `Intl.DisplayNames`.
Because the server only validates a locale's *shape* (`^[a-z]{2}-[A-Z]{2}$`), a
tag the phone cannot render can still arrive from the web. `format.dart` resolves
through a supported-language check and falls back to `en-US` instead of throwing;
`test/models_format_test.dart` covers it.
Every screen reads its text from the language files, and `flutter test` fails if
a key exists in English but not in Polish or Danish. See
[TRANSLATIONS.md](../TRANSLATIONS.md).
## Biometric / face sign-in & app lock
Fingerprint and face-recognition sign-in via `local_auth`, with credentials kept
in Android Keystore–backed secure storage (`flutter_secure_storage`).
- After a successful password login the app offers to **enable biometric login**;
the entered (known-good) credentials are stored securely.
- The login screen then shows **"Sign in with face recognition / fingerprint"**
buttons (labels reflect the enrolled biometric kinds) and auto-prompts once.
On success the stored credentials are replayed against the normal login API, so
each biometric sign-in mints a fresh session. Stale credentials (e.g. after a
password change) auto-disable biometric login.
- **App lock** — the token persists, so a valid session normally restores silently.
When biometric login is enabled the app instead starts **locked** (and re-locks
when backgrounded) and shows a lock screen requiring a biometric unlock. A
**30-second grace period** means quick app-switches don't re-lock; a full app
close (process kill) always locks on next launch. "Use password instead" on the
lock screen logs out and returns to the login form.
- Manage it under **Settings → Security** (enabling re-confirms the password).
Android host requirements (already configured, don't revert):
`MainActivity` extends **`FlutterFragmentActivity`** (required by `local_auth`),
and `AndroidManifest.xml` declares `android.permission.USE_BIOMETRIC`.
## More than one server
Two sites, two full DriverVault stacks — and one app. The server picker is the
first button in the Garage header: it names the server you are reading right
now, and switches between them in a tap. With only one server known there is
nothing to pick between, so it goes straight to adding the second.
- **The home server** is the address this build ships with (`kDefaultApiBase`,
overridable per-device from the login screen's **Server settings**). It is
always in the list and can't be removed.
- **Any other server** is added by address — `https://garage.example.com`; the
`/api` is appended for you if you leave the path off — and has to be reachable
from wherever the phone is.
- **A session per server.** Each server is its own PocketBase with its own users,
so a token can't be carried across: you sign into each one once, and after that
switching needs no password. Sessions live in `SharedPreferences` under
`cc_session_<id>`, the list under `cc_servers`, the active one under
`cc_active_server`.
- **Switching rebuilds the shell**, because record ids belong to the server that
issued them — the garage, the charging page and the settings all re-read from
the one now active, and its owner's appearance prefs come with it.
- **An expiring remote session doesn't sign you out of the app**: that server's
token is dropped, the app falls back to the home server, and the entry stays in
the list to sign into again. Only *Log out* clears every server at once.
Upgrading from a single-server build carries what was there onto the home entry
— the saved session (`cc_token` / `cc_user`) and the address it was pointed at
(`cc_server_url`) — so nobody is signed out by the update.
## Configure the API endpoint
The app talks to `kDefaultApiBase` (see `lib/config.dart`), default
`http://localhost:8080/api`. Override at build time with `--dart-define`, or at
runtime from the login screen's **Server settings**, which edits the address of
the active server — on a fresh install, the home one (persisted in `cc_servers`).
## Run & build
```bash
flutter pub get
# run on a connected device against a LAN server
flutter run -d <device> --dart-define=API_BASE=http://10.2.1.101:8080/api
# build a debug APK for a real phone on the LAN
flutter build apk --debug --dart-define=API_BASE=http://10.2.1.101:8080/api
adb install -r build/app/outputs/flutter-apk/app-debug.apk
adb shell monkey -p com.drivervault.phoneapp -c android.intent.category.LAUNCHER 1
```
Notes:
- `android/gradle.properties` sets `kotlin.incremental=false` — required because
the project lives on drive `E:` while Gradle/Kotlin caches are on `C:` (the
incremental compiler can't compute cross-root relative paths on Windows).
- `AndroidManifest.xml` sets `android:usesCleartextTraffic="true"` because the API
base is a plain-HTTP LAN URL.
- The API Server must be running and reachable at the configured URL.
## Structure
```
lib/
├── config.dart # default API base URL (kDefaultApiBase)
├── models.dart # Car (+ access getters), the record types, integrations, profile
├── api.dart # ApiClient — the only thing that calls the API Server
├── auth.dart # AuthService — the active server's session, app-lock flag
├── servers.dart # ServerRegistry — the servers, their sessions, the active one
├── biometric.dart # BiometricAuth — local_auth + secure storage; biometricAuth singleton
├── app_settings.dart # AppSettings (theme/locale/date/font), persisted; drives MaterialApp
├── i18n.dart # translation lookup — t("key"); en/pl/da with en fallback
├── theme.dart # shared colours/tones (status badges, charging tiles)
├── format.dart # date/km formatting + next-service status (worst-of date/km)
├── service_parts.dart # the parts a service can change, in one list
├── main.dart # app root; routes Login / Lock / RootShell; lifecycle re-lock
├── widgets/
│ └── attachment_field.dart # pick / view / clear a record's attached file
└── screens/
├── root_shell.dart # bottom-nav shell: Garage, Charging, Settings, Users
├── login_screen.dart lock_screen.dart dashboard_screen.dart
├── car_detail_screen.dart car_form_sheet.dart record_form_sheets.dart
├── car_view_sheet.dart # which tabs/rows/columns a car shows + the catalogues
├── provider_tab.dart # the connected-service tab (MyToyota)
├── servers_sheet.dart # the server picker + the add / edit / sign-in sheet
└── charging_screen.dart settings_screen.dart admin_users_screen.dart
```