Compare commits

...

12 Commits

Author SHA1 Message Date
69bd6f688a Add friends leaderboard, reverse button in add page
All checks were successful
Release / meta (push) Successful in 8s
Release / linux-build (push) Successful in 7m11s
Release / web-build (push) Successful in 5m3s
Release / android-build (push) Successful in 18m23s
Release / release-master (push) Successful in 22s
Release / release-dev (push) Successful in 25s
2026-01-03 13:22:43 +00:00
89b760508d Add new friends system, and sharing legs support
All checks were successful
Release / meta (push) Successful in 9s
Release / linux-build (push) Successful in 6m37s
Release / web-build (push) Successful in 5m29s
Release / android-build (push) Successful in 15m58s
Release / release-master (push) Successful in 20s
Release / release-dev (push) Successful in 26s
2026-01-03 01:07:08 +00:00
42af39b442 fix issue with version and app id
All checks were successful
Release / meta (push) Successful in 7s
Release / linux-build (push) Successful in 6m42s
Release / web-build (push) Successful in 5m38s
Release / android-build (push) Successful in 15m17s
Release / release-master (push) Successful in 24s
Release / release-dev (push) Successful in 28s
2026-01-02 19:10:32 +00:00
2fa66ff9c6 add admin page, fix no legs infinite load on dashboard
All checks were successful
Release / meta (push) Successful in 8s
Release / linux-build (push) Successful in 6m49s
Release / web-build (push) Successful in 6m23s
Release / android-build (push) Successful in 16m56s
Release / release-master (push) Successful in 30s
Release / release-dev (push) Successful in 32s
2026-01-02 18:49:14 +00:00
29cecf0ded add android bundle release
All checks were successful
Release / meta (push) Successful in 10s
Release / linux-build (push) Successful in 6m32s
Release / web-build (push) Successful in 5m50s
Release / android-build (push) Successful in 20m43s
Release / release-master (push) Successful in 26s
Release / release-dev (push) Successful in 28s
2026-01-02 14:34:11 +00:00
f9c392bb07 new app icon
All checks were successful
Release / meta (push) Successful in 10s
Release / linux-build (push) Successful in 7m21s
Release / web-build (push) Successful in 7m30s
Release / android-build (push) Successful in 19m56s
Release / release-dev (push) Successful in 25s
Release / release-master (push) Successful in 24s
2026-01-02 00:18:57 +00:00
e5b145b4b2 increment verison
All checks were successful
Release / meta (push) Successful in 7s
Release / linux-build (push) Successful in 6m28s
Release / web-build (push) Successful in 6m54s
Release / android-build (push) Successful in 18m9s
Release / release-master (push) Successful in 38s
Release / release-dev (push) Successful in 41s
2026-01-01 23:13:18 +00:00
59458484aa add build step for flutter web, add persistent pagination in the traction list
Some checks failed
Release / meta (push) Successful in 14s
Release / web-build (push) Has been cancelled
Release / release-dev (push) Has been cancelled
Release / release-master (push) Has been cancelled
Release / linux-build (push) Has been cancelled
Release / android-build (push) Has been cancelled
2026-01-01 23:08:22 +00:00
648872acf1 re add mileograph tags
All checks were successful
Release / meta (push) Successful in 10s
Release / linux-build (push) Successful in 6m40s
Release / android-build (push) Successful in 14m28s
Release / release-master (push) Successful in 32s
Release / release-dev (push) Successful in 36s
2026-01-01 18:06:50 +00:00
b427ed0bd3 fix failed flutter install
Some checks failed
Release / meta (push) Successful in 2s
Release / android-build (push) Failing after 2m7s
Release / linux-build (push) Failing after 2m6s
Release / release-dev (push) Has been skipped
Release / release-master (push) Has been skipped
2026-01-01 17:26:54 +00:00
66a1d149f0 remove mileograph tag
Some checks failed
Release / meta (push) Successful in 26s
Release / android-build (push) Failing after 2m38s
Release / linux-build (push) Failing after 2m58s
Release / release-dev (push) Has been skipped
Release / release-master (push) Has been skipped
2026-01-01 17:11:55 +00:00
cea483ae0b Add ability to select distance unit
Some checks failed
Release / android-build (push) Blocked by required conditions
Release / meta (push) Successful in 10s
Release / linux-build (push) Successful in 6m39s
Release / release-dev (push) Has been cancelled
Release / release-master (push) Has been cancelled
2026-01-01 15:28:11 +00:00
89 changed files with 5105 additions and 1067 deletions

View File

@@ -12,6 +12,7 @@ env:
FLUTTER_VERSION: "3.38.5" FLUTTER_VERSION: "3.38.5"
BUILD_WINDOWS: "false" # Windows build disabled (no runner available) BUILD_WINDOWS: "false" # Windows build disabled (no runner available)
GITEA_BASE_URL: https://git.tgj.services GITEA_BASE_URL: https://git.tgj.services
WEB_IMAGE: "git.tgj.services/petegregoryy/mileograph-web"
jobs: jobs:
meta: meta:
@@ -123,6 +124,8 @@ jobs:
run: | run: |
set -euo pipefail set -euo pipefail
FLUTTER_HOME="$HOME/flutter" FLUTTER_HOME="$HOME/flutter"
# Avoid git ownership issues when Flutter checks out deps.
git config --global --add safe.directory "$FLUTTER_HOME" || true
if [ ! -x "$FLUTTER_HOME/bin/flutter" ]; then if [ ! -x "$FLUTTER_HOME/bin/flutter" ]; then
rm -rf "$FLUTTER_HOME" rm -rf "$FLUTTER_HOME"
curl -fsSL -o /tmp/flutter.tar.xz "https://storage.googleapis.com/flutter_infra_release/releases/stable/linux/flutter_linux_${FLUTTER_VERSION}-stable.tar.xz" curl -fsSL -o /tmp/flutter.tar.xz "https://storage.googleapis.com/flutter_infra_release/releases/stable/linux/flutter_linux_${FLUTTER_VERSION}-stable.tar.xz"
@@ -152,6 +155,18 @@ jobs:
- name: Build Android App Bundle (release) - name: Build Android App Bundle (release)
run: flutter build appbundle --release run: flutter build appbundle --release
- name: Archive Android App Bundle
env:
BASE_VERSION: ${{ needs.meta.outputs.base_version }}
run: |
set -euo pipefail
BUNDLE_SRC="build/app/outputs/bundle/release/app-release.aab"
if [ ! -f "$BUNDLE_SRC" ]; then
echo "Bundle not found at $BUNDLE_SRC"
exit 1
fi
cp "$BUNDLE_SRC" "mileograph-${BASE_VERSION}.aab"
- name: Download bundletool - name: Download bundletool
run: | run: |
BUNDLETOOL_VERSION=1.15.6 BUNDLETOOL_VERSION=1.15.6
@@ -198,6 +213,12 @@ jobs:
name: android-apk name: android-apk
path: mileograph-${{ needs.meta.outputs.base_version }}.apk path: mileograph-${{ needs.meta.outputs.base_version }}.apk
- name: Upload Android AAB artifact
uses: actions/upload-artifact@v3
with:
name: android-aab
path: mileograph-${{ needs.meta.outputs.base_version }}.aab
linux-build: linux-build:
runs-on: runs-on:
- mileograph - mileograph
@@ -220,6 +241,8 @@ jobs:
run: | run: |
set -euo pipefail set -euo pipefail
FLUTTER_HOME="$HOME/flutter" FLUTTER_HOME="$HOME/flutter"
# Avoid git ownership issues when Flutter checks out deps.
git config --global --add safe.directory "$FLUTTER_HOME" || true
if [ ! -x "$FLUTTER_HOME/bin/flutter" ]; then if [ ! -x "$FLUTTER_HOME/bin/flutter" ]; then
rm -rf "$FLUTTER_HOME" rm -rf "$FLUTTER_HOME"
curl -fsSL -o /tmp/flutter.tar.xz "https://storage.googleapis.com/flutter_infra_release/releases/stable/linux/flutter_linux_${FLUTTER_VERSION}-stable.tar.xz" curl -fsSL -o /tmp/flutter.tar.xz "https://storage.googleapis.com/flutter_infra_release/releases/stable/linux/flutter_linux_${FLUTTER_VERSION}-stable.tar.xz"
@@ -251,6 +274,108 @@ jobs:
name: linux-bundle name: linux-bundle
path: app-linux-x64.tar.gz path: app-linux-x64.tar.gz
web-build:
runs-on:
- mileograph
needs: meta
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install OS deps (Web)
run: |
if command -v sudo >/dev/null 2>&1; then
SUDO="sudo"
else
SUDO=""
fi
$SUDO apt-get update
$SUDO apt-get install -y unzip xz-utils zip libstdc++6 liblzma-dev curl jq docker.io
if ! docker info >/dev/null 2>&1; then
$SUDO systemctl start docker 2>/dev/null || $SUDO service docker start 2>/dev/null || true
fi
- name: Install Flutter SDK
run: |
set -euo pipefail
FLUTTER_HOME="$HOME/flutter"
git config --global --add safe.directory "$FLUTTER_HOME" || true
if [ ! -x "$FLUTTER_HOME/bin/flutter" ]; then
rm -rf "$FLUTTER_HOME"
curl -fsSL -o /tmp/flutter.tar.xz "https://storage.googleapis.com/flutter_infra_release/releases/stable/linux/flutter_linux_${FLUTTER_VERSION}-stable.tar.xz"
tar -C "$HOME" -xf /tmp/flutter.tar.xz
fi
echo "$FLUTTER_HOME/bin" >> "$GITHUB_PATH"
"$FLUTTER_HOME/bin/flutter" --version
- name: Allow all git directories (CI)
run: git config --global --add safe.directory '*'
- name: Set pub cache path
run: echo "PUB_CACHE=${GITHUB_WORKSPACE}/.pub-cache" >> "$GITHUB_ENV"
- name: Flutter dependencies
run: flutter pub get
- name: Enable Flutter web
run: flutter config --enable-web
- name: Build Flutter web (release)
run: |
flutter build web --release --base-href=/
tar -C build/web -czf app-web.tar.gz .
- name: Upload Web artifact
uses: actions/upload-artifact@v3
with:
name: web-build
path: app-web.tar.gz
- name: Compute web image tags
id: web_meta
env:
BASE_VERSION: ${{ needs.meta.outputs.base_version }}
DEV_SUFFIX: ${{ needs.meta.outputs.dev_suffix }}
run: |
IMAGE="${WEB_IMAGE}"
TAG=""
ALIAS=""
if [ "${GITHUB_REF}" = "refs/heads/dev" ]; then
TAG="${BASE_VERSION}${DEV_SUFFIX}"
ALIAS="dev"
elif [ "${GITHUB_REF}" = "refs/heads/master" ]; then
TAG="${BASE_VERSION}"
ALIAS="latest"
fi
echo "image=${IMAGE}" >> "$GITHUB_OUTPUT"
echo "tag=${TAG}" >> "$GITHUB_OUTPUT"
echo "alias=${ALIAS}" >> "$GITHUB_OUTPUT"
- name: Login to registry
if: ${{ secrets.DOCKERHUB_TOKEN != '' && steps.web_meta.outputs.tag != '' }}
env:
REGISTRY_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}
run: |
echo "$REGISTRY_TOKEN" | docker login git.tgj.services -u petegregoryy --password-stdin
- name: Build and push web image
if: ${{ secrets.DOCKERHUB_TOKEN != '' && steps.web_meta.outputs.tag != '' }}
env:
IMAGE: ${{ steps.web_meta.outputs.image }}
TAG: ${{ steps.web_meta.outputs.tag }}
ALIAS: ${{ steps.web_meta.outputs.alias }}
run: |
docker buildx create --name buildx --driver=docker-container --use || docker buildx use buildx
TAG_ARGS=(-t "${IMAGE}:${TAG}")
if [ -n "$ALIAS" ]; then
TAG_ARGS+=(-t "${IMAGE}:${ALIAS}")
fi
docker buildx build --builder buildx --platform linux/amd64 \
-f Dockerfile.web \
--push \
"${TAG_ARGS[@]}" .
release-dev: release-dev:
runs-on: runs-on:
- mileograph - mileograph
@@ -258,6 +383,7 @@ jobs:
- meta - meta
- android-build - android-build
- linux-build - linux-build
- web-build
steps: steps:
- name: Install jq - name: Install jq
run: | run: |
@@ -275,6 +401,13 @@ jobs:
name: android-apk name: android-apk
path: artifacts path: artifacts
- name: Download Android AAB
if: ${{ github.ref == 'refs/heads/dev' }}
uses: actions/download-artifact@v3
with:
name: android-aab
path: artifacts
- name: Prepare APK and tag - name: Prepare APK and tag
if: ${{ github.ref == 'refs/heads/dev' }} if: ${{ github.ref == 'refs/heads/dev' }}
id: bundle id: bundle
@@ -289,11 +422,14 @@ jobs:
VERSION="${BASE}${DEV_SUFFIX}" VERSION="${BASE}${DEV_SUFFIX}"
APK_NAME="mileograph-${VERSION}.apk" APK_NAME="mileograph-${VERSION}.apk"
AAB_NAME="mileograph-${VERSION}.aab"
mv "artifacts/mileograph-${BASE}.apk" "artifacts/${APK_NAME}" mv "artifacts/mileograph-${BASE}.apk" "artifacts/${APK_NAME}"
mv "artifacts/mileograph-${BASE}.aab" "artifacts/${AAB_NAME}"
echo "tag=${TAG}" >> "$GITHUB_OUTPUT" echo "tag=${TAG}" >> "$GITHUB_OUTPUT"
echo "apk=artifacts/${APK_NAME}" >> "$GITHUB_OUTPUT" echo "apk=artifacts/${APK_NAME}" >> "$GITHUB_OUTPUT"
echo "aab=artifacts/${AAB_NAME}" >> "$GITHUB_OUTPUT"
- name: Create prerelease on Gitea - name: Create prerelease on Gitea
if: ${{ github.ref == 'refs/heads/dev' }} if: ${{ github.ref == 'refs/heads/dev' }}
@@ -334,6 +470,18 @@ jobs:
"${GITEA_BASE_URL}/api/v1/repos/${{ github.repository }}/releases/${RELEASE_ID}/assets" \ "${GITEA_BASE_URL}/api/v1/repos/${{ github.repository }}/releases/${RELEASE_ID}/assets" \
>/dev/null >/dev/null
# Attach AAB
AAB="${{ steps.bundle.outputs.aab }}"
NAME_AAB=$(basename "$AAB")
echo "Uploading $NAME_AAB"
curl -sS -X POST \
-H "Authorization: token ${{ secrets.GITEA_TOKEN }}" \
-F "attachment=@${AAB}" \
-F "name=${NAME_AAB}" \
"${GITEA_BASE_URL}/api/v1/repos/${{ github.repository }}/releases/${RELEASE_ID}/assets" \
>/dev/null
release-master: release-master:
runs-on: runs-on:
- mileograph - mileograph
@@ -341,6 +489,7 @@ jobs:
- meta - meta
- android-build - android-build
- linux-build - linux-build
- web-build
steps: steps:
- name: Install jq - name: Install jq
run: | run: |
@@ -358,6 +507,13 @@ jobs:
name: android-apk name: android-apk
path: artifacts path: artifacts
- name: Download Android AAB
if: ${{ github.ref == 'refs/heads/master' }}
uses: actions/download-artifact@v3
with:
name: android-aab
path: artifacts
- name: Prepare APK and tag - name: Prepare APK and tag
if: ${{ github.ref == 'refs/heads/master' }} if: ${{ github.ref == 'refs/heads/master' }}
id: bundle id: bundle
@@ -367,6 +523,7 @@ jobs:
echo "tag=${TAG}" >> "$GITHUB_OUTPUT" echo "tag=${TAG}" >> "$GITHUB_OUTPUT"
echo "apk=artifacts/mileograph-${BASE}.apk" >> "$GITHUB_OUTPUT" echo "apk=artifacts/mileograph-${BASE}.apk" >> "$GITHUB_OUTPUT"
echo "aab=artifacts/mileograph-${BASE}.aab" >> "$GITHUB_OUTPUT"
- name: Create release on Gitea - name: Create release on Gitea
if: ${{ github.ref == 'refs/heads/master' }} if: ${{ github.ref == 'refs/heads/master' }}
@@ -405,3 +562,15 @@ jobs:
-F "name=${NAME}" \ -F "name=${NAME}" \
"${GITEA_BASE_URL}/api/v1/repos/${{ github.repository }}/releases/${RELEASE_ID}/assets" \ "${GITEA_BASE_URL}/api/v1/repos/${{ github.repository }}/releases/${RELEASE_ID}/assets" \
>/dev/null >/dev/null
# Attach AAB
AAB="${{ steps.bundle.outputs.aab }}"
NAME_AAB=$(basename "$AAB")
echo "Uploading $NAME_AAB"
curl -sS -X POST \
-H "Authorization: token ${{ secrets.GITEA_TOKEN }}" \
-F "attachment=@${AAB}" \
-F "name=${NAME_AAB}" \
"${GITEA_BASE_URL}/api/v1/repos/${{ github.repository }}/releases/${RELEASE_ID}/assets" \
>/dev/null

10
Dockerfile.web Normal file
View File

@@ -0,0 +1,10 @@
FROM nginx:1.27-alpine
# Use a minimal Nginx image to serve the built Flutter web app.
# Assumes `flutter build web` has already populated build/web/ in the build context.
COPY deploy/web/nginx.conf /etc/nginx/conf.d/default.conf
COPY build/web /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

View File

@@ -1,16 +1,67 @@
# mileograph_flutter # Mileograph (Flutter)
A new Flutter project. Mileograph is a Flutter client for logging and analysing railway journeys. It lets you record legs, group them into trips, track locomotive mileage, and view stats and leaderboards.
## Getting Started ## Features
- Add and edit journey legs with traction, timings, routes, notes, and delays.
- Group legs into trips and see mileage totals and traction stats.
- Browse traction, view loco details, mileage leaderboards, timelines, and legs.
- Dashboard with homepage stats, “On This Day”, recent traction changes, and trips.
- Profile badges, class clearance progress, and traction progress.
- Offline-friendly UI built with Provider, GoRouter, and Material 3 styling.
This project is a starting point for a Flutter application. ## Project layout
- `lib/objects/objects.dart` — shared model classes and helpers.
- `lib/services/` — API, data loading, auth, endpoints, distance units.
- `lib/components/` — UI pages and widgets (entries, traction, dashboard, trips, settings, etc.).
- `assets/` — icons/fonts and other bundled assets.
A few resources to get you started if this is your first Flutter project: ## Prerequisites
- Flutter SDK (3.x or later recommended).
- Dart SDK (bundled with Flutter).
- A Mileograph API endpoint (set in Settings within the app).
- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) ## Setup
- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook) 1) Install Flutter: follow https://docs.flutter.dev/get-started/install and ensure `flutter doctor` is green.
2) Get dependencies:
```bash
flutter pub get
```
3) Configure an API endpoint:
- Run the app, open Settings, and set the base URL for your Mileograph backend.
- The app probes the endpoint for a version string before saving.
For help getting started with Flutter development, view the ## Running
[online documentation](https://docs.flutter.dev/), which offers tutorials, - Debug (mobile/web depending on your toolchain):
samples, guidance on mobile development, and a full API reference. ```bash
flutter run
```
- Release build (example for Android):
```bash
flutter build apk --release
```
## Testing and linting
- Static analysis: `flutter analyze`
- Unit/widget tests (if present): `flutter test`
## Contributing
1) Fork or branch from `main`.
2) Make changes with clear, small commits.
3) Add tests where feasible and keep `flutter analyze` clean.
4) Submit a PR describing:
- What changed and why.
- How to test or reproduce.
- Any API or migration notes.
### Coding conventions
- Prefer stateless widgets where possible; keep state localized.
- Use existing services in `lib/services` for API access; add new endpoints there.
- Keep models in `objects.dart` (or nearby files) and use helper parsers for defensive JSON handling.
- Follow Material theming already in use; keep strings user-facing and concise.
### Issue reporting
Include device/OS, Flutter version (`flutter --version`), steps to reproduce, expected vs. actual behaviour, and logs if available.
## License
Copyright © Mileograph contributors. See repository terms if provided.

View File

@@ -1,3 +1,4 @@
import java.io.File
import java.util.Properties import java.util.Properties
plugins { plugins {
@@ -22,8 +23,21 @@ val releaseKeyAlias = System.getenv("ANDROID_KEY_ALIAS")
val releaseKeyPassword = System.getenv("ANDROID_KEY_PASSWORD") val releaseKeyPassword = System.getenv("ANDROID_KEY_PASSWORD")
?: keystoreProperties.getProperty("keyPassword") ?: keystoreProperties.getProperty("keyPassword")
val releaseStoreFilePath: File? = releaseStoreFile?.let { path ->
val candidate = File(path)
if (candidate.isAbsolute) return@let candidate
val candidates = listOfNotNull(
rootProject.file(path),
rootProject.projectDir.parentFile?.let { File(it, path) },
project.file(path),
)
candidates.firstOrNull { it.exists() }
}
val hasReleaseKeystore = listOf( val hasReleaseKeystore = listOf(
releaseStoreFile, releaseStoreFilePath?.path,
releaseStorePassword, releaseStorePassword,
releaseKeyAlias, releaseKeyAlias,
releaseKeyPassword releaseKeyPassword
@@ -31,7 +45,7 @@ val hasReleaseKeystore = listOf(
android { android {
namespace = "com.example.mileograph_flutter" namespace = "com.example.mileograph_flutter"
compileSdk = flutter.compileSdkVersion compileSdk = 36
ndkVersion = "27.0.12077973" ndkVersion = "27.0.12077973"
compileOptions { compileOptions {
@@ -48,8 +62,8 @@ android {
applicationId = "com.petegregoryy.mileograph_flutter" applicationId = "com.petegregoryy.mileograph_flutter"
// You can update the following values to match your application needs. // You can update the following values to match your application needs.
// For more information, see: https://flutter.dev/to/review-gradle-config. // For more information, see: https://flutter.dev/to/review-gradle-config.
minSdk = flutter.minSdkVersion minSdk = 24
targetSdk = flutter.targetSdkVersion targetSdk = 36
versionCode = flutter.versionCode versionCode = flutter.versionCode
versionName = flutter.versionName versionName = flutter.versionName
} }
@@ -57,7 +71,7 @@ android {
signingConfigs { signingConfigs {
if (hasReleaseKeystore) { if (hasReleaseKeystore) {
create("release") { create("release") {
storeFile = file(releaseStoreFile!!) storeFile = releaseStoreFilePath
storePassword = releaseStorePassword storePassword = releaseStorePassword
keyAlias = releaseKeyAlias!! keyAlias = releaseKeyAlias!!
keyPassword = releaseKeyPassword keyPassword = releaseKeyPassword

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.7 KiB

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.0 KiB

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.6 KiB

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

After

Width:  |  Height:  |  Size: 1014 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 689 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.1 KiB

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.3 KiB

After

Width:  |  Height:  |  Size: 2.4 KiB

View File

@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<resources> <resources>
<color name="ic_launcher_background">#ffffff</color> <color name="ic_launcher_background">#000000</color>
</resources> </resources>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.2 KiB

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

28
deploy/web/nginx.conf Normal file
View File

@@ -0,0 +1,28 @@
server {
listen 80;
server_name _;
root /usr/share/nginx/html;
include /etc/nginx/mime.types;
# Serve hashed assets aggressively; keep index/service worker cacheable but not immutable.
location /assets/ {
try_files $uri =404;
expires 30d;
add_header Cache-Control "public, max-age=2592000, immutable";
}
location /icons/ {
try_files $uri =404;
expires 30d;
add_header Cache-Control "public, max-age=2592000";
}
location = /flutter_service_worker.js {
add_header Cache-Control "no-cache";
try_files $uri =404;
}
location / {
try_files $uri $uri/ /index.html;
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 55 KiB

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 598 B

After

Width:  |  Height:  |  Size: 346 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 497 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 KiB

After

Width:  |  Height:  |  Size: 738 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 834 B

After

Width:  |  Height:  |  Size: 425 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 KiB

After

Width:  |  Height:  |  Size: 697 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.4 KiB

After

Width:  |  Height:  |  Size: 1017 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 497 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

After

Width:  |  Height:  |  Size: 876 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 632 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 KiB

After

Width:  |  Height:  |  Size: 698 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.2 KiB

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.1 KiB

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

After

Width:  |  Height:  |  Size: 834 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.1 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

After

Width:  |  Height:  |  Size: 841 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.3 KiB

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.8 KiB

After

Width:  |  Height:  |  Size: 1.7 KiB

View File

@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:mileograph_flutter/services/api_service.dart'; import 'package:mileograph_flutter/services/api_service.dart';
import 'package:mileograph_flutter/services/authservice.dart'; import 'package:mileograph_flutter/services/authservice.dart';
import 'package:mileograph_flutter/services/data_service.dart'; import 'package:mileograph_flutter/services/data_service.dart';
import 'package:mileograph_flutter/services/distance_unit_service.dart';
import 'package:mileograph_flutter/services/endpoint_service.dart'; import 'package:mileograph_flutter/services/endpoint_service.dart';
import 'package:mileograph_flutter/ui/app_shell.dart'; import 'package:mileograph_flutter/ui/app_shell.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
@@ -16,6 +17,9 @@ class App extends StatelessWidget {
ChangeNotifierProvider<EndpointService>( ChangeNotifierProvider<EndpointService>(
create: (_) => EndpointService(), create: (_) => EndpointService(),
), ),
ChangeNotifierProvider<DistanceUnitService>(
create: (_) => DistanceUnitService(),
),
ProxyProvider<EndpointService, ApiService>( ProxyProvider<EndpointService, ApiService>(
update: (_, endpoint, api) { update: (_, endpoint, api) {
final service = api ?? ApiService(baseUrl: endpoint.baseUrl); final service = api ?? ApiService(baseUrl: endpoint.baseUrl);

View File

@@ -366,6 +366,16 @@ class _RouteCalculatorState extends State<RouteCalculator> {
spacing: 12, spacing: 12,
runSpacing: 8, runSpacing: 8,
children: [ children: [
ElevatedButton.icon(
icon: const Icon(Icons.swap_horiz),
label: const Text('Reverse route'),
onPressed: () async {
setState(() {
data.stations = data.stations.reversed.toList();
});
await _calculateRoute(data.stations);
},
),
ElevatedButton.icon( ElevatedButton.icon(
icon: const Icon(Icons.add), icon: const Icon(Icons.add),
label: const Text('Add Station'), label: const Text('Add Station'),

View File

@@ -1,4 +1,6 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:mileograph_flutter/services/distance_unit_service.dart';
import 'package:provider/provider.dart';
class RouteSummaryWidget extends StatelessWidget { class RouteSummaryWidget extends StatelessWidget {
final double distance; final double distance;
@@ -12,13 +14,14 @@ class RouteSummaryWidget extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final distanceUnits = context.watch<DistanceUnitService>();
return Padding( return Padding(
padding: const EdgeInsets.all(16), padding: const EdgeInsets.all(16),
child: Row( child: Row(
children: [ children: [
Expanded( Expanded(
child: Text( child: Text(
"Total Distance: ${distance.toStringAsFixed(2)} mi", "Total Distance: ${distanceUnits.format(distance, decimals: 2)}",
style: Theme.of(context).textTheme.titleMedium, style: Theme.of(context).textTheme.titleMedium,
), ),
), ),
@@ -48,6 +51,7 @@ class RouteDetailsView extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final distanceUnits = context.watch<DistanceUnitService>();
final highlightColor = Theme.of(context).colorScheme.primary; final highlightColor = Theme.of(context).colorScheme.primary;
final mutedColor = Theme.of(context).colorScheme.outlineVariant; final mutedColor = Theme.of(context).colorScheme.outlineVariant;
return Column( return Column(
@@ -78,7 +82,9 @@ class RouteDetailsView extends StatelessWidget {
? TextStyle(color: highlightColor, fontWeight: FontWeight.w600) ? TextStyle(color: highlightColor, fontWeight: FontWeight.w600)
: null, : null,
), ),
trailing: Text("${costs[index].toStringAsFixed(2)} mi"), trailing: Text(
distanceUnits.format(costs[index], decimals: 2),
),
); );
}, },
), ),

View File

@@ -1,17 +1,31 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:mileograph_flutter/services/data_service.dart'; import 'package:mileograph_flutter/services/data_service.dart';
import 'package:mileograph_flutter/services/distance_unit_service.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
enum _LeaderboardScope { global, friends }
class LeaderboardPanel extends StatelessWidget { class LeaderboardPanel extends StatefulWidget {
const LeaderboardPanel({super.key}); const LeaderboardPanel({super.key});
@override
State<LeaderboardPanel> createState() => _LeaderboardPanelState();
}
class _LeaderboardPanelState extends State<LeaderboardPanel> {
_LeaderboardScope _scope = _LeaderboardScope.global;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final data = context.watch<DataService>(); final data = context.watch<DataService>();
final leaderboard = data.homepageStats?.leaderboard ?? []; final distanceUnits = context.watch<DistanceUnitService>();
final leaderboard = _scope == _LeaderboardScope.global
? (data.homepageStats?.leaderboard ?? [])
: data.friendsLeaderboard;
final loading = _scope == _LeaderboardScope.global
? data.isHomepageLoading
: data.isFriendsLeaderboardLoading;
final textTheme = Theme.of(context).textTheme; final textTheme = Theme.of(context).textTheme;
if (data.isHomepageLoading && leaderboard.isEmpty) { if (loading && leaderboard.isEmpty) {
return const Padding( return const Padding(
padding: EdgeInsets.all(16.0), padding: EdgeInsets.all(16.0),
child: Center(child: CircularProgressIndicator()), child: Center(child: CircularProgressIndicator()),
@@ -49,6 +63,38 @@ class LeaderboardPanel extends StatelessWidget {
style: textTheme.labelSmall, style: textTheme.labelSmall,
), ),
), ),
const SizedBox(width: 8),
SegmentedButton<_LeaderboardScope>(
segments: const [
ButtonSegment(
value: _LeaderboardScope.global,
label: Text('Global'),
),
ButtonSegment(
value: _LeaderboardScope.friends,
label: Text('Friends'),
),
],
selected: {_scope},
onSelectionChanged: (vals) async {
if (vals.isEmpty) return;
final selected = vals.first;
setState(() => _scope = selected);
if (selected == _LeaderboardScope.friends &&
data.friendsLeaderboard.isEmpty &&
!data.isFriendsLeaderboardLoading) {
await data.fetchFriendsLeaderboard();
} else if (selected == _LeaderboardScope.global &&
(data.homepageStats?.leaderboard.isEmpty ?? true) &&
!data.isHomepageLoading) {
await data.fetchHomepageStats();
}
},
style: SegmentedButton.styleFrom(
visualDensity: VisualDensity.compact,
padding: const EdgeInsets.symmetric(horizontal: 8),
),
),
], ],
), ),
const SizedBox(height: 8), const SizedBox(height: 8),
@@ -82,7 +128,10 @@ class LeaderboardPanel extends StatelessWidget {
), ),
), ),
trailing: Text( trailing: Text(
'${leaderboard[index].mileage.toStringAsFixed(1)} mi', distanceUnits.format(
leaderboard[index].mileage,
decimals: 1,
),
style: textTheme.labelLarge?.copyWith( style: textTheme.labelLarge?.copyWith(
fontWeight: FontWeight.w700, fontWeight: FontWeight.w700,
), ),

View File

@@ -1,6 +1,6 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:mileograph_flutter/services/data_service.dart'; import 'package:mileograph_flutter/services/data_service.dart';
import 'package:mileograph_flutter/services/distance_unit_service.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
class TopTractionPanel extends StatelessWidget { class TopTractionPanel extends StatelessWidget {
@@ -9,6 +9,7 @@ class TopTractionPanel extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final data = context.watch<DataService>(); final data = context.watch<DataService>();
final distanceUnits = context.watch<DistanceUnitService>();
final stats = data.homepageStats; final stats = data.homepageStats;
final locos = stats?.topLocos ?? []; final locos = stats?.topLocos ?? [];
final textTheme = Theme.of(context).textTheme; final textTheme = Theme.of(context).textTheme;
@@ -78,7 +79,10 @@ class TopTractionPanel extends StatelessWidget {
), ),
), ),
trailing: Text( trailing: Text(
'${locos[index].mileage?.toStringAsFixed(1)} mi', distanceUnits.format(
locos[index].mileage ?? 0,
decimals: 1,
),
style: textTheme.labelLarge?.copyWith( style: textTheme.labelLarge?.copyWith(
fontWeight: FontWeight.w700, fontWeight: FontWeight.w700,
), ),

View File

@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart'; import 'package:go_router/go_router.dart';
import 'package:mileograph_flutter/objects/objects.dart'; import 'package:mileograph_flutter/objects/objects.dart';
import 'package:mileograph_flutter/services/data_service.dart'; import 'package:mileograph_flutter/services/data_service.dart';
import 'package:mileograph_flutter/services/distance_unit_service.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
class LegCard extends StatefulWidget { class LegCard extends StatefulWidget {
@@ -26,9 +27,15 @@ class _LegCardState extends State<LegCard> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final leg = widget.leg; final leg = widget.leg;
final isShared = leg.legShareId != null && leg.legShareId!.isNotEmpty;
final distanceUnits = context.watch<DistanceUnitService>();
final routeSegments = _parseRouteSegments(leg.route); final routeSegments = _parseRouteSegments(leg.route);
final textTheme = Theme.of(context).textTheme; final textTheme = Theme.of(context).textTheme;
return Card( return Card(
clipBehavior: Clip.antiAlias,
elevation: 1,
child: Theme(
data: Theme.of(context).copyWith(dividerColor: Colors.transparent),
child: ExpansionTile( child: ExpansionTile(
onExpansionChanged: (v) => setState(() => _expanded = v), onExpansionChanged: (v) => setState(() => _expanded = v),
tilePadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4), tilePadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
@@ -109,12 +116,6 @@ class _LegCardState extends State<LegCard> {
subtitle: LayoutBuilder( subtitle: LayoutBuilder(
builder: (context, constraints) { builder: (context, constraints) {
final isWide = constraints.maxWidth > 520; final isWide = constraints.maxWidth > 520;
final timeWidget = _timeWithDelay(
context,
leg.beginTime,
leg.beginDelayMinutes,
includeDate: widget.showDate,
);
final tractionWrap = !_expanded && leg.locos.isNotEmpty final tractionWrap = !_expanded && leg.locos.isNotEmpty
? Wrap( ? Wrap(
spacing: 8, spacing: 8,
@@ -181,7 +182,7 @@ class _LegCardState extends State<LegCard> {
crossAxisAlignment: CrossAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.end,
children: [ children: [
Text( Text(
'${leg.mileage.toStringAsFixed(1)} mi', distanceUnits.format(leg.mileage, decimals: 1),
style: textTheme.labelLarge?.copyWith( style: textTheme.labelLarge?.copyWith(
fontWeight: FontWeight.w700, fontWeight: FontWeight.w700,
), ),
@@ -197,6 +198,17 @@ class _LegCardState extends State<LegCard> {
], ],
], ],
), ),
if (isShared) ...[
const SizedBox(width: 8),
Tooltip(
message: 'Shared entry',
child: Icon(
Icons.share,
size: 18,
color: Theme.of(context).colorScheme.primary,
),
),
],
if (widget.showEditButton) ...[ if (widget.showEditButton) ...[
const SizedBox(width: 8), const SizedBox(width: 8),
IconButton( IconButton(
@@ -260,6 +272,7 @@ class _LegCardState extends State<LegCard> {
), ),
], ],
), ),
),
); );
} }

View File

@@ -294,6 +294,7 @@ class _RegisterPanelContentState extends State<RegisterPanelContent> {
final _passwordController = TextEditingController(); final _passwordController = TextEditingController();
final _inviteController = TextEditingController(); final _inviteController = TextEditingController();
bool _registering = false; bool _registering = false;
String? _usernameError;
@override @override
void dispose() { void dispose() {
@@ -306,10 +307,21 @@ class _RegisterPanelContentState extends State<RegisterPanelContent> {
} }
Future<void> _register() async { Future<void> _register() async {
final username = _usernameController.text.trim();
if (username.contains(' ') || username.contains('@')) {
setState(() {
_usernameError = 'Username cannot contain spaces or @';
});
return;
} else {
setState(() {
_usernameError = null;
});
}
setState(() => _registering = true); setState(() => _registering = true);
try { try {
await widget.authService.register( await widget.authService.register(
username: _usernameController.text.trim(), username: username,
email: _emailController.text.trim(), email: _emailController.text.trim(),
fullName: _displayNameController.text.trim(), fullName: _displayNameController.text.trim(),
password: _passwordController.text, password: _passwordController.text,
@@ -363,6 +375,21 @@ class _RegisterPanelContentState extends State<RegisterPanelContent> {
border: OutlineInputBorder(), border: OutlineInputBorder(),
labelText: "Username", labelText: "Username",
), ),
onChanged: (_) {
if (_usernameError != null &&
!_usernameController.text.contains(' ') &&
!_usernameController.text.contains('@')) {
setState(() => _usernameError = null);
}
},
),
if (_usernameError != null)
Padding(
padding: const EdgeInsets.only(top: 4.0),
child: Text(
_usernameError!,
style: TextStyle(color: Theme.of(context).colorScheme.error),
),
), ),
const SizedBox(height: 8), const SizedBox(height: 8),
TextField( TextField(

View File

@@ -0,0 +1,705 @@
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:mileograph_flutter/objects/objects.dart';
import 'package:mileograph_flutter/services/data_service.dart';
import 'package:provider/provider.dart';
class BadgesPage extends StatefulWidget {
const BadgesPage({super.key});
@override
State<BadgesPage> createState() => _BadgesPageState();
}
class _BadgesPageState extends State<BadgesPage> {
bool _initialised = false;
final Map<String, bool> _groupExpanded = {};
bool _loadingAwards = false;
bool _loadingClassProgress = false;
bool _loadingLocoProgress = false;
@override
void didChangeDependencies() {
super.didChangeDependencies();
if (_initialised) return;
_initialised = true;
_refreshAwards();
}
Future<void> _refreshAwards() {
_loadingAwards = false;
_loadingClassProgress = false;
_loadingLocoProgress = false;
final data = context.read<DataService>();
return Future.wait([
data.fetchBadgeAwards(limit: 20, badgeCode: 'class_clearance'),
data.fetchClassClearanceProgress(),
data.fetchLocoClearanceProgress(),
]);
}
@override
Widget build(BuildContext context) {
final data = context.watch<DataService>();
final awards = data.badgeAwards;
final loading = data.isBadgeAwardsLoading;
final classProgress = data.classClearanceProgress;
final classProgressLoading =
data.isClassClearanceProgressLoading || _loadingClassProgress;
final locoProgress = data.locoClearanceProgress;
final locoProgressLoading =
data.isLocoClearanceProgressLoading || _loadingLocoProgress;
final hasAnyData =
awards.isNotEmpty || classProgress.isNotEmpty || locoProgress.isNotEmpty;
return Scaffold(
appBar: AppBar(
title: const Text('Badges'),
leading: IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () {
final navigator = Navigator.of(context);
if (navigator.canPop()) {
navigator.pop();
} else {
context.go('/');
}
},
),
),
body: RefreshIndicator(
onRefresh: _refreshAwards,
child: ListView(
padding: const EdgeInsets.all(16),
children: [
if ((loading || classProgressLoading || locoProgressLoading) &&
!hasAnyData)
const Center(
child: Padding(
padding: EdgeInsets.symmetric(vertical: 24.0),
child: CircularProgressIndicator(),
),
)
else if (!hasAnyData)
const Padding(
padding: EdgeInsets.symmetric(vertical: 12.0),
child: Text('No badges awarded yet.'),
)
else
..._buildGroupedAwards(
context,
awards,
classProgress,
locoProgress,
classProgressLoading,
locoProgressLoading,
data.classClearanceHasMore,
data.locoClearanceHasMore,
data.badgeAwardsHasMore,
loading,
),
],
),
),
);
}
List<Widget> _buildGroupedAwards(
BuildContext context,
List<BadgeAward> awards,
List<ClassClearanceProgress> classProgress,
List<LocoClearanceProgress> locoProgress,
bool classProgressLoading,
bool locoProgressLoading,
bool classProgressHasMore,
bool locoProgressHasMore,
bool badgeAwardsHasMore,
bool badgeAwardsLoading,
) {
final grouped = _groupAwards(awards);
if ((classProgress.isNotEmpty || classProgressLoading) &&
!grouped.containsKey('class_clearance')) {
grouped['class_clearance'] = [];
}
if ((locoProgress.isNotEmpty || locoProgressLoading) &&
!grouped.containsKey('loco_clearance')) {
grouped['loco_clearance'] = [];
}
final codes = _orderedBadgeCodes(grouped.keys.toList());
return codes.map((code) {
final items = grouped[code]!;
final expanded = _groupExpanded[code] ?? true;
final title = _formatBadgeName(code);
final isClass = code == 'class_clearance';
final isLoco = code == 'loco_clearance';
final classItems = isClass ? classProgress : <ClassClearanceProgress>[];
final locoItems = isLoco ? locoProgress : <LocoClearanceProgress>[];
final awardCount = isLoco
? locoItems.where((item) => item.awardedTiers.isNotEmpty).length
: items.length;
final isLoadingSection = isClass
? (classProgressLoading || badgeAwardsLoading || _loadingAwards)
: (isLoco ? locoProgressLoading : false);
final children = <Widget>[];
if (isClass && items.isNotEmpty) {
children.add(_buildSubheading(context, 'Awarded'));
children.addAll(
items.map(
(award) => Padding(
padding:
const EdgeInsets.symmetric(horizontal: 12.0, vertical: 4.0),
child: _buildAwardCard(context, award, compact: true),
),
),
);
if (badgeAwardsHasMore || badgeAwardsLoading || _loadingAwards) {
children.add(
Padding(
padding: const EdgeInsets.only(top: 4.0, bottom: 8.0),
child: _buildLoadMoreButton(
context,
badgeAwardsLoading || _loadingAwards,
() => _loadMoreAwards(),
),
),
);
}
} else if (!isClass && !isLoco && items.isNotEmpty) {
children.add(_buildSubheading(context, 'Awarded'));
children.addAll(
items.map(
(award) => Padding(
padding:
const EdgeInsets.symmetric(horizontal: 12.0, vertical: 4.0),
child: _buildAwardCard(context, award, compact: true),
),
),
);
}
if (isClass) {
children.addAll(
_buildClassProgressSection(
context,
classItems,
classProgressLoading,
classProgressHasMore,
),
);
}
if (isLoco) {
children.addAll(
_buildLocoProgressSection(
context,
locoItems,
locoProgressLoading,
locoProgressHasMore,
showHeading: false,
),
);
}
if (children.isEmpty && !isLoadingSection) {
children.add(
const Padding(
padding: EdgeInsets.symmetric(vertical: 6.0),
child: Text('No awards'),
),
);
}
return Card(
margin: const EdgeInsets.symmetric(vertical: 4.0),
child: ExpansionTile(
key: ValueKey(code),
tilePadding: const EdgeInsets.symmetric(horizontal: 12.0),
title: Row(
children: [
Expanded(child: Text(title)),
if (isLoadingSection) ...[
const SizedBox(width: 8),
const SizedBox(
height: 18,
width: 18,
child: CircularProgressIndicator(strokeWidth: 2),
),
],
const SizedBox(width: 8),
_buildCountChip(context, awardCount),
],
),
initiallyExpanded: expanded,
onExpansionChanged: (isOpen) {
setState(() => _groupExpanded[code] = isOpen);
},
children: children,
),
);
}).toList();
}
Map<String, List<BadgeAward>> _groupAwards(List<BadgeAward> awards) {
final Map<String, List<BadgeAward>> grouped = {};
for (final award in awards) {
final code = award.badgeCode.toLowerCase();
grouped.putIfAbsent(code, () => []).add(award);
}
return grouped;
}
Widget _buildAwardCard(
BuildContext context,
BadgeAward award, {
bool compact = false,
}) {
final badgeName = _formatBadgeName(award.badgeCode);
final tier = award.badgeTier.isNotEmpty
? award.badgeTier[0].toUpperCase() + award.badgeTier.substring(1)
: '';
final tierIcon = _buildTierIcon(award.badgeTier);
final scope = _scopeToShow(award);
final content = Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
if (tierIcon != null) ...[
tierIcon,
const SizedBox(width: 8),
],
Expanded(
child: Text(
'$badgeName$tier',
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
),
if (award.awardedAt != null)
Text(
_formatAwardDate(award.awardedAt!),
style: Theme.of(context).textTheme.bodySmall,
),
],
),
if (scope != null && scope.isNotEmpty) ...[
const SizedBox(height: 4),
Text(
scope,
style: Theme.of(context).textTheme.bodyMedium,
),
],
if (award.loco != null) ...[
const SizedBox(height: 6),
_buildLocoInfo(context, award.loco!),
],
],
);
if (compact) {
return content;
}
return Card(
child: Padding(
padding: const EdgeInsets.all(10.0),
child: content,
),
);
}
Widget _buildLocoInfo(BuildContext context, LocoSummary loco) {
final lines = <String>[];
final classNum = [
if (loco.locoClass.isNotEmpty) loco.locoClass,
if (loco.number.isNotEmpty) loco.number,
].join(' ');
if (classNum.isNotEmpty) lines.add(classNum);
if ((loco.name ?? '').isNotEmpty) lines.add(loco.name!);
if ((loco.livery ?? '').isNotEmpty) lines.add(loco.livery!);
if ((loco.location ?? '').isNotEmpty) lines.add(loco.location!);
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Icon(Icons.train, size: 20),
const SizedBox(width: 8),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: lines.map((line) {
return Text(
line,
style: Theme.of(context).textTheme.bodyMedium,
);
}).toList(),
),
),
],
);
}
String _formatBadgeName(String code) {
if (code.isEmpty) return 'Badge';
const known = {
'class_clearance': 'Class Clearance',
'loco_clearance': 'Loco Clearance',
};
final lower = code.toLowerCase();
if (known.containsKey(lower)) return known[lower]!;
final parts = code.split(RegExp(r'[_\\s]+')).where((p) => p.isNotEmpty);
return parts
.map((p) => p[0].toUpperCase() + p.substring(1).toLowerCase())
.join(' ');
}
List<String> _orderedBadgeCodes(List<String> codes) {
final lowerCodes = codes.map((c) => c.toLowerCase()).toSet();
final ordered = <String>[];
for (final code in ['loco_clearance', 'class_clearance']) {
if (lowerCodes.remove(code)) ordered.add(code);
}
final remaining = lowerCodes.toList()
..sort((a, b) => _formatBadgeName(a).compareTo(_formatBadgeName(b)));
ordered.addAll(remaining);
return ordered;
}
Widget _buildSubheading(BuildContext context, String label) {
return Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 4),
child: Text(
label,
style: Theme.of(context)
.textTheme
.labelMedium
?.copyWith(fontWeight: FontWeight.w700),
),
);
}
List<Widget> _buildClassProgressSection(
BuildContext context,
List<ClassClearanceProgress> progress,
bool isLoading,
bool hasMore,
) {
if (progress.isEmpty && !isLoading && !hasMore) return const [];
return [
_buildSubheading(context, 'In Progress'),
...progress.map(
(item) => Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 6.0),
child: _buildClassProgressCard(context, item),
),
),
if (hasMore || isLoading)
Padding(
padding: const EdgeInsets.only(top: 4.0, bottom: 8.0),
child: _buildLoadMoreButton(
context,
isLoading,
() => _loadMoreClassProgress(),
),
),
if (progress.isNotEmpty) const SizedBox(height: 4),
];
}
List<Widget> _buildLocoProgressSection(
BuildContext context,
List<LocoClearanceProgress> progress,
bool isLoading,
bool hasMore,
{bool showHeading = true}
) {
if (progress.isEmpty && !isLoading && !hasMore) return const [];
return [
if (showHeading) _buildSubheading(context, 'In Progress'),
if (progress.isEmpty && isLoading)
Padding(
padding: const EdgeInsets.symmetric(vertical: 12.0),
child: _buildLoadingIndicator(),
),
...progress.map(
(item) => Padding(
padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 6.0),
child: _buildLocoProgressCard(context, item),
),
),
if (hasMore || isLoading)
Padding(
padding: const EdgeInsets.only(top: 4.0, bottom: 8.0),
child: _buildLoadMoreButton(
context,
isLoading,
() => _loadMoreLocoProgress(),
),
),
if (progress.isNotEmpty) const SizedBox(height: 4),
];
}
Widget _buildClassProgressCard(
BuildContext context,
ClassClearanceProgress progress,
) {
final pct = progress.percentComplete.clamp(0, 100);
return Card(
margin: const EdgeInsets.symmetric(vertical: 4.0),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Expanded(
child: Text(
progress.className,
style: Theme.of(context).textTheme.bodyMedium,
),
),
Text(
'${pct.toStringAsFixed(0)}%',
style: Theme.of(context).textTheme.labelMedium,
),
],
),
const SizedBox(height: 4),
LinearProgressIndicator(
value: progress.total == 0 ? 0 : pct / 100,
minHeight: 6,
),
if (progress.total > 0)
Padding(
padding: const EdgeInsets.only(top: 2.0),
child: Text(
'${progress.completed}/${progress.total}',
style: Theme.of(context)
.textTheme
.labelSmall
?.copyWith(color: Theme.of(context).hintColor),
),
),
],
),
),
);
}
Widget _buildLocoProgressCard(
BuildContext context,
LocoClearanceProgress progress,
) {
final tierIcons = progress.awardedTiers
.map((tier) => _buildTierIcon(tier, size: 18))
.whereType<Widget>()
.toList();
final reachedTopTier = progress.nextTier.isEmpty;
final pct = progress.percent.clamp(0, 100);
final nextTier = progress.nextTier.isNotEmpty
? progress.nextTier[0].toUpperCase() + progress.nextTier.substring(1)
: 'Next';
final loco = progress.loco;
final title = [
if (loco.number.isNotEmpty) loco.number,
if (loco.locoClass.isNotEmpty) loco.locoClass,
].join('');
return Card(
margin: const EdgeInsets.symmetric(vertical: 4.0),
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Expanded(
child: Text(
title.isNotEmpty ? title : 'Loco',
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
),
if (tierIcons.isNotEmpty)
Row(
children: tierIcons
.expand((icon) sync* {
yield icon;
yield const SizedBox(width: 4);
})
.toList()
..removeLast(),
),
],
),
if ((loco.name ?? '').isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 2.0),
child: Text(
loco.name ?? '',
style: Theme.of(context).textTheme.bodySmall,
),
),
if (!reachedTopTier) ...[
const SizedBox(height: 4),
LinearProgressIndicator(
value: progress.required == 0 ? 0 : pct / 100,
minHeight: 6,
),
Padding(
padding: const EdgeInsets.only(top: 2.0),
child: Text(
'${pct.toStringAsFixed(0)}% to $nextTier award',
style: Theme.of(context).textTheme.bodyMedium,
),
),
],
],
),
),
);
}
Widget _buildLoadMoreButton(
BuildContext context,
bool isLoading,
Future<void> Function() onPressed,
) {
return Align(
alignment: Alignment.center,
child: OutlinedButton.icon(
onPressed: isLoading
? null
: () {
onPressed();
},
icon: isLoading
? const SizedBox(
height: 18,
width: 18,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.expand_more),
label: Text(isLoading ? 'Loading...' : 'Load more'),
),
);
}
Widget _buildLoadingIndicator() {
return const Center(
child: SizedBox(
height: 24,
width: 24,
child: CircularProgressIndicator(strokeWidth: 2),
),
);
}
Widget _buildCountChip(BuildContext context, int count) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(999),
),
child: Text(
'$count',
style: Theme.of(context)
.textTheme
.labelMedium
?.copyWith(fontWeight: FontWeight.w700),
),
);
}
Future<void> _loadMoreClassProgress() {
final data = context.read<DataService>();
if (data.isClassClearanceProgressLoading || _loadingClassProgress) {
return Future.value();
}
setState(() => _loadingClassProgress = true);
return data
.fetchClassClearanceProgress(
offset: data.classClearanceProgress.length,
append: true,
)
.whenComplete(() {
if (mounted) setState(() => _loadingClassProgress = false);
});
}
Future<void> _loadMoreLocoProgress() {
final data = context.read<DataService>();
if (data.isLocoClearanceProgressLoading || _loadingLocoProgress) {
return Future.value();
}
setState(() => _loadingLocoProgress = true);
return data
.fetchLocoClearanceProgress(
offset: data.locoClearanceProgress.length,
append: true,
)
.whenComplete(() {
if (mounted) setState(() => _loadingLocoProgress = false);
});
}
Future<void> _loadMoreAwards() {
final data = context.read<DataService>();
if (data.isBadgeAwardsLoading || _loadingAwards) return Future.value();
setState(() => _loadingAwards = true);
return data
.fetchBadgeAwards(
offset: data.badgeAwards.length,
append: true,
badgeCode: 'class_clearance',
limit: 20,
)
.whenComplete(() {
if (mounted) setState(() => _loadingAwards = false);
});
}
String _formatAwardDate(DateTime date) {
final y = date.year.toString().padLeft(4, '0');
final m = date.month.toString().padLeft(2, '0');
final d = date.day.toString().padLeft(2, '0');
return '$y-$m-$d';
}
Widget? _buildTierIcon(String tier, {double size = 24}) {
final lower = tier.toLowerCase();
Color? color;
switch (lower) {
case 'bronze':
color = const Color(0xFFCD7F32);
break;
case 'silver':
color = const Color(0xFFC0C0C0);
break;
case 'gold':
color = const Color(0xFFFFD700);
break;
}
if (color == null) return null;
return Icon(Icons.emoji_events, color: color, size: size);
}
String? _scopeToShow(BadgeAward award) {
final scope = award.scopeValue?.trim() ?? '';
if (scope.isEmpty) return null;
final code = award.badgeCode.toLowerCase();
if (code == 'loco_clearance') {
// Hide numeric loco IDs; loco details are shown separately.
if (int.tryParse(scope) != null) return null;
}
return scope;
}
}

View File

@@ -7,6 +7,7 @@ import 'package:mileograph_flutter/components/dashboard/top_traction_panel.dart'
import 'package:mileograph_flutter/objects/objects.dart'; import 'package:mileograph_flutter/objects/objects.dart';
import 'package:mileograph_flutter/services/authservice.dart'; import 'package:mileograph_flutter/services/authservice.dart';
import 'package:mileograph_flutter/services/data_service.dart'; import 'package:mileograph_flutter/services/data_service.dart';
import 'package:mileograph_flutter/services/distance_unit_service.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
class Dashboard extends StatefulWidget { class Dashboard extends StatefulWidget {
@@ -23,9 +24,10 @@ class _DashboardState extends State<Dashboard> {
Widget build(BuildContext context) { Widget build(BuildContext context) {
final data = context.watch<DataService>(); final data = context.watch<DataService>();
final auth = context.watch<AuthService>(); final auth = context.watch<AuthService>();
final distanceUnits = context.watch<DistanceUnitService>();
final stats = data.homepageStats; final stats = data.homepageStats;
final isInitialLoading = data.isHomepageLoading || stats == null; final isInitialLoading = data.isHomepageLoading && stats == null;
return RefreshIndicator( return RefreshIndicator(
onRefresh: () async { onRefresh: () async {
@@ -46,9 +48,15 @@ class _DashboardState extends State<Dashboard> {
ListView( ListView(
padding: const EdgeInsets.all(16), padding: const EdgeInsets.all(16),
children: [ children: [
_buildHero(context, auth, data, stats), _buildHero(context, auth, data, stats, distanceUnits),
const SizedBox(height: spacing), const SizedBox(height: spacing),
_buildTiles(context, data, maxWidth, spacing), _buildTiles(
context,
data,
distanceUnits,
maxWidth,
spacing,
),
], ],
), ),
if (isInitialLoading) if (isInitialLoading)
@@ -81,6 +89,7 @@ class _DashboardState extends State<Dashboard> {
AuthService auth, AuthService auth,
DataService data, DataService data,
HomepageStats? stats, HomepageStats? stats,
DistanceUnitService distanceUnits,
) { ) {
final colorScheme = Theme.of(context).colorScheme; final colorScheme = Theme.of(context).colorScheme;
final greetingName = final greetingName =
@@ -119,14 +128,14 @@ class _DashboardState extends State<Dashboard> {
_metricTile( _metricTile(
context, context,
label: 'Total mileage', label: 'Total mileage',
value: '${totalMileage.toStringAsFixed(1)} mi', value: distanceUnits.format(totalMileage, decimals: 1),
icon: Icons.route, icon: Icons.route,
color: colorScheme.onPrimaryContainer, color: colorScheme.onPrimaryContainer,
), ),
_metricTile( _metricTile(
context, context,
label: 'This year', label: 'This year',
value: '${currentYearMileage.toStringAsFixed(1)} mi', value: distanceUnits.format(currentYearMileage, decimals: 1),
icon: Icons.calendar_today, icon: Icons.calendar_today,
color: colorScheme.onPrimaryContainer, color: colorScheme.onPrimaryContainer,
), ),
@@ -215,6 +224,7 @@ class _DashboardState extends State<Dashboard> {
Widget _buildTiles( Widget _buildTiles(
BuildContext context, BuildContext context,
DataService data, DataService data,
DistanceUnitService distanceUnits,
double maxWidth, double maxWidth,
double spacing, double spacing,
) { ) {
@@ -229,9 +239,9 @@ class _DashboardState extends State<Dashboard> {
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ children: [
_buildOnThisDayCard(context, data), _buildOnThisDayCard(context, data, distanceUnits),
const SizedBox(height: 16), const SizedBox(height: 16),
_buildTripsCard(context, data), _buildTripsCard(context, data, distanceUnits),
const SizedBox(height: 16), const SizedBox(height: 16),
const LatestLocoChangesPanel(expanded: true), const LatestLocoChangesPanel(expanded: true),
], ],
@@ -256,13 +266,13 @@ class _DashboardState extends State<Dashboard> {
return Column( return Column(
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ children: [
_buildOnThisDayCard(context, data), _buildOnThisDayCard(context, data, distanceUnits),
const SizedBox(height: 16), const SizedBox(height: 16),
const TopTractionPanel(), const TopTractionPanel(),
const SizedBox(height: 16), const SizedBox(height: 16),
const LeaderboardPanel(), const LeaderboardPanel(),
const SizedBox(height: 16), const SizedBox(height: 16),
_buildTripsCard(context, data), _buildTripsCard(context, data, distanceUnits),
const SizedBox(height: 16), const SizedBox(height: 16),
const LatestLocoChangesPanel(), const LatestLocoChangesPanel(),
], ],
@@ -296,7 +306,8 @@ class _DashboardState extends State<Dashboard> {
); );
} }
Widget _buildOnThisDayCard(BuildContext context, DataService data) { Widget _buildOnThisDayCard(
BuildContext context, DataService data, DistanceUnitService distanceUnits) {
final filtered = data.onThisDay final filtered = data.onThisDay
.where((leg) => leg.beginTime.year != DateTime.now().year) .where((leg) => leg.beginTime.year != DateTime.now().year)
.toList(); .toList();
@@ -329,7 +340,7 @@ class _DashboardState extends State<Dashboard> {
: Column( : Column(
children: [ children: [
for (int idx = 0; idx < visible.length; idx++) ...[ for (int idx = 0; idx < visible.length; idx++) ...[
_otdRow(context, visible[idx], textTheme), _otdRow(context, visible[idx], textTheme, distanceUnits),
if (idx != visible.length - 1) const Divider(height: 12), if (idx != visible.length - 1) const Divider(height: 12),
], ],
], ],
@@ -337,7 +348,8 @@ class _DashboardState extends State<Dashboard> {
); );
} }
Widget _otdRow(BuildContext context, Leg leg, TextTheme textTheme) { Widget _otdRow(BuildContext context, Leg leg, TextTheme textTheme,
DistanceUnitService distanceUnits) {
final traction = leg.locos; final traction = leg.locos;
return Row( return Row(
crossAxisAlignment: CrossAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center,
@@ -443,7 +455,7 @@ class _DashboardState extends State<Dashboard> {
crossAxisAlignment: CrossAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.end,
children: [ children: [
Text( Text(
'${leg.mileage.toStringAsFixed(1)} mi', distanceUnits.format(leg.mileage, decimals: 1),
style: textTheme.labelLarge?.copyWith( style: textTheme.labelLarge?.copyWith(
fontWeight: FontWeight.w800, fontWeight: FontWeight.w800,
), ),
@@ -498,11 +510,12 @@ class _DashboardState extends State<Dashboard> {
); );
} }
Widget _buildTripsCard(BuildContext context, DataService data) { Widget _buildTripsCard(
BuildContext context, DataService data, DistanceUnitService distanceUnits) {
final tripsUnsorted = data.trips; final tripsUnsorted = data.trips;
List trips = []; List<TripSummary> trips = [];
if (tripsUnsorted.isNotEmpty) { if (tripsUnsorted.isNotEmpty) {
trips = [...tripsUnsorted]..sort((a, b) => b.tripId.compareTo(a.tripId)); trips = [...tripsUnsorted]..sort(TripSummary.compareByDateDesc);
} }
return _panel( return _panel(
context, context,
@@ -543,7 +556,7 @@ class _DashboardState extends State<Dashboard> {
?.copyWith(fontWeight: FontWeight.w700), ?.copyWith(fontWeight: FontWeight.w700),
), ),
Text( Text(
'${trip.tripMileage.toStringAsFixed(1)} mi', distanceUnits.format(trip.tripMileage, decimals: 1),
style: Theme.of(context).textTheme.labelMedium, style: Theme.of(context).textTheme.labelMedium,
), ),
], ],

View File

@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:mileograph_flutter/components/legs/leg_card.dart'; import 'package:mileograph_flutter/components/legs/leg_card.dart';
import 'package:mileograph_flutter/objects/objects.dart'; import 'package:mileograph_flutter/objects/objects.dart';
import 'package:mileograph_flutter/services/data_service.dart'; import 'package:mileograph_flutter/services/data_service.dart';
import 'package:mileograph_flutter/services/distance_unit_service.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
class LegsPage extends StatefulWidget { class LegsPage extends StatefulWidget {
@@ -90,6 +91,7 @@ class _LegsPageState extends State<LegsPage> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final data = context.watch<DataService>(); final data = context.watch<DataService>();
final distanceUnits = context.watch<DistanceUnitService>();
final legs = data.legs; final legs = data.legs;
final pageMileage = _pageMileage(legs); final pageMileage = _pageMileage(legs);
@@ -121,7 +123,7 @@ class _LegsPageState extends State<LegsPage> {
children: [ children: [
Text('Page mileage', Text('Page mileage',
style: Theme.of(context).textTheme.labelSmall), style: Theme.of(context).textTheme.labelSmall),
Text('${pageMileage.toStringAsFixed(1)} mi', Text(distanceUnits.format(pageMileage, decimals: 1),
style: Theme.of(context) style: Theme.of(context)
.textTheme .textTheme
.titleMedium .titleMedium
@@ -212,7 +214,7 @@ class _LegsPageState extends State<LegsPage> {
else else
Column( Column(
children: [ children: [
..._buildLegsWithDividers(context, legs), ..._buildLegsWithDividers(context, legs, distanceUnits),
const SizedBox(height: 8), const SizedBox(height: 8),
if (data.legsHasMore || data.isLegsLoading) if (data.legsHasMore || data.isLegsLoading)
Align( Align(
@@ -239,7 +241,11 @@ class _LegsPageState extends State<LegsPage> {
); );
} }
List<Widget> _buildLegsWithDividers(BuildContext context, List<Leg> legs) { List<Widget> _buildLegsWithDividers(
BuildContext context,
List<Leg> legs,
DistanceUnitService distanceUnits,
) {
final widgets = <Widget>[]; final widgets = <Widget>[];
String? currentDate; String? currentDate;
double dayMileage = 0; double dayMileage = 0;
@@ -261,10 +267,8 @@ class _LegsPageState extends State<LegsPage> {
), ),
), ),
), ),
Text( Text(distanceUnits.format(dayMileage, decimals: 1),
'${dayMileage.toStringAsFixed(1)} mi', style: Theme.of(context).textTheme.labelMedium),
style: Theme.of(context).textTheme.labelMedium,
),
], ],
), ),
), ),

View File

@@ -1,81 +1,13 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:mileograph_flutter/components/pages/profile.dart'; import 'package:mileograph_flutter/components/pages/more/more_home_page.dart';
import 'package:mileograph_flutter/components/pages/settings.dart';
import 'package:mileograph_flutter/components/pages/stats.dart'; export 'more/admin_page.dart';
class MorePage extends StatelessWidget { class MorePage extends StatelessWidget {
const MorePage({super.key}); const MorePage({super.key});
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Navigator( return const MoreHomePage();
onGenerateRoute: (settings) {
final name = settings.name ?? '/';
Widget page;
switch (name) {
case '/settings':
page = const SettingsPage();
break;
case '/profile':
page = const ProfilePage();
break;
case '/stats':
page = const StatsPage();
break;
case '/more/settings':
page = const SettingsPage();
break;
case '/more/profile':
page = const ProfilePage();
break;
case '/more/stats':
page = const StatsPage();
break;
case '/':
default:
page = _MoreHome();
}
return MaterialPageRoute(builder: (_) => page, settings: settings);
},
);
}
}
class _MoreHome extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ListView(
padding: const EdgeInsets.all(16),
children: [
Text(
'More',
style: Theme.of(context).textTheme.headlineSmall,
),
const SizedBox(height: 12),
Card(
child: Column(
children: [
ListTile(
leading: const Icon(Icons.emoji_events),
title: const Text('Badges'),
onTap: () => Navigator.of(context).pushNamed('/more/profile'),
),
const Divider(height: 1),
ListTile(
leading: const Icon(Icons.bar_chart),
title: const Text('Stats'),
onTap: () => Navigator.of(context).pushNamed('/more/stats'),
),
const Divider(height: 1),
ListTile(
leading: const Icon(Icons.settings),
title: const Text('Settings'),
onTap: () => Navigator.of(context).pushNamed('/more/settings'),
),
],
),
),
],
);
} }
} }

View File

@@ -0,0 +1,476 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:mileograph_flutter/objects/objects.dart';
import 'package:mileograph_flutter/services/api_service.dart';
import 'package:mileograph_flutter/services/authservice.dart';
class AdminPage extends StatefulWidget {
const AdminPage({super.key});
@override
State<AdminPage> createState() => _AdminPageState();
}
class _AdminPageState extends State<AdminPage> {
final TextEditingController _titleController = TextEditingController();
final TextEditingController _bodyController = TextEditingController();
final List<UserSummary> _selectedUsers = [];
List<UserSummary> _userOptions = [];
List<String> _channels = [];
String? _selectedChannel;
String? _channelError;
bool _loadingChannels = false;
String? _userError;
bool _sending = false;
@override
void initState() {
super.initState();
_loadChannels();
}
@override
void dispose() {
_titleController.dispose();
_bodyController.dispose();
super.dispose();
}
Future<void> _loadChannels() async {
setState(() {
_loadingChannels = true;
_channelError = null;
});
try {
final api = context.read<ApiService>();
final json = await api.get('/notifications/channels');
List<dynamic>? list;
if (json is List) {
list = json;
} else if (json is Map) {
for (final key in ['channels', 'data']) {
final value = json[key];
if (value is List) {
list = value;
break;
}
}
}
final parsed =
list?.map((e) => e.toString()).where((e) => e.isNotEmpty).toList() ??
const [];
setState(() {
_channels = parsed;
_selectedChannel = parsed.isNotEmpty ? parsed.first : null;
});
} catch (e) {
setState(() {
_channelError = 'Failed to load channels';
});
} finally {
if (mounted) setState(() => _loadingChannels = false);
}
}
Future<List<UserSummary>> _fetchUserSuggestions(
ApiService api,
String query,
) async {
final encoded = Uri.encodeComponent(query);
final candidates = [
'/users/search?q=$encoded',
'/users/search?query=$encoded',
'/users?search=$encoded',
];
for (final path in candidates) {
try {
final json = await api.get(path);
List<dynamic>? list;
if (json is List) {
list = json;
} else if (json is Map) {
for (final key in ['users', 'data', 'results', 'items']) {
final value = json[key];
if (value is List) {
list = value;
break;
}
}
}
if (list != null) {
return list
.whereType<Map>()
.map((e) => UserSummary.fromJson(
e.map((k, v) => MapEntry(k.toString(), v)),
))
.toList();
}
} catch (_) {
// Try next endpoint
}
}
return const [];
}
void _removeUser(UserSummary user) {
setState(() {
_selectedUsers.removeWhere((u) => u.userId == user.userId);
});
}
Future<void> _openUserPicker() async {
final api = context.read<ApiService>();
var tempSelected = List<UserSummary>.from(_selectedUsers);
var options = List<UserSummary>.from(_userOptions);
String query = '';
bool loading = false;
String? error = _userError;
Future<void> runSearch(String q, void Function(void Function()) setModalState) async {
setModalState(() {
query = q;
loading = true;
error = null;
});
try {
final results = await _fetchUserSuggestions(api, q);
setModalState(() {
options = results;
loading = false;
error = null;
});
if (mounted) {
setState(() {
_userOptions = results;
_userError = null;
});
}
} catch (e) {
setModalState(() {
loading = false;
error = 'Failed to search users';
});
if (mounted) {
setState(() {
_userError = 'Failed to search users';
});
}
}
}
var initialFetchTriggered = false;
await showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
builder: (ctx) {
return StatefulBuilder(
builder: (ctx, setModalState) {
if (!initialFetchTriggered && !loading && options.isEmpty) {
initialFetchTriggered = true;
WidgetsBinding.instance.addPostFrameCallback(
(_) => runSearch('', setModalState),
);
}
final lowerQuery = query.toLowerCase();
final filtered = lowerQuery.isEmpty
? options
: options.where((u) {
return u.displayName.toLowerCase().contains(lowerQuery) ||
u.username.toLowerCase().contains(lowerQuery) ||
u.email.toLowerCase().contains(lowerQuery);
}).toList();
return SafeArea(
child: Padding(
padding: EdgeInsets.only(
left: 16,
right: 16,
top: 16,
bottom: MediaQuery.of(ctx).viewInsets.bottom + 16,
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Text(
'Select recipients',
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
const Spacer(),
TextButton(
onPressed: () {
setModalState(() {
tempSelected.clear();
});
setState(() => _selectedUsers.clear());
},
child: const Text('Clear'),
),
],
),
const SizedBox(height: 8),
TextField(
decoration: const InputDecoration(
labelText: 'Search users',
border: OutlineInputBorder(),
),
onChanged: (val) => runSearch(val, setModalState),
),
if (loading)
const Padding(
padding: EdgeInsets.only(top: 8.0),
child: LinearProgressIndicator(minHeight: 2),
),
if (error != null)
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Text(
error!,
style:
TextStyle(color: Theme.of(context).colorScheme.error),
),
),
const SizedBox(height: 12),
SizedBox(
height: 340,
child: filtered.isEmpty
? const Center(child: Text('No users yet.'))
: ListView.builder(
itemCount: filtered.length,
itemBuilder: (_, index) {
final user = filtered[index];
final selected =
tempSelected.any((u) => u.userId == user.userId);
return CheckboxListTile(
value: selected,
title: Text(user.displayName),
subtitle: user.email.isNotEmpty
? Text(user.email)
: (user.username.isNotEmpty
? Text(user.username)
: null),
onChanged: (val) {
setModalState(() {
if (val == true) {
if (!tempSelected
.any((u) => u.userId == user.userId)) {
tempSelected.add(user);
}
} else {
tempSelected.removeWhere(
(u) => u.userId == user.userId);
}
});
if (mounted) {
setState(() {
_selectedUsers
..clear()
..addAll(tempSelected);
});
}
},
);
},
),
),
const SizedBox(height: 8),
Align(
alignment: Alignment.centerRight,
child: TextButton(
onPressed: () => Navigator.of(ctx).pop(),
child: const Text('Done'),
),
),
],
),
),
);
},
);
},
);
}
Future<void> _sendNotification() async {
final channel = _selectedChannel;
if (channel == null || channel.isEmpty) {
_showSnack('Select a channel first.');
return;
}
if (_selectedUsers.isEmpty) {
_showSnack('Select at least one user.');
return;
}
final title = _titleController.text.trim();
final body = _bodyController.text.trim();
if (title.isEmpty || body.isEmpty) {
_showSnack('Title and body are required.');
return;
}
setState(() => _sending = true);
try {
final api = context.read<ApiService>();
await api.post('/notifications/new', {
'user_ids': _selectedUsers.map((e) => e.userId).toList(),
'channel': channel,
'title': title,
'body': body,
});
if (!mounted) return;
_showSnack('Notification sent');
setState(() {
_selectedUsers.clear();
_titleController.clear();
_bodyController.clear();
_userOptions.clear();
});
} catch (e) {
_showSnack('Failed to send: $e');
} finally {
if (mounted) setState(() => _sending = false);
}
}
void _showSnack(String message) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message)));
}
@override
Widget build(BuildContext context) {
final isAdmin = context.select<AuthService, bool>((auth) => auth.isElevated);
if (!isAdmin) {
return const Scaffold(
body: Center(child: Text('You do not have access to this page.')),
);
}
return Scaffold(
appBar: AppBar(
title: const Text('Admin'),
),
body: ListView(
padding: const EdgeInsets.all(16),
children: [
Text(
'Send notification',
style: Theme.of(context).textTheme.titleLarge?.copyWith(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 12),
_buildUserPicker(),
const SizedBox(height: 12),
DropdownButtonFormField<String>(
value: _selectedChannel,
decoration: const InputDecoration(
labelText: 'Channel',
border: OutlineInputBorder(),
),
items: _channels
.map(
(c) => DropdownMenuItem(
value: c,
child: Text(c),
),
)
.toList(),
onChanged:
_loadingChannels ? null : (val) => setState(() => _selectedChannel = val),
),
if (_loadingChannels)
const Padding(
padding: EdgeInsets.only(top: 8.0),
child: LinearProgressIndicator(minHeight: 2),
),
if (_channelError != null)
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Text(
_channelError!,
style: TextStyle(color: Theme.of(context).colorScheme.error),
),
),
const SizedBox(height: 12),
TextField(
controller: _titleController,
decoration: const InputDecoration(
labelText: 'Title',
border: OutlineInputBorder(),
),
),
const SizedBox(height: 12),
TextField(
controller: _bodyController,
minLines: 3,
maxLines: 6,
decoration: const InputDecoration(
labelText: 'Body',
border: OutlineInputBorder(),
),
),
const SizedBox(height: 16),
SizedBox(
width: double.infinity,
child: ElevatedButton.icon(
onPressed: _sending ? null : _sendNotification,
icon: _sending
? const SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.send),
label: Text(_sending ? 'Sending...' : 'Send notification'),
),
),
],
),
);
}
Widget _buildUserPicker() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Recipients',
style: Theme.of(context).textTheme.titleMedium,
),
const SizedBox(height: 8),
Wrap(
spacing: 8,
runSpacing: 8,
children: _selectedUsers
.map(
(u) => InputChip(
label: Text(u.displayName),
onDeleted: () => _removeUser(u),
),
)
.toList(),
),
const SizedBox(height: 8),
OutlinedButton.icon(
onPressed: _openUserPicker,
icon: const Icon(Icons.person_search),
label: const Text('Select users'),
),
if (_userError != null)
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Text(
_userError!,
style: TextStyle(color: Theme.of(context).colorScheme.error),
),
),
],
);
}
}

View File

@@ -0,0 +1,59 @@
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:mileograph_flutter/services/authservice.dart';
class MoreHomePage extends StatelessWidget {
const MoreHomePage({super.key});
@override
Widget build(BuildContext context) {
final isAdmin = context.select<AuthService, bool>((auth) => auth.isElevated);
return ListView(
padding: const EdgeInsets.all(16),
children: [
Text(
'More',
style: Theme.of(context).textTheme.headlineSmall,
),
const SizedBox(height: 12),
Card(
child: Column(
children: [
ListTile(
leading: const Icon(Icons.person),
title: const Text('Profile'),
onTap: () => context.go('/more/profile'),
),
const Divider(height: 1),
ListTile(
leading: const Icon(Icons.emoji_events),
title: const Text('Badges'),
onTap: () => context.go('/more/badges'),
),
const Divider(height: 1),
ListTile(
leading: const Icon(Icons.bar_chart),
title: const Text('Stats'),
onTap: () => context.go('/more/stats'),
),
const Divider(height: 1),
ListTile(
leading: const Icon(Icons.settings),
title: const Text('Settings'),
onTap: () => context.go('/more/settings'),
),
if (isAdmin) const Divider(height: 1),
if (isAdmin)
ListTile(
leading: const Icon(Icons.admin_panel_settings),
title: const Text('Admin'),
onTap: () => context.go('/more/admin'),
),
],
),
),
],
);
}
}

View File

@@ -10,7 +10,9 @@ import 'package:mileograph_flutter/components/calculator/calculator.dart';
import 'package:mileograph_flutter/components/pages/traction.dart'; import 'package:mileograph_flutter/components/pages/traction.dart';
import 'package:mileograph_flutter/objects/objects.dart'; import 'package:mileograph_flutter/objects/objects.dart';
import 'package:mileograph_flutter/services/api_service.dart'; import 'package:mileograph_flutter/services/api_service.dart';
import 'package:mileograph_flutter/services/authservice.dart';
import 'package:mileograph_flutter/services/data_service.dart'; import 'package:mileograph_flutter/services/data_service.dart';
import 'package:mileograph_flutter/services/distance_unit_service.dart';
import 'package:mileograph_flutter/services/navigation_guard.dart'; import 'package:mileograph_flutter/services/navigation_guard.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';

View File

@@ -4,14 +4,24 @@ extension _NewEntryDraftLogic on _NewEntryPageState {
Future<bool> _handleExitIntent() async { Future<bool> _handleExitIntent() async {
if (!mounted) return false; if (!mounted) return false;
if (_isEditing) return true; if (_isEditing) return true;
if (_activeLegShare != null) return true;
if (_formIsEmpty()) return true; if (_formIsEmpty()) return true;
if (_activeDraftId != null && !_draftChangedFromBaseline()) { if (_activeDraftId != null && !_draftChangedFromBaseline()) {
return true; return true;
} }
final currentSnapshot = _currentSubmissionSnapshot();
if (_lastSubmittedSnapshot != null &&
_snapshotEquality.equals(_lastSubmittedSnapshot, currentSnapshot)) {
return true;
}
final choice = await _promptSaveDraft(); final choice = await _promptSaveDraft();
if (choice == _ExitChoice.cancel) return false; if (choice == _ExitChoice.cancel) return false;
if (choice == _ExitChoice.save) { if (choice == _ExitChoice.save) {
try {
await _saveDraftEntry(draftId: _activeDraftId); await _saveDraftEntry(draftId: _activeDraftId);
} catch (_) {
return true;
}
} else if (choice == _ExitChoice.discard) { } else if (choice == _ExitChoice.discard) {
// Delay reset to avoid setState during the dialog/build phase. // Delay reset to avoid setState during the dialog/build phase.
await Future<void>.delayed(Duration.zero); await Future<void>.delayed(Duration.zero);
@@ -53,6 +63,7 @@ extension _NewEntryDraftLogic on _NewEntryPageState {
Future<_ExitChoice> _promptSaveDraft() async { Future<_ExitChoice> _promptSaveDraft() async {
if (!mounted) return _ExitChoice.cancel; if (!mounted) return _ExitChoice.cancel;
try {
final result = await showDialog<_ExitChoice>( final result = await showDialog<_ExitChoice>(
context: context, context: context,
barrierDismissible: false, barrierDismissible: false,
@@ -78,10 +89,15 @@ extension _NewEntryDraftLogic on _NewEntryPageState {
], ],
), ),
); );
if (!mounted) return _ExitChoice.cancel;
return result ?? _ExitChoice.cancel; return result ?? _ExitChoice.cancel;
} catch (_) {
return _ExitChoice.cancel;
}
} }
Future<void> _openDrafts() async { Future<void> _openDrafts() async {
if (_activeLegShare != null) return;
final selected = await Navigator.of(context).push<_StoredDraft>( final selected = await Navigator.of(context).push<_StoredDraft>(
MaterialPageRoute( MaterialPageRoute(
builder: (_) => _DraftListPage( builder: (_) => _DraftListPage(
@@ -97,6 +113,7 @@ extension _NewEntryDraftLogic on _NewEntryPageState {
} }
Future<void> _saveDraftManually() async { Future<void> _saveDraftManually() async {
if (_activeLegShare != null) return;
if (_savingDraft) return; if (_savingDraft) return;
if (_formIsEmpty()) { if (_formIsEmpty()) {
ScaffoldMessenger.maybeOf(context)?.showSnackBar( ScaffoldMessenger.maybeOf(context)?.showSnackBar(
@@ -123,7 +140,9 @@ extension _NewEntryDraftLogic on _NewEntryPageState {
} }
Future<void> _saveDraft() async { Future<void> _saveDraft() async {
if (_restoringDraft || !_draftPersistenceEnabled) return; if (_restoringDraft || !_draftPersistenceEnabled || _activeLegShare != null) {
return;
}
final prefs = await SharedPreferences.getInstance(); final prefs = await SharedPreferences.getInstance();
final draft = { final draft = {
"date": _selectedDate.toIso8601String(), "date": _selectedDate.toIso8601String(),
@@ -169,6 +188,14 @@ extension _NewEntryDraftLogic on _NewEntryPageState {
"distance": _routeResult!.distance, "distance": _routeResult!.distance,
}, },
"tractionItems": _serializeTractionItems(), "tractionItems": _serializeTractionItems(),
"shareUserIds": _shareUserIds.toList(),
"shareUsers": _shareUsers
.map((u) => {
"user_id": u.userId,
"username": u.username,
"full_name": u.fullName,
})
.toList(),
}; };
await prefs.setString(_kDraftPrefsKey, jsonEncode(draft)); await prefs.setString(_kDraftPrefsKey, jsonEncode(draft));
} }
@@ -235,6 +262,7 @@ extension _NewEntryDraftLogic on _NewEntryPageState {
required String id, required String id,
bool includeTimestamp = true, bool includeTimestamp = true,
}) { }) {
final units = _distanceUnits(context);
final routeStations = _routeResult?.calculatedRoute ?? []; final routeStations = _routeResult?.calculatedRoute ?? [];
final endTime = _legEndDateTime; final endTime = _legEndDateTime;
final originTime = _originDateTime; final originTime = _originDateTime;
@@ -249,7 +277,7 @@ extension _NewEntryDraftLogic on _NewEntryPageState {
? _endController.text.trim() ? _endController.text.trim()
: (routeStations.isNotEmpty ? routeStations.last : ''); : (routeStations.isNotEmpty ? routeStations.last : '');
final mileageVal = _useManualMileage final mileageVal = _useManualMileage
? double.tryParse(_mileageController.text.trim()) ?? 0 ? (units.milesFromInput(_mileageController.text.trim()) ?? 0)
: (_routeResult?.distance ?? 0); : (_routeResult?.distance ?? 0);
final tractionPayload = _buildTractionPayload(); final tractionPayload = _buildTractionPayload();
final commonPayload = { final commonPayload = {
@@ -338,6 +366,7 @@ extension _NewEntryDraftLogic on _NewEntryPageState {
final destination = payload['leg_destination'] as String? ?? ''; final destination = payload['leg_destination'] as String? ?? '';
final tripRaw = payload['leg_trip']; final tripRaw = payload['leg_trip'];
final tripId = tripRaw is num ? tripRaw.toInt() : null; final tripId = tripRaw is num ? tripRaw.toInt() : null;
final units = _distanceUnits(context);
List<String> routeStations = []; List<String> routeStations = [];
RouteResult? restoredRouteResult; RouteResult? restoredRouteResult;
@@ -416,14 +445,20 @@ extension _NewEntryDraftLogic on _NewEntryPageState {
final miles = (payload['leg_distance'] as num?)?.toDouble(); final miles = (payload['leg_distance'] as num?)?.toDouble();
_mileageController.text = miles == null || miles == 0 _mileageController.text = miles == null || miles == 0
? '' ? ''
: miles.toStringAsFixed(2); : units.format(
miles,
decimals: 2,
includeUnit: false,
);
} else { } else {
_startController.text = _startController.text =
routeStations.isNotEmpty ? routeStations.first : ''; routeStations.isNotEmpty ? routeStations.first : '';
_endController.text = _endController.text =
routeStations.isNotEmpty ? routeStations.last : ''; routeStations.isNotEmpty ? routeStations.last : '';
final dist = _routeResult?.distance ?? 0; final dist = _routeResult?.distance ?? 0;
_mileageController.text = dist == 0 ? '' : dist.toStringAsFixed(2); _mileageController.text = dist == 0
? ''
: units.format(dist, decimals: 2, includeUnit: false);
} }
final tractionRaw = data['tractionItems']; final tractionRaw = data['tractionItems'];
@@ -436,6 +471,19 @@ extension _NewEntryDraftLogic on _NewEntryPageState {
..clear() ..clear()
..add(_TractionItem.marker()); ..add(_TractionItem.marker());
} }
final shareIdsRaw = data['shareUserIds'];
final shareUsersRaw = data['shareUsers'];
_shareUserIds = shareIdsRaw is List
? shareIdsRaw.map((e) => e.toString()).toSet()
: {};
_shareUsers = shareUsersRaw is List
? shareUsersRaw
.whereType<Map>()
.map((e) => UserSummary.fromJson(
e.map((k, v) => MapEntry(k.toString(), v)),
))
.toList()
: [];
_lastSubmittedSnapshot = null; _lastSubmittedSnapshot = null;
final idRaw = data['id']; final idRaw = data['id'];
if (idRaw != null) { if (idRaw != null) {

View File

@@ -150,6 +150,7 @@ class _DraftListBodyState extends State<_DraftListBody> {
final payload = draft.data['payload']; final payload = draft.data['payload'];
if (payload is! Map) return ''; if (payload is! Map) return '';
final map = Map<String, dynamic>.from(payload); final map = Map<String, dynamic>.from(payload);
final units = context.read<DistanceUnitService>();
final parts = <String>[]; final parts = <String>[];
if ((map['leg_trip'] as int? ?? 0) != 0) { if ((map['leg_trip'] as int? ?? 0) != 0) {
parts.add('Trip ${map['leg_trip']}'); parts.add('Trip ${map['leg_trip']}');
@@ -164,7 +165,7 @@ class _DraftListBodyState extends State<_DraftListBody> {
(map['leg_distance'] as num?)?.toDouble() ?? (map['leg_distance'] as num?)?.toDouble() ??
(map['leg_mileage'] as num?)?.toDouble(); (map['leg_mileage'] as num?)?.toDouble();
if (mileage != null && mileage > 0) { if (mileage != null && mileage > 0) {
parts.add('${mileage.toStringAsFixed(1)} mi'); parts.add(units.format(mileage, decimals: 1));
} else if (map['leg_route'] is List && } else if (map['leg_route'] is List &&
(map['leg_route'] as List).isNotEmpty) { (map['leg_route'] as List).isNotEmpty) {
parts.add('Route ${(map['leg_route'] as List).length} stops'); parts.add('Route ${(map['leg_route'] as List).length} stops');
@@ -176,4 +177,3 @@ class _DraftListBodyState extends State<_DraftListBody> {
return parts.join(''); return parts.join('');
} }
} }

View File

@@ -1,9 +1,10 @@
part of 'new_entry.dart'; part of 'new_entry.dart';
class NewEntryPage extends StatefulWidget { class NewEntryPage extends StatefulWidget {
const NewEntryPage({super.key, this.editLegId}); const NewEntryPage({super.key, this.editLegId, this.legShare});
final int? editLegId; final int? editLegId;
final LegShareData? legShare;
@override @override
State<NewEntryPage> createState() => _NewEntryPageState(); State<NewEntryPage> createState() => _NewEntryPageState();
@@ -51,9 +52,17 @@ class _NewEntryPageState extends State<NewEntryPage> {
final DeepCollectionEquality _snapshotEquality = final DeepCollectionEquality _snapshotEquality =
const DeepCollectionEquality(); const DeepCollectionEquality();
String? _activeDraftId; String? _activeDraftId;
DistanceUnit? _lastDistanceUnit;
Set<String> _shareUserIds = {};
List<UserSummary> _shareUsers = [];
LegShareData? _activeLegShare;
String? _sharedFromUser;
int? _shareNotificationId;
bool _routeReversedFlag = false;
bool get _isEditing => widget.editLegId != null; bool get _isEditing => widget.editLegId != null;
bool get _draftPersistenceEnabled => bool get _draftPersistenceEnabled =>
_activeLegShare == null &&
false; // legacy single draft disabled in favor of draft list false; // legacy single draft disabled in favor of draft list
@override @override
@@ -68,16 +77,28 @@ class _NewEntryPageState extends State<NewEntryPage> {
data.fetchClassList(); data.fetchClassList();
data.fetchTripOptions(); data.fetchTripOptions();
_loadStations(); _loadStations();
if (_draftPersistenceEnabled) { if (_draftPersistenceEnabled && widget.legShare == null) {
_loadDraft(); _loadDraft();
} }
_loadStations(); _loadStations();
if (_isEditing && widget.editLegId != null) { if (_isEditing && widget.editLegId != null) {
_loadLegForEdit(widget.editLegId!); _loadLegForEdit(widget.editLegId!);
} else if (widget.legShare != null) {
_applyLegShare(widget.legShare!);
} }
}); });
} }
@override
void didUpdateWidget(covariant NewEntryPage oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.legShare != null &&
(oldWidget.legShare == null ||
widget.legShare!.id != oldWidget.legShare!.id)) {
_applyLegShare(widget.legShare!);
}
}
@override @override
void dispose() { void dispose() {
NavigationGuard.unregister(_exitGuard); NavigationGuard.unregister(_exitGuard);
@@ -100,9 +121,375 @@ class _NewEntryPageState extends State<NewEntryPage> {
setState(fn); setState(fn);
} }
DistanceUnitService _distanceUnits(BuildContext context) =>
context.read<DistanceUnitService>();
String _formatDistance(
DistanceUnitService units,
double miles, {
int decimals = 1,
bool includeUnit = true,
}) {
return units.format(
miles,
decimals: decimals,
includeUnit: includeUnit,
);
}
String _manualMileageLabel(DistanceUnit unit) {
switch (unit) {
case DistanceUnit.milesDecimal:
return 'Mileage (mi)';
case DistanceUnit.kilometers:
return 'Mileage (km)';
case DistanceUnit.milesChains:
return 'Mileage (m.ch)';
}
}
void _reverseRouteAndEndpoints() {
setState(() {
// Swap start/end and origin/destination fields
final startText = _startController.text;
final endText = _endController.text;
_startController.text = endText;
_endController.text = startText;
final originText = _originController.text;
final destText = _destinationController.text;
_originController.text = destText;
_destinationController.text = originText;
// Reverse route result if present
if (_routeResult != null) {
final reversedInput = _routeResult!.inputRoute.reversed.toList();
final reversedCalc = _routeResult!.calculatedRoute.reversed.toList();
final reversedCosts = _routeResult!.costs.reversed.toList();
_routeResult = RouteResult(
inputRoute: reversedInput,
calculatedRoute: reversedCalc,
costs: reversedCosts,
distance: _routeResult!.distance,
);
final units = _distanceUnits(context);
_mileageController.text = _formatDistance(
units,
_routeResult!.distance,
decimals: 2,
includeUnit: false,
);
_useManualMileage = false;
} else if (_useManualMileage &&
_mileageController.text.trim().isNotEmpty) {
// keep manual mileage, just swap endpoints
}
_routeReversedFlag = !_routeReversedFlag;
});
_saveDraft();
_scheduleMatchUpdate();
}
double _milesFromInputWithUnit(DistanceUnit unit) {
return DistanceFormatter(unit)
.parseInputMiles(_mileageController.text.trim()) ??
0;
}
List<UserSummary> _friendsFromFriendships(
DataService data,
String? selfId,
) {
final friends = <UserSummary>[];
for (final f in data.friendships) {
final other = _friendFromFriendship(f, selfId);
if (other != null &&
other.userId.isNotEmpty &&
!friends.any((u) => u.userId == other.userId)) {
friends.add(other);
}
}
return friends;
}
UserSummary? _friendFromFriendship(Friendship friendship, String? selfId) {
final self = selfId ?? '';
if (friendship.requesterId == self) return friendship.addressee;
if (friendship.addresseeId == self) return friendship.requester;
if (friendship.addressee != null) return friendship.addressee;
if (friendship.requester != null) return friendship.requester;
return null;
}
Widget _buildShareSection(BuildContext context) {
final selected = _shareUsers;
final label = selected.isEmpty
? 'Share with friends'
: 'Shared with ${selected.length} friend${selected.length == 1 ? '' : 's'}';
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
OutlinedButton.icon(
onPressed: _submitting ? null : _openShareSheet,
icon: const Icon(Icons.share),
label: Text(label),
),
if (selected.isNotEmpty) ...[
const SizedBox(height: 8),
Wrap(
spacing: 8,
runSpacing: 8,
children: selected
.map(
(u) => InputChip(
label: Text(u.displayName),
avatar: const Icon(Icons.person, size: 16),
onDeleted: _submitting
? null
: () {
setState(() {
_shareUserIds.remove(u.userId);
_shareUsers.removeWhere(
(item) => item.userId == u.userId,
);
});
},
),
)
.toList(),
),
],
],
);
}
Widget _buildSharedBanner() {
final from = _sharedFromUser;
return Container(
width: double.infinity,
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.orange.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(8),
border: Border.all(color: Colors.orange.withValues(alpha: 0.4)),
),
child: Row(
children: [
const Icon(Icons.share, color: Colors.orange),
const SizedBox(width: 8),
Expanded(
child: Text(
from != null && from.isNotEmpty
? 'This entry was shared by $from.'
: 'This entry was shared with you.',
style: const TextStyle(fontWeight: FontWeight.w600),
),
),
],
),
);
}
Future<void> _openShareSheet() async {
if (_activeLegShare != null) return;
final data = context.read<DataService>();
final auth = context.read<AuthService>();
try {
await data.fetchFriendships();
} catch (_) {}
if (!mounted) return;
final baseFriends = _friendsFromFriendships(data, auth.userId);
final initialSelectedIds = {..._shareUserIds};
final initialSelectedUsers = {
for (final u in _shareUsers) u.userId: u,
};
final result = await showModalBottomSheet<List<UserSummary>>(
context: context,
isScrollControlled: true,
builder: (ctx) {
final searchController = TextEditingController();
List<UserSummary> searchResults = [];
bool searching = false;
String searchTerm = '';
String? searchError;
final selectedIds = {...initialSelectedIds};
final selectedUsers = {...initialSelectedUsers};
return StatefulBuilder(
builder: (modalContext, setModalState) {
Future<void> runSearch(String term) async {
final trimmed = term.trim();
if (trimmed.isEmpty) {
setModalState(() {
searchTerm = '';
searchResults = [];
searchError = null;
});
return;
}
setModalState(() {
searchTerm = trimmed;
searching = true;
searchError = null;
});
try {
final results =
await data.searchUsers(trimmed, friendsOnly: true);
setModalState(() {
searchResults = results;
});
} catch (e) {
setModalState(() {
searchError = 'Search failed';
});
} finally {
setModalState(() {
searching = false;
});
}
}
final list = searchTerm.isNotEmpty ? searchResults : baseFriends;
return Padding(
padding: EdgeInsets.only(
bottom: MediaQuery.of(modalContext).viewInsets.bottom + 16,
left: 16,
right: 16,
top: 16,
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
const Expanded(
child: Text(
'Share with friends',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w600,
),
),
),
IconButton(
onPressed: () => Navigator.of(modalContext).pop(),
icon: const Icon(Icons.close),
),
],
),
const SizedBox(height: 8),
TextField(
controller: searchController,
decoration: InputDecoration(
labelText: 'Search friends',
border: const OutlineInputBorder(),
suffixIcon: IconButton(
icon: const Icon(Icons.search),
onPressed: () => runSearch(searchController.text),
),
),
onSubmitted: runSearch,
),
if (searching)
const Padding(
padding: EdgeInsets.only(top: 8.0),
child: LinearProgressIndicator(minHeight: 2),
),
if (searchError != null)
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Text(
searchError!,
style: const TextStyle(color: Colors.red),
),
),
const SizedBox(height: 12),
SizedBox(
height: 320,
child: list.isEmpty
? const Center(child: Text('No friends found'))
: ListView.builder(
itemCount: list.length,
itemBuilder: (_, index) {
final user = list[index];
final isSelected =
selectedIds.contains(user.userId);
return CheckboxListTile(
value: isSelected,
title: Text(user.displayName),
subtitle: user.username.isNotEmpty
? Text('@${user.username}')
: null,
onChanged: (checked) {
setModalState(() {
if (checked == true) {
selectedIds.add(user.userId);
selectedUsers[user.userId] = user;
} else {
selectedIds.remove(user.userId);
selectedUsers.remove(user.userId);
}
});
},
);
},
),
),
const SizedBox(height: 12),
Row(
children: [
TextButton(
onPressed: () => Navigator.of(modalContext).pop(),
child: const Text('Cancel'),
),
const Spacer(),
ElevatedButton(
onPressed: () => Navigator.of(modalContext).pop(
selectedIds
.map((id) => selectedUsers[id])
.whereType<UserSummary>()
.toList(),
),
child: const Text('Save'),
),
],
),
],
),
);
},
);
},
);
if (result != null && mounted) {
setState(() {
_shareUsers = result;
_shareUserIds = result.map((u) => u.userId).toSet();
});
}
}
void _syncManualFieldUnit(DistanceUnit currentUnit) {
if (!_useManualMileage) {
_lastDistanceUnit = currentUnit;
return;
}
final previousUnit = _lastDistanceUnit ?? currentUnit;
if (previousUnit == currentUnit) return;
final miles = _milesFromInputWithUnit(previousUnit);
final nextText = DistanceFormatter(currentUnit)
.format(miles, decimals: 2, includeUnit: false);
_mileageController.text = nextText;
_lastDistanceUnit = currentUnit;
}
Widget _buildTripSelector(BuildContext context) { Widget _buildTripSelector(BuildContext context) {
final trips = context.watch<DataService>().tripList; final trips = context.watch<DataService>().tripList;
final sorted = [...trips]..sort((a, b) => b.tripId.compareTo(a.tripId)); final sorted = [...trips]..sort(TripSummary.compareByDateDesc);
final tripIds = sorted.map((t) => t.tripId).toSet(); final tripIds = sorted.map((t) => t.tripId).toSet();
final selectedValue = final selectedValue =
(_selectedTripId != null && tripIds.contains(_selectedTripId)) (_selectedTripId != null && tripIds.contains(_selectedTripId))
@@ -223,10 +610,17 @@ class _NewEntryPageState extends State<NewEntryPage> {
), ),
), ),
); );
if (!mounted) return;
if (result != null) { if (result != null) {
final units = _distanceUnits(context);
setState(() { setState(() {
_routeResult = result; _routeResult = result;
_mileageController.text = result.distance.toStringAsFixed(2); _mileageController.text = _formatDistance(
units,
result.distance,
decimals: 2,
includeUnit: false,
);
_useManualMileage = false; _useManualMileage = false;
}); });
_saveDraft(); _saveDraft();
@@ -426,6 +820,7 @@ class _NewEntryPageState extends State<NewEntryPage> {
final endTime = DateTime.tryParse(json['leg_end_time'] ?? ''); final endTime = DateTime.tryParse(json['leg_end_time'] ?? '');
final routeStations = _parseRouteStations(json['leg_route']); final routeStations = _parseRouteStations(json['leg_route']);
final mileageVal = (json['leg_mileage'] as num?)?.toDouble() ?? 0.0; final mileageVal = (json['leg_mileage'] as num?)?.toDouble() ?? 0.0;
final units = _distanceUnits(context);
final useManual = routeStations.isEmpty; final useManual = routeStations.isEmpty;
final routeResult = useManual final routeResult = useManual
? null ? null
@@ -484,7 +879,12 @@ class _NewEntryPageState extends State<NewEntryPage> {
_endDelayController.text = endDelay.toString(); _endDelayController.text = endDelay.toString();
_mileageController.text = mileageVal == 0 _mileageController.text = mileageVal == 0
? '' ? ''
: mileageVal.toStringAsFixed(2); : _formatDistance(
units,
mileageVal,
decimals: 2,
includeUnit: false,
);
_tractionItems _tractionItems
..clear() ..clear()
..addAll(tractionItems); ..addAll(tractionItems);
@@ -509,6 +909,96 @@ class _NewEntryPageState extends State<NewEntryPage> {
} }
} }
void _applyLegShare(LegShareData share) {
final entry = share.entry;
final beginTime = entry.beginTime;
final endTime = entry.endTime;
final routeStations = entry.route;
final mileageVal = entry.mileage;
final units = _distanceUnits(context);
final useManual = routeStations.isEmpty;
final routeResult = useManual
? null
: RouteResult(
inputRoute: routeStations,
calculatedRoute: routeStations,
costs: const <double>[],
distance: mileageVal,
);
final tractionItems = _buildTractionFromApi(
entry.locos
.map((l) => {
"loco_id": l.id,
"type": l.type,
"number": l.number,
"class": l.locoClass,
"name": l.name,
"operator": l.operator,
"notes": l.notes,
"evn": l.evn,
"alloc_pos": l.allocPos,
"alloc_powering": l.powering ? 1 : 0,
})
.toList(),
);
final beginDelay = entry.beginDelayMinutes ?? 0;
final endDelay = entry.endDelayMinutes ?? 0;
final originTime = entry.originTime;
final destinationTime = entry.destinationTime;
final hasOriginTime = originTime != null;
final hasDestinationTime = destinationTime != null;
final hasEndTime = endTime != null || endDelay != 0;
_restoringDraft = true;
setState(() {
_activeLegShare = share;
_sharedFromUser = share.sharedFromName;
_shareNotificationId = share.notificationId;
_selectedTripId = null;
_selectedDate = beginTime;
_selectedTime = TimeOfDay.fromDateTime(beginTime);
_selectedEndDate = endTime ?? beginTime;
_selectedEndTime = TimeOfDay.fromDateTime(endTime ?? beginTime);
_hasEndTime = hasEndTime;
_selectedOriginDate = originTime ?? beginTime;
_selectedOriginTime = TimeOfDay.fromDateTime(originTime ?? beginTime);
_selectedDestinationDate = destinationTime ?? endTime ?? beginTime;
_selectedDestinationTime =
TimeOfDay.fromDateTime(destinationTime ?? endTime ?? beginTime);
_hasOriginTime = hasOriginTime;
_hasDestinationTime = hasDestinationTime;
_useManualMileage = useManual;
_routeResult = routeResult;
_startController.text = entry.start;
_endController.text = entry.end;
_headcodeController.text = entry.headcode.toUpperCase();
_notesController.text = entry.notes;
_networkController.text = entry.network.toUpperCase();
_originController.text = entry.origin;
_destinationController.text = entry.destination;
_beginDelayController.text = beginDelay.toString();
_endDelayController.text = endDelay.toString();
_mileageController.text = mileageVal == 0
? ''
: _formatDistance(
units,
mileageVal,
decimals: 2,
includeUnit: false,
);
_tractionItems
..clear()
..addAll(tractionItems);
if (_tractionItems.where((e) => e.isMarker).isEmpty) {
_tractionItems.insert(0, _TractionItem.marker());
}
_lastSubmittedSnapshot = null;
_shareUserIds.clear();
_shareUsers.clear();
});
_restoringDraft = false;
}
List<String> _parseRouteStations(dynamic raw) { List<String> _parseRouteStations(dynamic raw) {
if (raw is List) { if (raw is List) {
return raw.map((e) => e.toString()).toList(); return raw.map((e) => e.toString()).toList();
@@ -728,11 +1218,15 @@ class _NewEntryPageState extends State<NewEntryPage> {
key: _formKey, key: _formKey,
child: LayoutBuilder( child: LayoutBuilder(
builder: (context, constraints) { builder: (context, constraints) {
final distanceUnitService = context.watch<DistanceUnitService>();
final currentDistanceUnit = distanceUnitService.unit;
_syncManualFieldUnit(currentDistanceUnit);
final twoCol = !isMobile && constraints.maxWidth > 1000; final twoCol = !isMobile && constraints.maxWidth > 1000;
final tractionEmpty = _tractionItems.length == 1; final tractionEmpty = _tractionItems.length == 1;
final mileageEmpty = !_useManualMileage && _routeResult == null; final mileageEmpty = !_useManualMileage && _routeResult == null;
final balancePanels = twoCol && tractionEmpty && mileageEmpty; final balancePanels = twoCol && tractionEmpty && mileageEmpty;
final balancedHeight = balancePanels ? 165.0 : null; final balancedHeight = balancePanels ? 165.0 : null;
final mileageLabel = _manualMileageLabel(currentDistanceUnit);
final entryPanel = _section('Entry', [ final entryPanel = _section('Entry', [
Row( Row(
@@ -743,7 +1237,8 @@ class _NewEntryPageState extends State<NewEntryPage> {
minimumSize: const Size(0, 36), minimumSize: const Size(0, 36),
tapTargetSize: MaterialTapTargetSize.shrinkWrap, tapTargetSize: MaterialTapTargetSize.shrinkWrap,
), ),
onPressed: _isEditing ? null : _openDrafts, onPressed:
_isEditing || _activeLegShare != null ? null : _openDrafts,
icon: const Icon(Icons.list_alt, size: 16), icon: const Icon(Icons.list_alt, size: 16),
label: const Text('Drafts'), label: const Text('Drafts'),
), ),
@@ -754,7 +1249,10 @@ class _NewEntryPageState extends State<NewEntryPage> {
minimumSize: const Size(0, 36), minimumSize: const Size(0, 36),
tapTargetSize: MaterialTapTargetSize.shrinkWrap, tapTargetSize: MaterialTapTargetSize.shrinkWrap,
), ),
onPressed: _isEditing || _savingDraft || _submitting onPressed: _isEditing ||
_savingDraft ||
_submitting ||
_activeLegShare != null
? null ? null
: _saveDraftManually, : _saveDraftManually,
icon: _savingDraft icon: _savingDraft
@@ -781,7 +1279,13 @@ class _NewEntryPageState extends State<NewEntryPage> {
), ),
], ],
), ),
if (_activeLegShare != null) ...[
const SizedBox(height: 8),
_buildSharedBanner(),
],
_buildTripSelector(context), _buildTripSelector(context),
const SizedBox(height: 12),
if (_activeLegShare == null) _buildShareSection(context),
_dateTimeGroup( _dateTimeGroup(
context, context,
title: 'Departure time', title: 'Departure time',
@@ -930,17 +1434,53 @@ class _NewEntryPageState extends State<NewEntryPage> {
_buildTractionList(), _buildTractionList(),
], minHeight: balancedHeight); ], minHeight: balancedHeight);
final routeStart = _routeResult?.calculatedRoute.isNotEmpty == true
? _routeResult!.calculatedRoute.first
: (_routeResult?.inputRoute.isNotEmpty == true
? _routeResult!.inputRoute.first
: _startController.text.trim());
final routeEnd = _routeResult?.calculatedRoute.isNotEmpty == true
? _routeResult!.calculatedRoute.last
: (_routeResult?.inputRoute.isNotEmpty == true
? _routeResult!.inputRoute.last
: _endController.text.trim());
final mileagePanel = _section( final mileagePanel = _section(
'Mileage', 'Your Journey',
[ [
if (!_useManualMileage) if (!_useManualMileage)
Align( Wrap(
alignment: Alignment.centerLeft, spacing: 12,
child: ElevatedButton.icon( runSpacing: 8,
children: [
ElevatedButton.icon(
onPressed: _openCalculator, onPressed: _openCalculator,
icon: const Icon(Icons.calculate, size: 18), icon: const Icon(Icons.calculate, size: 18),
label: const Text('Open mileage calculator'), label: const Text('Open mileage calculator'),
), ),
OutlinedButton.icon(
onPressed: _reverseRouteAndEndpoints,
icon: const Icon(Icons.swap_horiz),
label: const Text('Reverse route'),
),
],
)
else
Align(
alignment: Alignment.centerLeft,
child: OutlinedButton.icon(
onPressed: _reverseRouteAndEndpoints,
icon: const Icon(Icons.swap_horiz),
label: const Text('Reverse route'),
),
),
if (routeStart.isNotEmpty || routeEnd.isNotEmpty)
ListTile(
contentPadding: EdgeInsets.zero,
title: const Text('Route'),
subtitle: Text(
'${routeStart.isEmpty ? 'Start' : routeStart}${routeEnd.isEmpty ? 'End' : routeEnd}',
),
), ),
if (_useManualMileage) if (_useManualMileage)
TextFormField( TextFormField(
@@ -948,9 +1488,13 @@ class _NewEntryPageState extends State<NewEntryPage> {
keyboardType: const TextInputType.numberWithOptions( keyboardType: const TextInputType.numberWithOptions(
decimal: true, decimal: true,
), ),
decoration: const InputDecoration( decoration: InputDecoration(
labelText: 'Mileage (mi)', labelText: mileageLabel,
border: OutlineInputBorder(), helperText: currentDistanceUnit ==
DistanceUnit.milesChains
? 'Enter as miles.chains (e.g., 12.40 for 12m 40c)'
: null,
border: const OutlineInputBorder(),
), ),
) )
else if (_routeResult != null) else if (_routeResult != null)
@@ -958,7 +1502,11 @@ class _NewEntryPageState extends State<NewEntryPage> {
contentPadding: EdgeInsets.zero, contentPadding: EdgeInsets.zero,
title: const Text('Calculated mileage'), title: const Text('Calculated mileage'),
subtitle: Text( subtitle: Text(
'${_routeResult!.distance.toStringAsFixed(2)} mi', _formatDistance(
distanceUnitService,
_routeResult!.distance,
decimals: 2,
),
), ),
) )
else else
@@ -973,7 +1521,17 @@ class _NewEntryPageState extends State<NewEntryPage> {
label: Text(_useManualMileage ? 'Manual' : 'Automatic'), label: Text(_useManualMileage ? 'Manual' : 'Automatic'),
selected: _useManualMileage, selected: _useManualMileage,
onSelected: (val) { onSelected: (val) {
setState(() => _useManualMileage = val); setState(() {
_useManualMileage = val;
if (val && _routeResult != null) {
_mileageController.text = _formatDistance(
distanceUnitService,
_routeResult!.distance,
decimals: 2,
includeUnit: false,
);
}
});
_saveDraft(); _saveDraft();
_scheduleMatchUpdate(); _scheduleMatchUpdate();
}, },
@@ -988,22 +1546,25 @@ class _NewEntryPageState extends State<NewEntryPage> {
children: [ children: [
entryPanel, entryPanel,
const SizedBox(height: 16), const SizedBox(height: 16),
if (twoCol) ...[
trainPanel, trainPanel,
const SizedBox(height: 16), const SizedBox(height: 16),
twoCol Row(
? Row(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Expanded(child: tractionPanel), Expanded(child: tractionPanel),
const SizedBox(width: 16), const SizedBox(width: 16),
Expanded(child: mileagePanel), Expanded(child: mileagePanel),
], ],
) ),
: Column( ] else
Column(
children: [ children: [
tractionPanel,
const SizedBox(height: 16),
mileagePanel, mileagePanel,
const SizedBox(height: 16),
trainPanel,
const SizedBox(height: 16),
tractionPanel,
], ],
), ),
const SizedBox(height: 12), const SizedBox(height: 12),
@@ -1016,11 +1577,15 @@ class _NewEntryPageState extends State<NewEntryPage> {
child: CircularProgressIndicator(strokeWidth: 2), child: CircularProgressIndicator(strokeWidth: 2),
) )
: const Icon(Icons.send), : const Icon(Icons.send),
label: Text( label: () {
_submitting final shareMode = _activeLegShare != null;
? (_isEditing ? 'Saving...' : 'Submitting...') if (_submitting) {
: (_isEditing ? 'Save changes' : 'Submit entry'), if (shareMode) return const Text('Accepting...');
), return Text(_isEditing ? 'Saving...' : 'Submitting...');
}
if (shareMode) return const Text('Accept entry');
return Text(_isEditing ? 'Save changes' : 'Submit entry');
}(),
), ),
], ],
), ),
@@ -1449,43 +2014,6 @@ class _NewEntryPageState extends State<NewEntryPage> {
); );
} }
Widget _timeToggleBlock({
required String label,
required bool value,
required ValueChanged<bool?>? onChanged,
required String matchLabel,
required bool matchValue,
required ValueChanged<bool?>? onMatchChanged,
required bool showMatch,
Widget? picker,
}) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
CheckboxListTile(
value: value,
onChanged: onChanged,
dense: true,
contentPadding: EdgeInsets.zero,
controlAffinity: ListTileControlAffinity.leading,
title: Text(label),
),
if (showMatch)
CheckboxListTile(
value: matchValue,
onChanged: onMatchChanged,
dense: true,
contentPadding: const EdgeInsets.only(left: 12),
controlAffinity: ListTileControlAffinity.leading,
title: Text(matchLabel),
),
if (picker != null) ...[
const SizedBox(height: 6),
picker,
],
],
);
}
} }
class _UpperCaseTextFormatter extends TextInputFormatter { class _UpperCaseTextFormatter extends TextInputFormatter {

View File

@@ -4,11 +4,12 @@ extension _NewEntrySubmitLogic on _NewEntryPageState {
Future<bool> _validateRequiredFields() async { Future<bool> _validateRequiredFields() async {
final missing = <String>[]; final missing = <String>[];
final units = _distanceUnits(context);
if (_useManualMileage) { if (_useManualMileage) {
if (_startController.text.trim().isEmpty) missing.add('From'); if (_startController.text.trim().isEmpty) missing.add('From');
if (_endController.text.trim().isEmpty) missing.add('To'); if (_endController.text.trim().isEmpty) missing.add('To');
final mileageText = _mileageController.text.trim(); final mileageText = _mileageController.text.trim();
if (double.tryParse(mileageText) == null) { if (mileageText.isEmpty || units.milesFromInput(mileageText) == null) {
missing.add('Mileage'); missing.add('Mileage');
} }
} else { } else {
@@ -51,6 +52,7 @@ extension _NewEntrySubmitLogic on _NewEntryPageState {
if (form == null) return; if (form == null) return;
if (!form.validate()) return; if (!form.validate()) return;
if (!await _validateRequiredFields()) return; if (!await _validateRequiredFields()) return;
if (!mounted) return;
final routeStations = _routeResult?.calculatedRoute ?? []; final routeStations = _routeResult?.calculatedRoute ?? [];
final startVal = _useManualMileage final startVal = _useManualMileage
? _startController.text.trim() ? _startController.text.trim()
@@ -58,8 +60,9 @@ extension _NewEntrySubmitLogic on _NewEntryPageState {
final endVal = _useManualMileage final endVal = _useManualMileage
? _endController.text.trim() ? _endController.text.trim()
: (routeStations.isNotEmpty ? routeStations.last : ''); : (routeStations.isNotEmpty ? routeStations.last : '');
final units = _distanceUnits(context);
final mileageVal = _useManualMileage final mileageVal = _useManualMileage
? double.tryParse(_mileageController.text.trim()) ?? 0 ? (units.milesFromInput(_mileageController.text.trim()) ?? 0)
: (_routeResult?.distance ?? 0); : (_routeResult?.distance ?? 0);
final tractionPayload = _buildTractionPayload(); final tractionPayload = _buildTractionPayload();
final endTime = _legEndDateTime; final endTime = _legEndDateTime;
@@ -68,12 +71,14 @@ extension _NewEntrySubmitLogic on _NewEntryPageState {
final beginDelay = _parseDelayMinutes(_beginDelayController.text); final beginDelay = _parseDelayMinutes(_beginDelayController.text);
final endDelay = final endDelay =
_hasEndTime ? _parseDelayMinutes(_endDelayController.text) : 0; _hasEndTime ? _parseDelayMinutes(_endDelayController.text) : 0;
final snapshot = _buildSubmissionSnapshot( final snapshot = _currentSubmissionSnapshot(
routeStations: routeStations, routeStations: routeStations,
startVal: startVal, startVal: startVal,
endVal: endVal, endVal: endVal,
mileageVal: mileageVal, mileageVal: mileageVal,
tractionPayload: tractionPayload, tractionPayload: tractionPayload,
beginDelay: beginDelay,
endDelay: endDelay,
); );
if (_lastSubmittedSnapshot != null && if (_lastSubmittedSnapshot != null &&
_snapshotEquality.equals(_lastSubmittedSnapshot, snapshot)) { _snapshotEquality.equals(_lastSubmittedSnapshot, snapshot)) {
@@ -105,6 +110,8 @@ extension _NewEntrySubmitLogic on _NewEntryPageState {
"leg_begin_delay": beginDelay, "leg_begin_delay": beginDelay,
if (_hasEndTime) "leg_end_delay": endDelay, if (_hasEndTime) "leg_end_delay": endDelay,
"locos": tractionPayload, "locos": tractionPayload,
if (_activeLegShare != null) "leg_share_id": _activeLegShare!.id,
"share_user_ids": _shareUserIds.toList(),
}; };
if (_useManualMileage) { if (_useManualMileage) {
final body = { final body = {
@@ -133,6 +140,9 @@ extension _NewEntrySubmitLogic on _NewEntryPageState {
if (!mounted) return; if (!mounted) return;
dataService.refreshLegs(); dataService.refreshLegs();
await dataService.fetchNotifications(); await dataService.fetchNotifications();
if (_shareNotificationId != null) {
await dataService.dismissNotifications([_shareNotificationId!]);
}
if (!mounted) return; if (!mounted) return;
messenger?.showSnackBar( messenger?.showSnackBar(
SnackBar( SnackBar(
@@ -153,16 +163,35 @@ extension _NewEntrySubmitLogic on _NewEntryPageState {
} }
} }
Map<String, dynamic> _buildSubmissionSnapshot({ Map<String, dynamic> _currentSubmissionSnapshot({
required List<String> routeStations, List<String>? routeStations,
required String startVal, String? startVal,
required String endVal, String? endVal,
required double mileageVal, double? mileageVal,
required List<Map<String, dynamic>> tractionPayload, List<Map<String, dynamic>>? tractionPayload,
int? beginDelay,
int? endDelay,
}) { }) {
final beginDelay = _parseDelayMinutes(_beginDelayController.text); final stations = routeStations ?? (_routeResult?.calculatedRoute ?? []);
final endDelay = final start = startVal ??
_hasEndTime ? _parseDelayMinutes(_endDelayController.text) : 0; (_useManualMileage
? _startController.text.trim()
: (stations.isNotEmpty ? stations.first : ''));
final end = endVal ??
(_useManualMileage
? _endController.text.trim()
: (stations.isNotEmpty ? stations.last : ''));
final mileage = mileageVal ??
(_useManualMileage
? (_distanceUnits(context)
.milesFromInput(_mileageController.text.trim()) ??
0)
: (_routeResult?.distance ?? 0));
final traction = tractionPayload ?? _buildTractionPayload();
final begin = beginDelay ?? _parseDelayMinutes(_beginDelayController.text);
final endDelayVal =
endDelay ?? (_hasEndTime ? _parseDelayMinutes(_endDelayController.text) : 0);
return { return {
"legId": widget.editLegId, "legId": widget.editLegId,
"useManualMileage": _useManualMileage, "useManualMileage": _useManualMileage,
@@ -174,18 +203,20 @@ extension _NewEntrySubmitLogic on _NewEntryPageState {
"hasOriginTime": _hasOriginTime, "hasOriginTime": _hasOriginTime,
"legDestinationTime": _destinationDateTime?.toIso8601String(), "legDestinationTime": _destinationDateTime?.toIso8601String(),
"hasDestinationTime": _hasDestinationTime, "hasDestinationTime": _hasDestinationTime,
"start": startVal, "start": start,
"end": endVal, "end": end,
"origin": _originController.text.trim(), "origin": _originController.text.trim(),
"destination": _destinationController.text.trim(), "destination": _destinationController.text.trim(),
"routeStations": routeStations, "routeStations": stations,
"mileage": mileageVal, "mileage": mileage,
"network": _networkController.text.trim(), "network": _networkController.text.trim(),
"notes": _notesController.text.trim(), "notes": _notesController.text.trim(),
"headcode": _headcodeController.text.trim(), "headcode": _headcodeController.text.trim(),
"beginDelay": beginDelay, "beginDelay": begin,
"endDelay": endDelay, "endDelay": endDelayVal,
"locos": tractionPayload, "legShareId": _activeLegShare?.id,
"shareUserIds": _shareUserIds.toList(),
"locos": traction,
"routeResult": _routeResult == null "routeResult": _routeResult == null
? null ? null
: { : {
@@ -220,6 +251,7 @@ extension _NewEntrySubmitLogic on _NewEntryPageState {
} }
Future<void> _resetFormState({bool clearDraft = false}) async { Future<void> _resetFormState({bool clearDraft = false}) async {
final hadShare = _activeLegShare != null || widget.legShare != null;
_formKey.currentState?.reset(); _formKey.currentState?.reset();
_startController.clear(); _startController.clear();
_endController.clear(); _endController.clear();
@@ -249,6 +281,11 @@ extension _NewEntrySubmitLogic on _NewEntryPageState {
_matchDestinationToEntry = false; _matchDestinationToEntry = false;
_matchUpdateScheduled = false; _matchUpdateScheduled = false;
_routeResult = null; _routeResult = null;
_activeLegShare = null;
_sharedFromUser = null;
_shareNotificationId = null;
_shareUserIds.clear();
_shareUsers.clear();
_tractionItems _tractionItems
..clear() ..clear()
..add(_TractionItem.marker()); ..add(_TractionItem.marker());
@@ -258,6 +295,10 @@ extension _NewEntrySubmitLogic on _NewEntryPageState {
_savingDraft = false; _savingDraft = false;
_loadedDraftSnapshot = null; _loadedDraftSnapshot = null;
}); });
if (hadShare && mounted) {
// Clear any share params from the URL when resetting.
GoRouter.of(context).go('/add');
}
if (clearDraft) { if (clearDraft) {
await _clearDraft(); await _clearDraft();
} }

View File

@@ -84,6 +84,13 @@ class _NewTractionPageState extends State<NewTractionPage> {
'traction_motors': TextEditingController(), 'traction_motors': TextEditingController(),
'build_date': TextEditingController(), 'build_date': TextEditingController(),
}; };
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
final data = context.read<DataService>();
if (data.locoClasses.isEmpty) {
data.fetchClassList();
}
});
} }
@override @override
@@ -254,6 +261,10 @@ class _NewTractionPageState extends State<NewTractionPage> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final isActive = _statusIsActive; final isActive = _statusIsActive;
final data = context.watch<DataService>();
final classOptions = [...data.locoClasses]..sort(
(a, b) => a.toLowerCase().compareTo(b.toLowerCase()),
);
final size = MediaQuery.of(context).size; final size = MediaQuery.of(context).size;
final isNarrow = size.width < 720; final isNarrow = size.width < 720;
final fieldWidth = isNarrow ? double.infinity : 340.0; final fieldWidth = isNarrow ? double.infinity : 340.0;
@@ -269,6 +280,89 @@ class _NewTractionPageState extends State<NewTractionPage> {
double? widthOverride, double? widthOverride,
String? Function(String?)? validator, String? Function(String?)? validator,
}) { }) {
// Special autocomplete for class field using existing loco classes.
if (key == 'class' && classOptions.isNotEmpty) {
return SizedBox(
width: widthOverride ?? fieldWidth,
child: Autocomplete<String>(
optionsBuilder: (TextEditingValue value) {
final query = value.text.trim().toLowerCase();
if (query.isEmpty) return classOptions;
return classOptions.where(
(c) => c.toLowerCase().contains(query),
);
},
onSelected: (selection) {
_controllers[key]?.text = selection;
_formKey.currentState?.validate();
},
fieldViewBuilder:
(context, textEditingController, focusNode, onFieldSubmitted) {
if (textEditingController.text != _controllers[key]?.text) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
if (textEditingController.text != _controllers[key]?.text) {
textEditingController.value =
_controllers[key]?.value ?? textEditingController.value;
}
});
}
return TextFormField(
controller: textEditingController,
focusNode: focusNode,
decoration: InputDecoration(
labelText: required ? '$label *' : label,
helperText: helper,
suffixText: suffixText,
border: const OutlineInputBorder(),
),
keyboardType: keyboardType,
maxLines: maxLines,
validator: (val) {
if (required && (val == null || val.trim().isEmpty)) {
return 'Required';
}
return validator?.call(val);
},
onChanged: (_) {
_controllers[key]?.text = textEditingController.text;
_formKey.currentState?.validate();
},
onFieldSubmitted: (_) => onFieldSubmitted(),
);
},
optionsViewBuilder: (context, onSelected, options) {
final opts = options.toList();
if (opts.isEmpty) return const SizedBox.shrink();
return Align(
alignment: Alignment.topLeft,
child: Material(
elevation: 4,
child: ConstrainedBox(
constraints: BoxConstraints(
maxHeight: 280,
maxWidth: widthOverride ?? fieldWidth,
),
child: ListView.builder(
padding: EdgeInsets.zero,
itemCount: opts.length,
itemBuilder: (context, index) {
final option = opts[index];
return ListTile(
dense: true,
title: Text(option),
onTap: () => onSelected(option),
);
},
),
),
),
);
},
),
);
}
return SizedBox( return SizedBox(
width: widthOverride ?? fieldWidth, width: widthOverride ?? fieldWidth,
child: TextFormField( child: TextFormField(

File diff suppressed because it is too large Load Diff

View File

@@ -5,6 +5,7 @@ import 'package:go_router/go_router.dart';
import 'package:http/http.dart' as http; import 'package:http/http.dart' as http;
import 'package:mileograph_flutter/services/authservice.dart'; import 'package:mileograph_flutter/services/authservice.dart';
import 'package:mileograph_flutter/services/api_service.dart'; import 'package:mileograph_flutter/services/api_service.dart';
import 'package:mileograph_flutter/services/distance_unit_service.dart';
import 'package:mileograph_flutter/services/endpoint_service.dart'; import 'package:mileograph_flutter/services/endpoint_service.dart';
import 'package:mileograph_flutter/services/data_service.dart'; import 'package:mileograph_flutter/services/data_service.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
@@ -175,10 +176,11 @@ class _SettingsPageState extends State<SettingsPage> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final endpointService = context.watch<EndpointService>(); final endpointService = context.watch<EndpointService>();
final distanceUnitService = context.watch<DistanceUnitService>();
final loggedIn = context.select<AuthService, bool>( final loggedIn = context.select<AuthService, bool>(
(auth) => auth.isLoggedIn, (auth) => auth.isLoggedIn,
); );
if (!endpointService.isLoaded) { if (!endpointService.isLoaded || !distanceUnitService.isLoaded) {
return const Scaffold( return const Scaffold(
body: Center(child: CircularProgressIndicator()), body: Center(child: CircularProgressIndicator()),
); );
@@ -204,6 +206,34 @@ class _SettingsPageState extends State<SettingsPage> {
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text(
'Distance units',
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 8),
Text(
'Choose how distances are displayed across the app.',
style: Theme.of(context).textTheme.bodySmall,
),
const SizedBox(height: 12),
SegmentedButton<DistanceUnit>(
segments: DistanceUnit.values
.map(
(unit) => ButtonSegment<DistanceUnit>(
value: unit,
label: Text(unit.label),
),
)
.toList(),
selected: {distanceUnitService.unit},
onSelectionChanged: (selection) {
final next = selection.first;
distanceUnitService.setUnit(next);
},
),
const SizedBox(height: 24),
Text( Text(
'API endpoint', 'API endpoint',
style: Theme.of(context).textTheme.titleMedium?.copyWith( style: Theme.of(context).textTheme.titleMedium?.copyWith(

View File

@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:intl/intl.dart'; import 'package:intl/intl.dart';
import 'package:mileograph_flutter/objects/objects.dart'; import 'package:mileograph_flutter/objects/objects.dart';
import 'package:mileograph_flutter/services/data_service.dart'; import 'package:mileograph_flutter/services/data_service.dart';
import 'package:mileograph_flutter/services/distance_unit_service.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
class StatsPage extends StatefulWidget { class StatsPage extends StatefulWidget {
@@ -12,7 +13,6 @@ class StatsPage extends StatefulWidget {
} }
class _StatsPageState extends State<StatsPage> { class _StatsPageState extends State<StatsPage> {
final NumberFormat _mileageFormat = NumberFormat('#,##0.##');
final NumberFormat _countFormat = NumberFormat.decimalPattern(); final NumberFormat _countFormat = NumberFormat.decimalPattern();
@override @override
@@ -30,16 +30,20 @@ class _StatsPageState extends State<StatsPage> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final data = context.watch<DataService>(); final data = context.watch<DataService>();
final distanceUnits = context.watch<DistanceUnitService>();
return Scaffold( return Scaffold(
appBar: AppBar(title: const Text('Stats')), appBar: AppBar(title: const Text('Stats')),
body: RefreshIndicator( body: RefreshIndicator(
onRefresh: () => _loadStats(force: true), onRefresh: () => _loadStats(force: true),
child: _buildContent(data), child: _buildContent(data, distanceUnits),
), ),
); );
} }
Widget _buildContent(DataService data) { Widget _buildContent(
DataService data,
DistanceUnitService distanceUnits,
) {
final stats = data.aboutStats; final stats = data.aboutStats;
final loading = data.isAboutStatsLoading; final loading = data.isAboutStatsLoading;
@@ -79,13 +83,14 @@ class _StatsPageState extends State<StatsPage> {
itemBuilder: (context, index) { itemBuilder: (context, index) {
return Padding( return Padding(
padding: EdgeInsets.only(bottom: index == years.length - 1 ? 0 : 12), padding: EdgeInsets.only(bottom: index == years.length - 1 ? 0 : 12),
child: _buildYearCard(context, years[index]), child: _buildYearCard(context, years[index], distanceUnits),
); );
}, },
); );
} }
Widget _buildYearCard(BuildContext context, StatsYear year) { Widget _buildYearCard(
BuildContext context, StatsYear year, DistanceUnitService distanceUnits) {
final theme = Theme.of(context); final theme = Theme.of(context);
return Card( return Card(
child: Padding( child: Padding(
@@ -109,7 +114,7 @@ class _StatsPageState extends State<StatsPage> {
_buildInfoChip( _buildInfoChip(
context, context,
label: 'Mileage', label: 'Mileage',
value: '${_mileageFormat.format(year.mileage)} mi', value: distanceUnits.format(year.mileage, decimals: 1),
), ),
_buildInfoChip( _buildInfoChip(
context, context,
@@ -130,7 +135,9 @@ class _StatsPageState extends State<StatsPage> {
dense: true, dense: true,
contentPadding: const EdgeInsets.symmetric(horizontal: 8), contentPadding: const EdgeInsets.symmetric(horizontal: 8),
title: Text(item.locoClass), title: Text(item.locoClass),
trailing: Text('${_mileageFormat.format(item.mileage)} mi'), trailing: Text(
distanceUnits.format(item.mileage, decimals: 1),
),
), ),
), ),
_buildSection<StatsNetworkMileage>( _buildSection<StatsNetworkMileage>(
@@ -142,7 +149,9 @@ class _StatsPageState extends State<StatsPage> {
dense: true, dense: true,
contentPadding: const EdgeInsets.symmetric(horizontal: 8), contentPadding: const EdgeInsets.symmetric(horizontal: 8),
title: Text(item.network), title: Text(item.network),
trailing: Text('${_mileageFormat.format(item.mileage)} mi'), trailing: Text(
distanceUnits.format(item.mileage, decimals: 1),
),
), ),
), ),
_buildSection<StatsStationVisits>( _buildSection<StatsStationVisits>(

View File

@@ -6,6 +6,7 @@ import 'package:go_router/go_router.dart';
import 'package:mileograph_flutter/components/traction/traction_card.dart'; import 'package:mileograph_flutter/components/traction/traction_card.dart';
import 'package:mileograph_flutter/objects/objects.dart'; import 'package:mileograph_flutter/objects/objects.dart';
import 'package:mileograph_flutter/services/data_service.dart'; import 'package:mileograph_flutter/services/data_service.dart';
import 'package:mileograph_flutter/services/distance_unit_service.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';

View File

@@ -37,6 +37,9 @@ class _TractionPageState extends State<TractionPage> {
final Map<String, TextEditingController> _dynamicControllers = {}; final Map<String, TextEditingController> _dynamicControllers = {};
final Map<String, String?> _enumSelections = {}; final Map<String, String?> _enumSelections = {};
bool _restoredFromPrefs = false; bool _restoredFromPrefs = false;
static const int _pageSize = 100;
int _lastTractionOffset = 0;
String? _lastQuerySignature;
@override @override
void initState() { void initState() {
@@ -59,6 +62,9 @@ class _TractionPageState extends State<TractionPage> {
Future<void> _initialLoad() async { Future<void> _initialLoad() async {
final data = context.read<DataService>(); final data = context.read<DataService>();
await _restoreSearchState(); await _restoreSearchState();
if (_lastTractionOffset == 0 && data.traction.length > _pageSize) {
_lastTractionOffset = data.traction.length - _pageSize;
}
data.fetchClassList(); data.fetchClassList();
data.fetchEventFields(); data.fetchEventFields();
await _refreshTraction(); await _refreshTraction();
@@ -103,7 +109,29 @@ class _TractionPageState extends State<TractionPage> {
dynamicFieldsUsed; dynamicFieldsUsed;
} }
Future<void> _refreshTraction({bool append = false}) async { String _tractionQuerySignature(
Map<String, dynamic> filters,
bool hadOnly,
) {
final sortedKeys = filters.keys.toList()..sort();
final filterSignature = sortedKeys
.map((key) => '$key=${filters[key]}')
.join('|');
final classQuery = (_selectedClass ?? _classController.text).trim();
return [
'class=$classQuery',
'number=${_numberController.text.trim()}',
'name=${_nameController.text.trim()}',
'mileageFirst=$_mileageFirst',
'hadOnly=$hadOnly',
'filters=$filterSignature',
].join(';');
}
Future<void> _refreshTraction({
bool append = false,
bool preservePosition = true,
}) async {
final data = context.read<DataService>(); final data = context.read<DataService>();
final filters = <String, dynamic>{}; final filters = <String, dynamic>{};
final name = _nameController.text.trim(); final name = _nameController.text.trim();
@@ -118,15 +146,49 @@ class _TractionPageState extends State<TractionPage> {
} }
}); });
final hadOnly = !_hasFilters; final hadOnly = !_hasFilters;
final signature = _tractionQuerySignature(filters, hadOnly);
final queryChanged =
_lastQuerySignature != null && signature != _lastQuerySignature;
_lastQuerySignature = signature;
if (queryChanged && !append) {
_lastTractionOffset = 0;
}
final shouldPreservePosition = preservePosition &&
!append &&
!queryChanged &&
_lastTractionOffset > 0;
int limit;
int offset;
if (append) {
offset = data.traction.length;
limit = _pageSize;
_lastTractionOffset = offset;
} else if (shouldPreservePosition) {
offset = 0;
limit = _pageSize + _lastTractionOffset;
} else {
offset = 0;
limit = _pageSize;
}
await data.fetchTraction( await data.fetchTraction(
hadOnly: hadOnly, hadOnly: hadOnly,
locoClass: _selectedClass ?? _classController.text.trim(), locoClass: _selectedClass ?? _classController.text.trim(),
locoNumber: _numberController.text.trim(), locoNumber: _numberController.text.trim(),
offset: append ? data.traction.length : 0, offset: offset,
limit: limit,
append: append, append: append,
filters: filters, filters: filters,
mileageFirst: _mileageFirst, mileageFirst: _mileageFirst,
); );
if (!append && !shouldPreservePosition) {
_lastTractionOffset = 0;
}
await _persistSearchState(); await _persistSearchState();
} }
@@ -639,6 +701,7 @@ class _TractionPageState extends State<TractionPage> {
Widget _buildClassStatsCard(BuildContext context) { Widget _buildClassStatsCard(BuildContext context) {
final scheme = Theme.of(context).colorScheme; final scheme = Theme.of(context).colorScheme;
final distanceUnits = context.watch<DistanceUnitService>();
if (_classStatsLoading) { if (_classStatsLoading) {
return Card( return Card(
child: Padding( child: Padding(
@@ -721,9 +784,27 @@ class _TractionPageState extends State<TractionPage> {
children: [ children: [
_metricTile('Had', hadCount), _metricTile('Had', hadCount),
_metricTile('Entries', entriesWithClass), _metricTile('Entries', entriesWithClass),
_metricTile('Avg mi / loco had', avgMileagePerLoco.toStringAsFixed(2)), _metricTile(
_metricTile('Avg mi / entry', avgMileagePerEntry.toStringAsFixed(2)), 'Avg distance / loco had',
_metricTile('Total mileage', totalMileage.toStringAsFixed(2)), distanceUnits.format(
avgMileagePerLoco,
decimals: 2,
),
),
_metricTile(
'Avg distance / entry',
distanceUnits.format(
avgMileagePerEntry,
decimals: 2,
),
),
_metricTile(
'Total distance',
distanceUnits.format(
totalMileage,
decimals: 2,
),
),
], ],
), ),
const SizedBox(height: 12), const SizedBox(height: 12),

View File

@@ -39,6 +39,16 @@ extension _TractionPersistence on _TractionPageState {
enumValues[entry.key.toString()] = entry.value?.toString(); enumValues[entry.key.toString()] = entry.value?.toString();
} }
} }
final lastOffsetRaw = decoded['lastOffset'];
if (lastOffsetRaw is int) {
_lastTractionOffset = lastOffsetRaw;
} else if (lastOffsetRaw is num) {
_lastTractionOffset = lastOffsetRaw.toInt();
}
final lastSig = decoded['querySignature']?.toString();
if (lastSig != null && lastSig.isNotEmpty) {
_lastQuerySignature = lastSig;
}
for (final entry in dynamicValues.entries) { for (final entry in dynamicValues.entries) {
_dynamicControllers.putIfAbsent( _dynamicControllers.putIfAbsent(
@@ -76,6 +86,8 @@ extension _TractionPersistence on _TractionPageState {
'showAdvancedFilters': _showAdvancedFilters, 'showAdvancedFilters': _showAdvancedFilters,
'dynamic': _dynamicControllers.map((k, v) => MapEntry(k, v.text)), 'dynamic': _dynamicControllers.map((k, v) => MapEntry(k, v.text)),
'enum': _enumSelections, 'enum': _enumSelections,
'lastOffset': _lastTractionOffset,
'querySignature': _lastQuerySignature,
}; };
try { try {

View File

@@ -1,6 +1,7 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:mileograph_flutter/objects/objects.dart'; import 'package:mileograph_flutter/objects/objects.dart';
import 'package:mileograph_flutter/services/data_service.dart'; import 'package:mileograph_flutter/services/data_service.dart';
import 'package:mileograph_flutter/services/distance_unit_service.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
class TripsPage extends StatefulWidget { class TripsPage extends StatefulWidget {
@@ -99,6 +100,7 @@ class _TripsPageState extends State<TripsPage> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final data = context.watch<DataService>(); final data = context.watch<DataService>();
final distanceUnits = context.watch<DistanceUnitService>();
final tripDetails = data.tripDetails; final tripDetails = data.tripDetails;
final tripSummaries = data.tripList; final tripSummaries = data.tripList;
final summaryById = { final summaryById = {
@@ -188,7 +190,8 @@ class _TripsPageState extends State<TripsPage> {
return Card( return Card(
child: ListTile( child: ListTile(
title: Text(trip.tripName), title: Text(trip.tripName),
subtitle: Text('${trip.tripMileage.toStringAsFixed(1)} mi'), subtitle:
Text(distanceUnits.format(trip.tripMileage, decimals: 1)),
), ),
); );
} }
@@ -206,6 +209,7 @@ class _TripsPageState extends State<TripsPage> {
TripDetail trip, TripDetail trip,
TripSummary? summary, TripSummary? summary,
) { ) {
final distanceUnits = context.watch<DistanceUnitService>();
final legs = trip.legs; final legs = trip.legs;
final legCount = final legCount =
trip.legCount > 0 ? trip.legCount : summary?.legCount ?? legs.length; trip.legCount > 0 ? trip.legCount : summary?.legCount ?? legs.length;
@@ -228,7 +232,7 @@ class _TripsPageState extends State<TripsPage> {
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text( Text(
'Trip', 'Trip #${trip.id}',
style: Theme.of(context).textTheme.labelMedium, style: Theme.of(context).textTheme.labelMedium,
), ),
const SizedBox(height: 4), const SizedBox(height: 4),
@@ -245,18 +249,12 @@ class _TripsPageState extends State<TripsPage> {
crossAxisAlignment: CrossAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.end,
children: [ children: [
Text( Text(
trip.mileage.toStringAsFixed(1), distanceUnits.format(trip.mileage, decimals: 1),
style: style:
Theme.of(context).textTheme.headlineSmall?.copyWith( Theme.of(context).textTheme.headlineSmall?.copyWith(
fontWeight: FontWeight.w800, fontWeight: FontWeight.w800,
), ),
), ),
Text(
'miles',
style: Theme.of(context).textTheme.labelMedium?.copyWith(
color: Theme.of(context).textTheme.bodySmall?.color,
),
),
], ],
), ),
], ],
@@ -367,6 +365,7 @@ class _TripsPageState extends State<TripsPage> {
} }
void _showTripDetail(BuildContext context, TripDetail trip) { void _showTripDetail(BuildContext context, TripDetail trip) {
final distanceUnits = context.read<DistanceUnitService>();
showModalBottomSheet( showModalBottomSheet(
context: context, context: context,
isScrollControlled: true, isScrollControlled: true,
@@ -491,7 +490,9 @@ class _TripsPageState extends State<TripsPage> {
), ),
], ],
const SizedBox(width: 4), const SizedBox(width: 4),
Text('${trip.mileage.toStringAsFixed(1)} mi'), Text(
distanceUnits.format(trip.mileage, decimals: 1),
),
], ],
), ),
const SizedBox(height: 8), const SizedBox(height: 8),
@@ -506,7 +507,12 @@ class _TripsPageState extends State<TripsPage> {
title: Text('${leg.start}${leg.end}'), title: Text('${leg.start}${leg.end}'),
subtitle: Text(_formatDate(leg.beginTime)), subtitle: Text(_formatDate(leg.beginTime)),
trailing: Text( trailing: Text(
leg.mileage?.toStringAsFixed(1) ?? '-', leg.mileage == null
? '-'
: distanceUnits.format(
leg.mileage!,
decimals: 1,
),
style: Theme.of(context).textTheme.labelLarge style: Theme.of(context).textTheme.labelLarge
?.copyWith(fontWeight: FontWeight.bold), ?.copyWith(fontWeight: FontWeight.bold),
), ),
@@ -529,6 +535,7 @@ class _TripsPageState extends State<TripsPage> {
TripDetail trip, TripDetail trip,
TripSummary? summary, TripSummary? summary,
) { ) {
final distanceUnits = context.read<DistanceUnitService>();
showModalBottomSheet( showModalBottomSheet(
context: context, context: context,
isScrollControlled: true, isScrollControlled: true,
@@ -561,7 +568,9 @@ class _TripsPageState extends State<TripsPage> {
?.copyWith(fontWeight: FontWeight.bold), ?.copyWith(fontWeight: FontWeight.bold),
), ),
const Spacer(), const Spacer(),
Text('${trip.mileage.toStringAsFixed(1)} mi'), Text(
distanceUnits.format(trip.mileage, decimals: 1),
),
], ],
), ),
const SizedBox(height: 8), const SizedBox(height: 8),

View File

@@ -1,5 +1,8 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:mileograph_flutter/objects/objects.dart'; import 'package:mileograph_flutter/objects/objects.dart';
import 'package:mileograph_flutter/services/api_service.dart';
import 'package:mileograph_flutter/services/distance_unit_service.dart';
import 'package:provider/provider.dart';
class TractionCard extends StatelessWidget { class TractionCard extends StatelessWidget {
const TractionCard({ const TractionCard({
@@ -28,6 +31,7 @@ class TractionCard extends StatelessWidget {
final domain = loco.domain ?? ''; final domain = loco.domain ?? '';
final hasMileageOrTrips = _hasMileageOrTrips(loco); final hasMileageOrTrips = _hasMileageOrTrips(loco);
final statusColors = _statusChipColors(context, status); final statusColors = _statusChipColors(context, status);
final distanceUnits = context.watch<DistanceUnitService>();
return Card( return Card(
child: Padding( child: Padding(
@@ -151,8 +155,11 @@ class TractionCard extends StatelessWidget {
children: [ children: [
_statPill( _statPill(
context, context,
label: 'Miles', label: 'Distance',
value: _formatNumber(loco.mileage), value: distanceUnits.format(
loco.mileage ?? 0,
decimals: 1,
),
), ),
_statPill( _statPill(
context, context,
@@ -203,6 +210,12 @@ Future<void> showTractionDetails(
LocoSummary loco, LocoSummary loco,
) async { ) async {
final hasMileageOrTrips = _hasMileageOrTrips(loco); final hasMileageOrTrips = _hasMileageOrTrips(loco);
final distanceUnits = context.read<DistanceUnitService>();
final api = context.read<ApiService>();
final leaderboardId = _leaderboardId(loco);
final leaderboardFuture = leaderboardId == null
? Future.value(const <LeaderboardEntry>[])
: _fetchLocoLeaderboard(api, leaderboardId);
await showModalBottomSheet( await showModalBottomSheet(
context: context, context: context,
isScrollControlled: true, isScrollControlled: true,
@@ -275,7 +288,10 @@ Future<void> showTractionDetails(
_detailRow( _detailRow(
context, context,
'Mileage', 'Mileage',
_formatNumber(loco.mileage ?? 0), distanceUnits.format(
loco.mileage ?? 0,
decimals: 1,
),
), ),
_detailRow( _detailRow(
context, context,
@@ -285,6 +301,63 @@ Future<void> showTractionDetails(
_detailRow(context, 'EVN', loco.evn ?? ''), _detailRow(context, 'EVN', loco.evn ?? ''),
if (loco.notes != null && loco.notes!.isNotEmpty) if (loco.notes != null && loco.notes!.isNotEmpty)
_detailRow(context, 'Notes', loco.notes!), _detailRow(context, 'Notes', loco.notes!),
const SizedBox(height: 16),
Text(
'Leaderboard',
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 8),
FutureBuilder<List<LeaderboardEntry>>(
future: leaderboardFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Padding(
padding: EdgeInsets.symmetric(vertical: 12.0),
child: Center(
child: SizedBox(
height: 24,
width: 24,
child: CircularProgressIndicator(strokeWidth: 2),
),
),
);
}
if (snapshot.hasError) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: Text(
'Failed to load leaderboard',
style: Theme.of(context).textTheme.labelMedium?.copyWith(
color: Theme.of(context).colorScheme.error,
),
),
);
}
final entries = snapshot.data ?? const <LeaderboardEntry>[];
if (entries.isEmpty) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: Text(
'No mileage leaderboard yet.',
style: Theme.of(context).textTheme.bodyMedium,
),
);
}
return Column(
children: entries.asMap().entries.map((entry) {
final rank = entry.key + 1;
return _leaderboardRow(
context,
rank,
entry.value,
distanceUnits,
);
}).toList(),
);
},
),
], ],
), ),
), ),
@@ -297,6 +370,105 @@ Future<void> showTractionDetails(
); );
} }
Future<List<LeaderboardEntry>> _fetchLocoLeaderboard(
ApiService api,
int locoId,
) async {
try {
final json = await api.get('/loco/leaderboard/id/$locoId');
Iterable<dynamic>? raw;
if (json is List) {
raw = json;
} else if (json is Map) {
for (final key in ['data', 'leaderboard', 'results']) {
final value = json[key];
if (value is List) {
raw = value;
break;
}
}
}
if (raw == null) return const [];
return raw.whereType<Map>().map((e) {
return LeaderboardEntry.fromJson(
e.map((key, value) => MapEntry(key.toString(), value)),
);
}).toList();
} catch (e) {
debugPrint('Failed to fetch loco leaderboard for $locoId: $e');
rethrow;
}
}
int? _leaderboardId(LocoSummary loco) {
int? parse(dynamic value) {
if (value == null) return null;
if (value is int) return value == 0 ? null : value;
if (value is num) return value.toInt() == 0 ? null : value.toInt();
return int.tryParse(value.toString());
}
return parse(loco.extra['loco_id']) ??
parse(loco.extra['id']) ??
parse(loco.id);
}
Widget _leaderboardRow(
BuildContext context,
int rank,
LeaderboardEntry entry,
DistanceUnitService distanceUnits,
) {
final theme = Theme.of(context);
final primaryName =
entry.userFullName.isNotEmpty ? entry.userFullName : entry.username;
final mileageLabel = distanceUnits.format(entry.mileage, decimals: 1);
return Padding(
padding: const EdgeInsets.symmetric(vertical: 6.0),
child: Row(
children: [
Container(
width: 36,
height: 36,
alignment: Alignment.center,
decoration: BoxDecoration(
color: theme.colorScheme.primaryContainer,
borderRadius: BorderRadius.circular(10),
),
child: Text(
'#$rank',
style: theme.textTheme.labelMedium?.copyWith(
fontWeight: FontWeight.w700,
color: theme.colorScheme.onPrimaryContainer,
),
),
),
const SizedBox(width: 10),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
primaryName,
style: theme.textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
],
),
),
Text(
mileageLabel,
style: theme.textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
],
),
);
}
Widget _detailRow(BuildContext context, String label, String value) { Widget _detailRow(BuildContext context, String label, String value) {
if (value.isEmpty) return const SizedBox.shrink(); if (value.isEmpty) return const SizedBox.shrink();
return Padding( return Padding(
@@ -368,8 +540,3 @@ bool _hasMileageOrTrips(LocoSummary loco) {
final trips = loco.trips ?? loco.journeys ?? 0; final trips = loco.trips ?? loco.journeys ?? 0;
return mileage > 0 || trips > 0; return mileage > 0 || trips > 0;
} }
String _formatNumber(double? value) {
if (value == null) return '0';
return value.toStringAsFixed(1);
}

View File

@@ -0,0 +1,127 @@
import 'package:flutter/material.dart';
import 'package:mileograph_flutter/objects/objects.dart';
import 'package:mileograph_flutter/services/data_service.dart';
import 'package:provider/provider.dart';
class FriendRequestNotificationCard extends StatelessWidget {
const FriendRequestNotificationCard({super.key, required this.notification});
final UserNotification notification;
@override
Widget build(BuildContext context) {
final data = context.read<DataService>();
final friendshipId = notification.body.trim();
if (friendshipId.isEmpty) {
return const Text('Invalid friend request notification.');
}
final future = data.fetchFriendshipById(friendshipId);
return FutureBuilder<Friendship?>(
future: future,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Padding(
padding: EdgeInsets.symmetric(vertical: 6.0),
child: SizedBox(
height: 20,
width: 20,
child: CircularProgressIndicator(strokeWidth: 2),
),
);
}
if (snapshot.hasError) {
return const Text('Failed to load request details.');
}
final friendship = snapshot.data;
final requester = friendship?.requester;
if (friendship == null || requester == null) {
return const Text('Friend request details unavailable.');
}
final buttonStyle = ElevatedButton.styleFrom(
minimumSize: const Size(0, 36),
);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
const Icon(Icons.person_add_alt, size: 18),
const SizedBox(width: 6),
Text(
requester.displayName.isNotEmpty
? requester.displayName
: '@${requester.username}',
style: Theme.of(context).textTheme.titleSmall,
),
],
),
const SizedBox(height: 6),
Wrap(
spacing: 8,
children: [
ElevatedButton(
style: buttonStyle,
onPressed: () =>
_respond(context, friendship.id, accept: true),
child: const Text('Accept'),
),
ElevatedButton(
style: buttonStyle,
onPressed: () =>
_respond(context, friendship.id, accept: false),
child: const Text('Reject'),
),
],
),
],
);
},
);
}
Future<void> _respond(
BuildContext context,
String? friendshipId, {
required bool accept,
}) async {
if (friendshipId == null || friendshipId.isEmpty) return;
final data = context.read<DataService>();
final messenger = ScaffoldMessenger.maybeOf(context);
try {
if (accept) {
await data.acceptFriendship(friendshipId);
if (!context.mounted) return;
messenger?.showSnackBar(
const SnackBar(content: Text('Friend request accepted')),
);
await _dismissNotification(context, messenger);
} else {
await data.rejectFriendship(friendshipId);
if (!context.mounted) return;
messenger?.showSnackBar(
const SnackBar(content: Text('Friend request rejected')),
);
await _dismissNotification(context, messenger);
}
await data.fetchPendingFriendships();
} catch (e) {
if (!context.mounted) return;
messenger?.showSnackBar(
SnackBar(content: Text('Failed to respond: $e')),
);
}
}
Future<void> _dismissNotification(
BuildContext context,
ScaffoldMessengerState? messenger,
) async {
try {
await context.read<DataService>().dismissNotifications([notification.id]);
} catch (e) {
messenger?.showSnackBar(
SnackBar(content: Text('Failed to dismiss notification: $e')),
);
}
}
}

View File

@@ -0,0 +1,147 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:mileograph_flutter/objects/objects.dart';
import 'package:mileograph_flutter/services/data_service.dart';
import 'package:provider/provider.dart';
class LegShareNotificationCard extends StatelessWidget {
const LegShareNotificationCard({super.key, required this.notification});
final UserNotification notification;
@override
Widget build(BuildContext context) {
final data = context.read<DataService>();
final legShareId = notification.body.trim();
if (legShareId.isEmpty) {
return const Text('Invalid leg share notification.');
}
final future = data.fetchLegShare(legShareId);
return FutureBuilder<LegShareData?>(
future: future,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Padding(
padding: EdgeInsets.symmetric(vertical: 6.0),
child: SizedBox(
height: 20,
width: 20,
child: CircularProgressIndicator(strokeWidth: 2),
),
);
}
if (snapshot.hasError) {
return const Text('Failed to load shared entry.');
}
final share = snapshot.data;
final entry = share?.entry;
if (share == null || entry == null) {
return const Text('Shared entry unavailable.');
}
final begin = entry.beginTime;
final beginStr =
'${begin.year.toString().padLeft(4, '0')}-${begin.month.toString().padLeft(2, '0')}-${begin.day.toString().padLeft(2, '0')} ${begin.hour.toString().padLeft(2, '0')}:${begin.minute.toString().padLeft(2, '0')}';
final start = entry.route.isNotEmpty ? entry.route.first : entry.start;
final end = entry.route.isNotEmpty ? entry.route.last : entry.end;
final sharedAt = share.sharedAt;
final sharedAtStr = sharedAt == null
? null
: '${sharedAt.year.toString().padLeft(4, '0')}-${sharedAt.month.toString().padLeft(2, '0')}-${sharedAt.day.toString().padLeft(2, '0')} ${sharedAt.hour.toString().padLeft(2, '0')}:${sharedAt.minute.toString().padLeft(2, '0')}';
final from = share.sharedFromName;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('$beginStr$start$end'),
if (from.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 4.0),
child: Text(
'From $from',
style: Theme.of(context).textTheme.bodySmall,
),
),
if (sharedAtStr != null)
Padding(
padding: const EdgeInsets.only(top: 4.0),
child: Text(
'Shared at $sharedAtStr',
style: Theme.of(context).textTheme.bodySmall,
),
),
const SizedBox(height: 8),
Wrap(
spacing: 8,
runSpacing: 8,
children: [
ElevatedButton(
onPressed: () => _accept(context, share),
child: const Text('Accept'),
),
OutlinedButton(
onPressed: () => _inspect(context, share),
child: const Text('Inspect'),
),
TextButton(
onPressed: () => _reject(context, share),
child: const Text('Reject'),
),
],
),
],
);
},
);
}
Future<void> _accept(BuildContext context, LegShareData share) async {
final data = context.read<DataService>();
final messenger = ScaffoldMessenger.maybeOf(context);
try {
await data.acceptLegShare(share);
if (!context.mounted) return;
await data.dismissNotifications([notification.id]);
// Refresh legs in the background.
unawaited(data.refreshLegs());
messenger?.showSnackBar(
const SnackBar(content: Text('Shared entry added to logbook')),
);
} catch (e) {
messenger?.showSnackBar(
SnackBar(content: Text('Failed to add shared entry: $e')),
);
}
}
Future<void> _reject(BuildContext context, LegShareData share) async {
final data = context.read<DataService>();
final messenger = ScaffoldMessenger.maybeOf(context);
try {
await data.rejectLegShare(share.id);
if (!context.mounted) return;
await data.dismissNotifications([notification.id]);
messenger?.showSnackBar(
const SnackBar(content: Text('Share rejected')),
);
} catch (e) {
messenger?.showSnackBar(
SnackBar(content: Text('Failed to reject share: $e')),
);
}
}
Future<void> _inspect(BuildContext context, LegShareData share) async {
final router = GoRouter.of(context);
// Close notifications panel if open.
if (Navigator.canPop(context)) {
Navigator.of(context).pop();
}
await Future<void>.delayed(Duration.zero);
final target = share.copyWith(notificationId: notification.id);
final ts = DateTime.now().millisecondsSinceEpoch;
final path = '/add?share=${Uri.encodeComponent(share.id)}&ts=$ts';
router.go(path, extra: target);
}
}

View File

@@ -66,6 +66,29 @@ DateTime _asDateTime(dynamic value, [DateTime? fallback]) {
return parsed ?? (fallback ?? DateTime.fromMillisecondsSinceEpoch(0)); return parsed ?? (fallback ?? DateTime.fromMillisecondsSinceEpoch(0));
} }
DateTime? _asNullableDateTime(dynamic value) {
if (value == null) return null;
if (value is DateTime) return value;
return DateTime.tryParse(value.toString());
}
int compareTripsByDateDesc(
DateTime? aDate,
DateTime? bDate,
int aId,
int bId,
) {
if (aDate != null && bDate != null) {
final cmp = bDate.compareTo(aDate);
if (cmp != 0) return cmp;
} else if (aDate != null) {
return -1;
} else if (bDate != null) {
return 1;
}
return bId.compareTo(aId);
}
class DestinationObject { class DestinationObject {
const DestinationObject( const DestinationObject(
this.label, this.label,
@@ -81,24 +104,245 @@ class DestinationObject {
} }
class UserData { class UserData {
const UserData(this.username, this.fullName, this.userId, this.email); const UserData({
required this.username,
required this.fullName,
required this.userId,
required this.email,
bool? elevated,
bool? disabled,
}) : elevated = elevated ?? false,
disabled = disabled ?? false;
final String userId; final String userId;
final String username; final String username;
final String fullName; final String fullName;
final String email; final String email;
final bool elevated;
final bool disabled;
} }
class AuthenticatedUserData extends UserData { class AuthenticatedUserData extends UserData {
const AuthenticatedUserData({ const AuthenticatedUserData({
required String userId, required super.userId,
required String username, required super.username,
required String fullName, required super.fullName,
required String email, required super.email,
bool? elevated,
bool? isElevated,
bool? disabled,
bool? isDisabled,
required this.accessToken, required this.accessToken,
}) : super(username, fullName, userId, email); }) : super(
elevated: (elevated ?? false) || (isElevated ?? false),
disabled: (disabled ?? false) || (isDisabled ?? false),
);
final String accessToken; final String accessToken;
bool get isElevated => elevated;
}
class UserSummary extends UserData {
const UserSummary({
required super.username,
required super.fullName,
required super.userId,
required super.email,
super.elevated = false,
super.disabled = false,
});
String get displayName => fullName.isNotEmpty ? fullName : username;
factory UserSummary.fromJson(Map<String, dynamic> json) => UserSummary(
username: _asString(json['username'] ?? json['user_name']),
fullName: _asString(json['full_name'] ?? json['name']),
userId: _asString(json['user_id'] ?? json['id']),
email: _asString(json['email']),
elevated: _asBool(json['elevated'] ?? json['is_elevated'], false),
disabled: _asBool(json['disabled'], false),
);
}
class Friendship {
final String? id;
final String status;
final String requesterId;
final String addresseeId;
final UserSummary? requester;
final UserSummary? addressee;
final DateTime? requestedAt;
final DateTime? respondedAt;
const Friendship({
required this.id,
required this.status,
required this.requesterId,
required this.addresseeId,
this.requester,
this.addressee,
this.requestedAt,
this.respondedAt,
});
String get _statusLower => status.toLowerCase();
bool get isNone => _statusLower == 'none';
bool get isPending => _statusLower == 'pending';
bool get isAccepted => _statusLower == 'accepted';
bool get isBlocked => _statusLower == 'blocked';
bool get isDeclined =>
_statusLower == 'declined' || _statusLower == 'rejected';
factory Friendship.fromJson(Map<String, dynamic> json) {
DateTime? parseDate(dynamic value) {
if (value is DateTime) return value;
return DateTime.tryParse(value?.toString() ?? '');
}
String pickId(Map<String, dynamic> map, List<String> keys) {
for (final key in keys) {
final value = map[key];
if (value == null) continue;
final str = value.toString();
if (str.isNotEmpty) return str;
}
return '';
}
UserSummary? parseUser(dynamic raw, {String? usernameKey, String? fullKey, String? idKey}) {
if (raw is Map) {
return UserSummary.fromJson(
raw.map((key, value) => MapEntry(key.toString(), value)),
);
}
final username = usernameKey != null ? _asString(json[usernameKey]) : '';
final fullName = fullKey != null ? _asString(json[fullKey]) : '';
final id = idKey != null ? _asString(json[idKey]) : '';
if (username.isEmpty && fullName.isEmpty && id.isEmpty) return null;
return UserSummary(
username: username,
fullName: fullName,
userId: id,
email: '',
);
}
final requesterJson = json['requester'] ??
json['requestor'] ??
json['sender'] ??
json['from_user'];
final addresseeJson = json['addressee'] ??
json['receiver'] ??
json['target_user'] ??
json['to_user'];
final requester = parseUser(
requesterJson,
usernameKey: 'requester_username',
fullKey: 'requester_full_name',
idKey: 'requester_id',
);
final addressee = parseUser(
addresseeJson,
usernameKey: 'addressee_username',
fullKey: 'addressee_full_name',
idKey: 'addressee_id',
);
final requesterUsername = _asString(json['requester_username']);
final requesterFullName = _asString(json['requester_full_name']);
final addresseeUsername = _asString(json['addressee_username']);
final addresseeFullName = _asString(json['addressee_full_name']);
final requesterId = requester?.userId.isNotEmpty == true
? requester!.userId
: pickId(json, [
'requester_id',
'requestor_id',
'requestorId',
'sender_id',
'from_user_id',
'from_id',
'user_id',
]);
final addresseeId = addressee?.userId.isNotEmpty == true
? addressee!.userId
: pickId(json, [
'addressee_id',
'addresseeId',
'receiver_id',
'target_user_id',
'to_user_id',
'to_id',
]);
final normalizedStatus = _asString(json['status'], 'none').trim();
return Friendship(
id: pickId(json, ['friendship_id', 'friendshipId', 'id']),
status: normalizedStatus.isNotEmpty ? normalizedStatus : 'none',
requesterId: requesterId,
addresseeId: addresseeId,
requester: requester ??
(requesterUsername.isNotEmpty || requesterFullName.isNotEmpty
? UserSummary(
username: requesterUsername,
fullName: requesterFullName,
userId: requesterId,
email: '',
)
: null),
addressee: addressee ??
(addresseeUsername.isNotEmpty || addresseeFullName.isNotEmpty
? UserSummary(
username: addresseeUsername,
fullName: addresseeFullName,
userId: addresseeId,
email: '',
)
: null),
requestedAt: parseDate(json['requested_at'] ?? json['requestedAt']),
respondedAt: parseDate(json['responded_at'] ?? json['respondedAt']),
);
}
factory Friendship.fromStatusJson(
Map<String, dynamic> json, {
String? targetUserId,
}) {
final statusVal = _asString(json['status'], 'none').trim();
if (statusVal.toLowerCase() == 'none') {
return Friendship(
id: null,
status: 'none',
requesterId: '',
addresseeId: targetUserId ?? '',
);
}
return Friendship.fromJson(json);
}
Friendship copyWith({
String? id,
String? status,
String? requesterId,
String? addresseeId,
UserSummary? requester,
UserSummary? addressee,
DateTime? requestedAt,
DateTime? respondedAt,
}) {
return Friendship(
id: id ?? this.id,
status: status ?? this.status,
requesterId: requesterId ?? this.requesterId,
addresseeId: addresseeId ?? this.addresseeId,
requester: requester ?? this.requester,
addressee: addressee ?? this.addressee,
requestedAt: requestedAt ?? this.requestedAt,
respondedAt: respondedAt ?? this.respondedAt,
);
}
} }
class HomepageStats { class HomepageStats {
@@ -147,10 +391,13 @@ class HomepageStats {
user: userData == null user: userData == null
? null ? null
: UserData( : UserData(
userData['username'] ?? '', username: userData['username'] ?? '',
userData['full_name'] ?? '', fullName: userData['full_name'] ?? '',
userData['user_id'] ?? '', userId: userData['user_id'] ?? '',
userData['email'] ?? '', email: userData['email'] ?? '',
elevated:
_asBool(userData['elevated'] ?? userData['is_elevated'], false),
disabled: _asBool(userData['disabled'], false),
), ),
); );
} }
@@ -375,6 +622,7 @@ class Loco {
final String type, number, locoClass; final String type, number, locoClass;
final String? name, operator, notes, evn; final String? name, operator, notes, evn;
final bool powering; final bool powering;
final int allocPos;
Loco({ Loco({
required this.id, required this.id,
@@ -386,6 +634,7 @@ class Loco {
this.notes, this.notes,
this.evn, this.evn,
this.powering = true, this.powering = true,
this.allocPos = 0,
}); });
factory Loco.fromJson(Map<String, dynamic> json) => Loco( factory Loco.fromJson(Map<String, dynamic> json) => Loco(
@@ -398,6 +647,7 @@ class Loco {
notes: json['notes'], notes: json['notes'],
evn: json['evn'], evn: json['evn'],
powering: _asBool(json['alloc_powering'] ?? json['powering'], true), powering: _asBool(json['alloc_powering'] ?? json['powering'], true),
allocPos: _asInt(json['alloc_pos'], 0),
); );
} }
@@ -431,6 +681,7 @@ class LocoSummary extends Loco {
this.location, this.location,
Map<String, dynamic>? extra, Map<String, dynamic>? extra,
super.powering = true, super.powering = true,
super.allocPos = 0,
}) : extra = extra ?? const {}, }) : extra = extra ?? const {},
super( super(
id: locoId, id: locoId,
@@ -443,7 +694,7 @@ class LocoSummary extends Loco {
); );
factory LocoSummary.fromJson(Map<String, dynamic> json) => LocoSummary( factory LocoSummary.fromJson(Map<String, dynamic> json) => LocoSummary(
locoId: json['loco_id'] ?? json['id'] ?? 0, locoId: _asInt(json['loco_id'] ?? json['id']),
locoType: json['type'] ?? json['loco_type'] ?? '', locoType: json['type'] ?? json['loco_type'] ?? '',
locoNumber: json['number'] ?? json['loco_number'] ?? '', locoNumber: json['number'] ?? json['loco_number'] ?? '',
locoName: json['name'] ?? json['loco_name'] ?? "", locoName: json['name'] ?? json['loco_name'] ?? "",
@@ -466,6 +717,7 @@ class LocoSummary extends Loco {
location: json['location'], location: json['location'],
extra: Map<String, dynamic>.from(json), extra: Map<String, dynamic>.from(json),
powering: _asBool(json['alloc_powering'] ?? json['powering'], true), powering: _asBool(json['alloc_powering'] ?? json['powering'], true),
allocPos: _asInt(json['alloc_pos'], 0),
); );
} }
@@ -722,9 +974,12 @@ class TripSummary {
final double tripMileage; final double tripMileage;
final int legCount; final int legCount;
final List<TripLocoStat> locoStats; final List<TripLocoStat> locoStats;
final DateTime? startDate;
final DateTime? endDate;
int get locoHadCount => locoStats.length; int get locoHadCount => locoStats.length;
int get winnersCount => locoStats.where((e) => e.won).length; int get winnersCount => locoStats.where((e) => e.won).length;
DateTime? get primaryDate => endDate ?? startDate;
TripSummary({ TripSummary({
required this.tripId, required this.tripId,
@@ -732,9 +987,58 @@ class TripSummary {
required this.tripMileage, required this.tripMileage,
this.legCount = 0, this.legCount = 0,
List<TripLocoStat>? locoStats, List<TripLocoStat>? locoStats,
this.startDate,
this.endDate,
}) : locoStats = locoStats ?? const []; }) : locoStats = locoStats ?? const [];
factory TripSummary.fromJson(Map<String, dynamic> json) => TripSummary( static int compareByDateDesc(TripSummary a, TripSummary b) =>
compareTripsByDateDesc(a.primaryDate, b.primaryDate, a.tripId, b.tripId);
factory TripSummary.fromJson(Map<String, dynamic> json) {
DateTime? startDate;
DateTime? endDate;
DateTime? parseDate(dynamic value) => _asNullableDateTime(value);
for (final key in [
'trip_begin_time',
'trip_start',
'trip_start_time',
'trip_date',
'start_date',
'date',
]) {
startDate ??= parseDate(json[key]);
}
for (final key in [
'trip_end_time',
'trip_finish_time',
'trip_end',
'end_date',
]) {
endDate ??= parseDate(json[key]);
}
if (json['trip_legs'] is List) {
for (final leg in json['trip_legs'] as List) {
DateTime? begin;
if (leg is TripLeg) {
begin = leg.beginTime;
} else if (leg is Map) {
begin = parseDate(leg['leg_begin_time']);
}
if (begin == null) continue;
if (startDate == null || begin.isBefore(startDate)) {
startDate = begin;
}
if (endDate == null || begin.isAfter(endDate)) {
endDate = begin;
}
}
}
return TripSummary(
tripId: _asInt(json['trip_id']), tripId: _asInt(json['trip_id']),
tripName: _asString(json['trip_name']), tripName: _asString(json['trip_name']),
tripMileage: _asDouble(json['trip_mileage']), tripMileage: _asDouble(json['trip_mileage']),
@@ -745,7 +1049,10 @@ class TripSummary {
locoStats: TripLocoStat.listFromJson( locoStats: TripLocoStat.listFromJson(
json['stats'] ?? json['trip_locos'] ?? json['locos'], json['stats'] ?? json['trip_locos'] ?? json['locos'],
), ),
startDate: startDate,
endDate: endDate,
); );
}
} }
class Leg { class Leg {
@@ -753,6 +1060,7 @@ class Leg {
final String start, end, network, notes, headcode, user; final String start, end, network, notes, headcode, user;
final String origin, destination; final String origin, destination;
final List<String> route; final List<String> route;
final String? legShareId;
final DateTime beginTime; final DateTime beginTime;
final DateTime? endTime; final DateTime? endTime;
final DateTime? originTime; final DateTime? originTime;
@@ -783,6 +1091,7 @@ class Leg {
this.endDelayMinutes, this.endDelayMinutes,
this.origin = '', this.origin = '',
this.destination = '', this.destination = '',
this.legShareId,
}); });
factory Leg.fromJson(Map<String, dynamic> json) { factory Leg.fromJson(Map<String, dynamic> json) {
@@ -823,6 +1132,93 @@ class Leg {
: _asInt(json['leg_end_delay']), : _asInt(json['leg_end_delay']),
origin: _asString(json['leg_origin']), origin: _asString(json['leg_origin']),
destination: _asString(json['leg_destination']), destination: _asString(json['leg_destination']),
legShareId: _asString(json['leg_share_id']),
);
}
}
class LegShareData {
final String id;
final Leg entry;
final Map<String, dynamic> metadata;
final UserSummary? requester;
final UserSummary? addressee;
final DateTime? sharedAt;
final String status;
final int? notificationId;
LegShareData({
required this.id,
required this.entry,
required this.metadata,
this.requester,
this.addressee,
this.sharedAt,
this.status = 'pending',
this.notificationId,
});
LegShareData copyWith({int? notificationId}) {
return LegShareData(
id: id,
entry: entry,
metadata: metadata,
requester: requester,
addressee: addressee,
sharedAt: sharedAt,
status: status,
notificationId: notificationId ?? this.notificationId,
);
}
String get sharedFromName =>
requester?.displayName.isNotEmpty == true ? requester!.displayName : '';
factory LegShareData.fromJson(Map<String, dynamic> json) {
final metadataRaw = json['metadata'];
final entryRaw = json['entry'];
final metadata = metadataRaw is Map
? metadataRaw.map((k, v) => MapEntry(k.toString(), v))
: <String, dynamic>{};
final shareId = _asString(
metadata['leg_share_id'] ?? metadata['share_id'] ?? json['leg_share_id'],
);
final requester = UserSummary.fromJson({
"user_id": metadata['requester_id'] ?? metadata['from_user_id'] ?? '',
"username": metadata['requester_username'] ?? '',
"full_name": metadata['requester_full_name'] ?? '',
"email": '',
});
final addressee = UserSummary.fromJson({
"user_id": metadata['addressee_id'] ?? metadata['target_user_id'] ?? '',
"username": metadata['addressee_username'] ?? '',
"full_name": metadata['addressee_full_name'] ?? '',
"email": '',
});
DateTime? sharedAt;
for (final key in ['requested_at', 'created_at', 'shared_at']) {
final value = metadata[key];
if (value != null) {
sharedAt = DateTime.tryParse(value.toString());
if (sharedAt != null) break;
}
}
final entryMap = entryRaw is Map
? entryRaw.map((k, v) => MapEntry(k.toString(), v))
: json.map((k, v) => MapEntry(k.toString(), v));
final entryObj = Leg.fromJson(entryMap);
final resolvedId = shareId.isNotEmpty
? shareId
: entryObj.legShareId ?? _asString(json['leg_share_id']);
return LegShareData(
id: resolvedId,
entry: entryObj,
metadata: metadata,
requester: requester.userId.isEmpty ? null : requester,
addressee: addressee.userId.isEmpty ? null : addressee,
sharedAt: sharedAt,
status: _asString(metadata['status'], 'pending'),
); );
} }
} }
@@ -941,6 +1337,34 @@ class TripDetail {
int get locoHadCount => locoStats.length; int get locoHadCount => locoStats.length;
int get winnersCount => locoStats.where((e) => e.won).length; int get winnersCount => locoStats.where((e) => e.won).length;
DateTime? get startDate {
DateTime? earliest;
for (final leg in legs) {
final begin = leg.beginTime;
if (begin == null) continue;
if (earliest == null || begin.isBefore(earliest)) {
earliest = begin;
}
}
return earliest;
}
DateTime? get endDate {
DateTime? latest;
for (final leg in legs) {
final begin = leg.beginTime;
if (begin == null) continue;
if (latest == null || begin.isAfter(latest)) {
latest = begin;
}
}
return latest;
}
DateTime? get primaryDate => endDate ?? startDate;
static int compareByDateDesc(TripDetail a, TripDetail b) =>
compareTripsByDateDesc(a.primaryDate, b.primaryDate, a.id, b.id);
TripDetail({ TripDetail({
required this.id, required this.id,
@@ -1073,6 +1497,8 @@ class UserNotification {
final int id; final int id;
final String title; final String title;
final String body; final String body;
final String channel;
final String type;
final DateTime? createdAt; final DateTime? createdAt;
final bool dismissed; final bool dismissed;
@@ -1080,6 +1506,8 @@ class UserNotification {
required this.id, required this.id,
required this.title, required this.title,
required this.body, required this.body,
required this.channel,
required this.type,
required this.createdAt, required this.createdAt,
required this.dismissed, required this.dismissed,
}); });
@@ -1096,6 +1524,8 @@ class UserNotification {
id: _asInt(json['notification_id'] ?? json['id']), id: _asInt(json['notification_id'] ?? json['id']),
title: _asString(json['title']), title: _asString(json['title']),
body: _asString(json['body']), body: _asString(json['body']),
channel: _asString(json['channel']),
type: _asString(json['type'] ?? json['notification_type']),
createdAt: createdAt, createdAt: createdAt,
dismissed: _asBool(json['dismissed'] ?? false, false), dismissed: _asBool(json['dismissed'] ?? false, false),
); );

View File

@@ -21,6 +21,9 @@ class AuthService extends ChangeNotifier {
String? get userId => _user?.userId; String? get userId => _user?.userId;
String? get username => _user?.username; String? get username => _user?.username;
String? get fullName => _user?.fullName; String? get fullName => _user?.fullName;
bool get isElevated => _user?.isElevated ?? false;
bool get isAdmin => isElevated; // alias for old name
bool get isDisabled => _user?.disabled ?? false;
void setLoginData({ void setLoginData({
required String userId, required String userId,
@@ -28,6 +31,8 @@ class AuthService extends ChangeNotifier {
required String fullName, required String fullName,
required String accessToken, required String accessToken,
required String email, required String email,
bool isElevated = false,
bool isDisabled = false,
}) { }) {
_user = AuthenticatedUserData( _user = AuthenticatedUserData(
userId: userId, userId: userId,
@@ -35,6 +40,8 @@ class AuthService extends ChangeNotifier {
fullName: fullName, fullName: fullName,
accessToken: accessToken, accessToken: accessToken,
email: email, email: email,
isElevated: isElevated,
disabled: isDisabled,
); );
_persistToken(accessToken); _persistToken(accessToken);
notifyListeners(); notifyListeners();
@@ -70,6 +77,8 @@ class AuthService extends ChangeNotifier {
fullName: userResponse['full_name'], fullName: userResponse['full_name'],
accessToken: accessToken, accessToken: accessToken,
email: userResponse['email'], email: userResponse['email'],
isElevated: _parseIsElevated(userResponse),
isDisabled: _parseIsDisabled(userResponse),
); );
} }
@@ -95,6 +104,8 @@ class AuthService extends ChangeNotifier {
fullName: userResponse['full_name'], fullName: userResponse['full_name'],
accessToken: token, accessToken: token,
email: userResponse['email'], email: userResponse['email'],
isElevated: _parseIsElevated(userResponse),
isDisabled: _parseIsDisabled(userResponse),
); );
} catch (_) { } catch (_) {
await _clearToken(); await _clearToken();
@@ -157,4 +168,60 @@ class AuthService extends ChangeNotifier {
void logout() { void logout() {
handleTokenExpired(); // reuse handleTokenExpired(); // reuse
} }
bool _parseIsElevated(Map<String, dynamic> json) {
dynamic value = json['is_elevated'] ??
json['elevated'] ??
json['is_admin'] ??
json['admin'] ??
json['isAdmin'] ??
json['admin_user'] ??
json['role'] ??
json['roles'] ??
json['permissions'] ??
json['scopes'] ??
json['is_staff'] ??
json['staff'] ??
json['is_superuser'] ??
json['superuser'] ??
json['groups'];
bool parseBoolish(dynamic v) {
if (v is bool) return v;
if (v is num) return v != 0;
final str = v?.toString().toLowerCase().trim();
if (str == null || str.isEmpty) return false;
if (['1', 'true', 'yes', 'y', 'admin', 'superuser', 'staff', 'elevated'].contains(str)) {
return true;
}
return str.contains('admin') || str.contains('superuser') || str.contains('staff');
}
if (value is List) {
for (final entry in value) {
if (parseBoolish(entry)) return true;
final s = entry?.toString().toLowerCase();
if (s != null &&
(s.contains('admin') ||
s.contains('superuser') ||
s.contains('staff') ||
s.contains('elevated') ||
s == 'root')) {
return true;
}
}
return false;
}
return parseBoolish(value);
}
bool _parseIsDisabled(Map<String, dynamic> json) {
dynamic value = json['disabled'] ?? json['is_disabled'];
if (value is bool) return value;
if (value is num) return value != 0;
final str = value?.toString().toLowerCase().trim();
if (str == null || str.isEmpty) return false;
return ['1', 'true', 'yes', 'y', 'disabled'].contains(str);
}
} }

View File

@@ -12,3 +12,5 @@ part 'data_service_trips.dart';
part 'data_service_notifications.dart'; part 'data_service_notifications.dart';
part 'data_service_badges.dart'; part 'data_service_badges.dart';
part 'data_service_stats.dart'; part 'data_service_stats.dart';
part 'data_service_friendships.dart';
part 'data_service_leg_share.dart';

View File

@@ -64,6 +64,18 @@ class DataService extends ChangeNotifier {
bool isLocoTimelineLoading(int locoId) => bool isLocoTimelineLoading(int locoId) =>
_isLocoTimelineLoading[locoId] ?? false; _isLocoTimelineLoading[locoId] ?? false;
// Friendships
List<Friendship> _friendships = [];
List<Friendship> _pendingIncoming = [];
List<Friendship> _pendingOutgoing = [];
List<Friendship> get friendships => _friendships;
List<Friendship> get pendingIncoming => _pendingIncoming;
List<Friendship> get pendingOutgoing => _pendingOutgoing;
bool _isFriendshipsLoading = false;
bool get isFriendshipsLoading => _isFriendshipsLoading;
bool _isPendingFriendshipsLoading = false;
bool get isPendingFriendshipsLoading => _isPendingFriendshipsLoading;
// Trips // Trips
List<TripSummary> _trips = []; List<TripSummary> _trips = [];
List<TripSummary> get trips => _trips; List<TripSummary> get trips => _trips;
@@ -96,6 +108,10 @@ class DataService extends ChangeNotifier {
bool get isHomepageLoading => _isHomepageLoading; bool get isHomepageLoading => _isHomepageLoading;
bool _isOnThisDayLoading = false; bool _isOnThisDayLoading = false;
bool get isOnThisDayLoading => _isOnThisDayLoading; bool get isOnThisDayLoading => _isOnThisDayLoading;
List<LeaderboardEntry> _friendsLeaderboard = [];
List<LeaderboardEntry> get friendsLeaderboard => _friendsLeaderboard;
bool _isFriendsLeaderboardLoading = false;
bool get isFriendsLeaderboardLoading => _isFriendsLeaderboardLoading;
// Notifications // Notifications
List<UserNotification> _notifications = []; List<UserNotification> _notifications = [];
@@ -151,7 +167,8 @@ class DataService extends ChangeNotifier {
try { try {
final json = await api.get('/stats/homepage'); final json = await api.get('/stats/homepage');
_homepageStats = HomepageStats.fromJson(json); _homepageStats = HomepageStats.fromJson(json);
_trips = _homepageStats?.trips ?? []; _trips = [...(_homepageStats?.trips ?? const [])]
..sort(TripSummary.compareByDateDesc);
} catch (e) { } catch (e) {
debugPrint('Failed to fetch homepage stats: $e'); debugPrint('Failed to fetch homepage stats: $e');
_homepageStats = null; _homepageStats = null;

View File

@@ -0,0 +1,282 @@
part of 'data_service.dart';
extension DataServiceFriendships on DataService {
Future<void> fetchFriendships() async {
_isFriendshipsLoading = true;
try {
final json = await api.get('/friendships');
List<dynamic>? list;
if (json is List) {
list = json;
} else if (json is Map) {
for (final key in ['friendships', 'data', 'items', 'results']) {
final value = json[key];
if (value is List) {
list = value;
break;
}
}
}
final parsed = list
?.whereType<Map>()
.map((e) => Friendship.fromJson(
e.map((k, v) => MapEntry(k.toString(), v)),
))
.where((f) => f.isAccepted)
.toList();
_friendships = parsed ?? [];
} catch (e) {
debugPrint('Failed to fetch friendships: $e');
_friendships = [];
} finally {
_isFriendshipsLoading = false;
_notifyAsync();
}
}
Future<void> fetchPendingFriendships() async {
_isPendingFriendshipsLoading = true;
try {
final incoming = await _fetchPending('incoming');
final outgoing = await _fetchPending('outgoing');
_pendingIncoming = incoming;
_pendingOutgoing = outgoing;
} catch (e) {
debugPrint('Failed to fetch pending friendships: $e');
_pendingIncoming = [];
_pendingOutgoing = [];
} finally {
_isPendingFriendshipsLoading = false;
_notifyAsync();
}
}
Future<List<Friendship>> _fetchPending(String direction) async {
final json = await api.get('/friendships/pending?direction=$direction');
List<dynamic>? list;
if (json is List) {
list = json;
} else if (json is Map) {
for (final key in ['friendships', 'data', 'items', 'results']) {
final value = json[key];
if (value is List) {
list = value;
break;
}
}
}
return list
?.whereType<Map>()
.map((e) => Friendship.fromJson(
e.map((k, v) => MapEntry(k.toString(), v)),
))
.where((f) => f.isPending)
.toList() ??
const [];
}
Future<Friendship?> fetchFriendshipById(String friendshipId) async {
try {
final json = await api.get('/friendships/$friendshipId');
if (json is Map) {
return Friendship.fromJson(
json.map((k, v) => MapEntry(k.toString(), v)),
);
}
} catch (e) {
debugPrint('Failed to fetch friendship $friendshipId: $e');
}
return null;
}
Future<List<UserSummary>> searchUsers(
String query, {
bool friendsOnly = false,
}) async {
final encoded = Uri.encodeComponent(query);
final json = await api.get(
'/users/search?search=$encoded${friendsOnly ? '&friends_only=true' : ''}',
);
List<dynamic>? list;
if (json is List) {
list = json;
} else if (json is Map) {
for (final key in ['users', 'data', 'results', 'items']) {
final value = json[key];
if (value is List) {
list = value;
break;
}
}
}
if (list == null) return const [];
return list
.whereType<Map>()
.map((e) => UserSummary.fromJson(
e.map((k, v) => MapEntry(k.toString(), v)),
))
.toList();
}
Future<Friendship> fetchFriendshipStatus(String targetUserId) async {
try {
final json = await api.get('/friendships/status/$targetUserId');
if (json is Map) {
return Friendship.fromStatusJson(
json.map((k, v) => MapEntry(k.toString(), v)),
targetUserId: targetUserId,
);
}
} catch (e) {
debugPrint('Failed to fetch friendship status for $targetUserId: $e');
}
return Friendship(
id: null,
status: 'none',
requesterId: '',
addresseeId: targetUserId,
);
}
Future<Friendship> requestFriendship(
String targetUserId, {
UserSummary? targetUser,
}) async {
final json = await api.post('/friendships/request', {
"target_user_id": targetUserId,
});
final friendship = _parseAndUpsertFriendship(
json,
fallbackStatus: 'pending',
overrideAddressee: targetUser,
);
_pendingOutgoing = [friendship, ..._pendingOutgoing];
_notifyAsync();
return friendship;
}
Future<Friendship> acceptFriendship(String friendshipId) async {
final json = await api.post('/friendships/$friendshipId/accept', {});
final friendship = _parseAndUpsertFriendship(json, fallbackStatus: 'accepted');
_pendingIncoming = _pendingIncoming.where((f) => f.id != friendshipId).toList();
_notifyAsync();
return friendship;
}
Future<Friendship> rejectFriendship(String friendshipId) async {
final json = await api.post('/friendships/$friendshipId/reject', {});
final friendship = _parseAndUpsertFriendship(json, fallbackStatus: 'declined');
_pendingIncoming = _pendingIncoming.where((f) => f.id != friendshipId).toList();
_notifyAsync();
return friendship;
}
Future<Friendship> cancelFriendship(String friendshipId) async {
final json = await api.post('/friendships/$friendshipId/cancel', {});
final friendship =
_parseAndRemoveFriendship(json, friendshipId, status: 'none');
_pendingOutgoing =
_pendingOutgoing.where((f) => f.id != friendshipId).toList();
_notifyAsync();
return friendship;
}
Future<void> deleteFriendship(String friendshipId) async {
try {
await api.delete('/friendships/$friendshipId');
} catch (e) {
debugPrint('Failed to delete friendship $friendshipId: $e');
rethrow;
}
_friendships = _friendships.where((f) => f.id != friendshipId).toList();
_pendingIncoming =
_pendingIncoming.where((f) => f.id != friendshipId).toList();
_pendingOutgoing =
_pendingOutgoing.where((f) => f.id != friendshipId).toList();
_notifyAsync();
}
Future<Friendship> blockUser(String targetUserId) async {
final json = await api.post('/friendships/block', {
"target_user_id": targetUserId,
});
final friendship = _parseAndUpsertFriendship(json, fallbackStatus: 'blocked');
_pendingIncoming = _pendingIncoming
.where((f) => f.addresseeId != targetUserId && f.requesterId != targetUserId)
.toList();
_pendingOutgoing = _pendingOutgoing
.where((f) => f.addresseeId != targetUserId && f.requesterId != targetUserId)
.toList();
_notifyAsync();
return friendship;
}
Friendship _parseAndUpsertFriendship(
dynamic json, {
String fallbackStatus = 'none',
UserSummary? overrideAddressee,
}) {
Friendship friendship;
if (json is Map) {
friendship = Friendship.fromJson(
json.map((k, v) => MapEntry(k.toString(), v)),
);
} else {
friendship = Friendship(
id: null,
status: fallbackStatus,
requesterId: '',
addresseeId: '',
);
}
if (overrideAddressee != null &&
(friendship.addressee == null ||
friendship.addressee!.userId.isEmpty ||
friendship.addressee!.displayName.isEmpty)) {
friendship = friendship.copyWith(
addressee: overrideAddressee,
addresseeId: overrideAddressee.userId,
);
}
_upsertFriendship(friendship);
return friendship;
}
Friendship _parseAndRemoveFriendship(
dynamic json,
String friendshipId, {
required String status,
}) {
Friendship friendship;
if (json is Map) {
friendship = Friendship.fromJson(
json.map((k, v) => MapEntry(k.toString(), v)),
);
} else {
friendship = Friendship(
id: friendshipId,
status: status,
requesterId: '',
addresseeId: '',
);
}
_friendships = _friendships.where((f) => f.id != friendshipId).toList();
_notifyAsync();
return friendship;
}
void _upsertFriendship(Friendship friendship) {
if (friendship.id == null || friendship.id!.isEmpty) {
_notifyAsync();
return;
}
final idx = _friendships.indexWhere((f) => f.id == friendship.id);
if (idx >= 0) {
_friendships[idx] = friendship;
} else {
_friendships = [friendship, ..._friendships];
}
_friendships = _friendships.where((f) => f.isAccepted).toList();
_notifyAsync();
}
}

View File

@@ -0,0 +1,97 @@
part of 'data_service.dart';
extension DataServiceLegShare on DataService {
Future<LegShareData?> fetchLegShare(String legShareId) async {
try {
final json = await api.get('/legs/share/$legShareId');
if (json is Map) {
return LegShareData.fromJson(
json.map((k, v) => MapEntry(k.toString(), v)),
);
}
} catch (e) {
debugPrint('Failed to fetch leg share $legShareId: $e');
rethrow;
}
return null;
}
Future<void> rejectLegShare(String legShareId) async {
try {
await api.post('/legs/share/$legShareId/reject', {});
} catch (e) {
debugPrint('Failed to reject leg share $legShareId: $e');
rethrow;
}
}
Future<int?> acceptLegShare(LegShareData share) async {
final entry = share.entry;
final hasRoute = entry.route.isNotEmpty;
final locosPayload = <Map<String, dynamic>>[];
for (var i = 0; i < entry.locos.length; i++) {
final loco = entry.locos[i];
final pos = loco.allocPos != 0 ? loco.allocPos : i;
locosPayload.add({
"loco_id": loco.id,
"alloc_pos": pos,
"alloc_powering": loco.powering ? 1 : 0,
});
}
final payload = <String, dynamic>{
"leg_share_id": share.id,
"leg_trip": null,
"leg_begin_time": entry.beginTime.toIso8601String(),
if (entry.endTime != null) "leg_end_time": entry.endTime!.toIso8601String(),
if (entry.originTime != null)
"leg_origin_time": entry.originTime!.toIso8601String(),
if (entry.destinationTime != null)
"leg_destination_time": entry.destinationTime!.toIso8601String(),
"leg_notes": entry.notes,
"leg_headcode": entry.headcode,
"leg_network": entry.network,
"leg_origin": entry.origin,
"leg_destination": entry.destination,
"leg_begin_delay": entry.beginDelayMinutes ?? 0,
if (entry.endDelayMinutes != null) "leg_end_delay": entry.endDelayMinutes,
"locos": locosPayload,
"share_user_ids": <String>[],
};
dynamic response;
if (hasRoute) {
response = await api.post(
'/add',
{
...payload,
"leg_route": entry.route,
"leg_mileage": entry.mileage,
},
);
} else {
response = await api.post(
'/add/manual',
{
...payload,
"leg_start": entry.start,
"leg_end": entry.end,
"leg_distance": entry.mileage,
"isKilometers": false,
},
);
}
final legId = _parseNullableInt(
response is Map ? response['leg_id'] : null,
);
if (legId != null) return legId;
return null;
}
int? _parseNullableInt(dynamic value) {
if (value is int) return value;
if (value is num) return value.toInt();
if (value is String) return int.tryParse(value);
return null;
}
}

View File

@@ -20,7 +20,7 @@ extension DataServiceNotifications on DataService {
final parsed = list final parsed = list
?.whereType<Map<String, dynamic>>() ?.whereType<Map<String, dynamic>>()
.map(UserNotification.fromJson) .map(UserNotification.fromJson)
.where((n) => !n.dismissed) .where((n) => !n.dismissed && n.channel.toLowerCase() != 'web')
.toList(); .toList();
if (parsed != null) { if (parsed != null) {

View File

@@ -25,4 +25,38 @@ extension DataServiceStats on DataService {
_notifyAsync(); _notifyAsync();
} }
} }
Future<void> fetchFriendsLeaderboard() async {
if (_isFriendsLeaderboardLoading) return;
_isFriendsLeaderboardLoading = true;
_notifyAsync();
try {
final json = await api.get('/stats/leaderboard/friends');
List<dynamic>? list;
if (json is List) {
list = json;
} else if (json is Map) {
for (final key in ['leaderboard', 'data', 'items', 'results']) {
final value = json[key];
if (value is List) {
list = value;
break;
}
}
}
_friendsLeaderboard = list
?.whereType<Map>()
.map((e) => LeaderboardEntry.fromJson(
e.map((k, v) => MapEntry(k.toString(), v)),
))
.toList() ??
const [];
} catch (e) {
debugPrint('Failed to fetch friends leaderboard: $e');
_friendsLeaderboard = [];
} finally {
_isFriendsLeaderboardLoading = false;
_notifyAsync();
}
}
} }

View File

@@ -13,7 +13,7 @@ extension DataServiceTraction on DataService {
Future<void> fetchTraction({ Future<void> fetchTraction({
bool hadOnly = false, bool hadOnly = false,
int offset = 0, int offset = 0,
int limit = 50, int limit = 100,
String? locoClass, String? locoClass,
String? locoNumber, String? locoNumber,
bool mileageFirst = true, bool mileageFirst = true,

View File

@@ -6,7 +6,7 @@ extension DataServiceTrips on DataService {
try { try {
final json = await api.get('/trips/info'); final json = await api.get('/trips/info');
final tripDetails = _parseTripInfoList(json); final tripDetails = _parseTripInfoList(json);
_tripDetails = [...tripDetails]..sort((a, b) => b.id.compareTo(a.id)); _tripDetails = [...tripDetails]..sort(TripDetail.compareByDateDesc);
_tripList = tripDetails _tripList = tripDetails
.map( .map(
(detail) => TripSummary( (detail) => TripSummary(
@@ -15,10 +15,12 @@ extension DataServiceTrips on DataService {
tripMileage: detail.mileage, tripMileage: detail.mileage,
legCount: detail.legCount, legCount: detail.legCount,
locoStats: detail.locoStats, locoStats: detail.locoStats,
startDate: detail.startDate,
endDate: detail.endDate,
), ),
) )
.toList() .toList()
..sort((a, b) => b.tripId.compareTo(a.tripId)); ..sort(TripSummary.compareByDateDesc);
} catch (e) { } catch (e) {
debugPrint('Failed to fetch trip_map: $e'); debugPrint('Failed to fetch trip_map: $e');
_tripDetails = []; _tripDetails = [];
@@ -49,7 +51,7 @@ extension DataServiceTrips on DataService {
.map((e) => TripSummary.fromJson(e)) .map((e) => TripSummary.fromJson(e))
.toList(); .toList();
_tripList = [...tripMap]..sort((a, b) => b.tripId.compareTo(a.tripId)); _tripList = [...tripMap]..sort(TripSummary.compareByDateDesc);
} else { } else {
debugPrint('Unexpected trip list response: $json'); debugPrint('Unexpected trip list response: $json');
_tripList = []; _tripList = [];
@@ -83,7 +85,7 @@ extension DataServiceTrips on DataService {
.map((e) => TripSummary.fromJson(e)) .map((e) => TripSummary.fromJson(e))
.toList(); .toList();
_tripList = [...tripMap]..sort((a, b) => b.tripId.compareTo(a.tripId)); _tripList = [...tripMap]..sort(TripSummary.compareByDateDesc);
} else { } else {
debugPrint('Unexpected trip list response: $json'); debugPrint('Unexpected trip list response: $json');
_tripList = []; _tripList = [];
@@ -105,7 +107,7 @@ extension DataServiceTrips on DataService {
} else { } else {
_tripList = [trip, ..._tripList]; _tripList = [trip, ..._tripList];
} }
_tripList.sort((a, b) => b.tripId.compareTo(a.tripId)); _tripList.sort(TripSummary.compareByDateDesc);
_notifyAsync(); _notifyAsync();
} }

View File

@@ -0,0 +1,211 @@
import 'package:flutter/foundation.dart';
import 'package:intl/intl.dart';
import 'package:shared_preferences/shared_preferences.dart';
enum DistanceUnit {
milesDecimal,
milesChains,
kilometers,
}
extension DistanceUnitLabels on DistanceUnit {
String get label {
switch (this) {
case DistanceUnit.milesDecimal:
return 'Miles (decimal)';
case DistanceUnit.milesChains:
return 'Miles & chains';
case DistanceUnit.kilometers:
return 'Kilometers';
}
}
String get shortLabel {
switch (this) {
case DistanceUnit.milesDecimal:
return 'mi';
case DistanceUnit.milesChains:
return 'm.ch';
case DistanceUnit.kilometers:
return 'km';
}
}
String get _prefsValue => toString().split('.').last;
static DistanceUnit fromPrefs(String raw) {
return DistanceUnit.values.firstWhere(
(u) => u._prefsValue == raw,
orElse: () => DistanceUnit.milesDecimal,
);
}
}
class DistanceUnitService extends ChangeNotifier {
static const _prefsKey = 'distance_unit';
static const double kmPerMile = 1.609344;
static const double chainsPerMile = 80.0;
DistanceUnitService() {
_load();
}
DistanceUnit _unit = DistanceUnit.milesDecimal;
bool _loaded = false;
DistanceUnit get unit => _unit;
bool get isLoaded => _loaded;
Future<void> _load() async {
final prefs = await SharedPreferences.getInstance();
final saved = prefs.getString(_prefsKey);
if (saved != null && saved.trim().isNotEmpty) {
_unit = DistanceUnitLabels.fromPrefs(saved.trim());
}
_loaded = true;
notifyListeners();
}
Future<void> setUnit(DistanceUnit unit) async {
_unit = unit;
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_prefsKey, unit._prefsValue);
notifyListeners();
}
double? milesFromInput(String input) =>
DistanceFormatter(_unit).parseInputMiles(input);
String format(double miles,
{int decimals = 1, bool includeUnit = true}) =>
DistanceFormatter(_unit)
.format(miles, decimals: decimals, includeUnit: includeUnit);
double toDisplay(double miles, {int decimals = 1}) =>
DistanceFormatter(_unit).convertMiles(miles, decimals: decimals);
}
class DistanceFormatter {
DistanceFormatter(this.unit);
final DistanceUnit unit;
String format(double miles,
{int decimals = 1, bool includeUnit = true}) {
decimals = decimals.clamp(1, 2);
if (unit == DistanceUnit.milesChains) {
// Always show chains with two decimals.
decimals = 2;
}
switch (unit) {
case DistanceUnit.milesDecimal:
final value = _numberFormat(decimals).format(miles);
return includeUnit ? '$value mi' : value;
case DistanceUnit.kilometers:
final kms = miles * DistanceUnitService.kmPerMile;
final value = _numberFormat(decimals).format(kms);
return includeUnit ? '$value km' : value;
case DistanceUnit.milesChains:
final value = _formatMilesChains(miles);
return includeUnit ? '$value mi' : value;
}
}
double convertMiles(double miles, {int decimals = 1}) {
decimals = decimals.clamp(1, 2);
switch (unit) {
case DistanceUnit.milesDecimal:
return double.parse(miles.toStringAsFixed(decimals));
case DistanceUnit.kilometers:
final kms = miles * DistanceUnitService.kmPerMile;
return double.parse(kms.toStringAsFixed(decimals));
case DistanceUnit.milesChains:
// Return miles again; chains representation handled by format.
return double.parse(miles.toStringAsFixed(decimals));
}
}
double milesFromDisplayValue(double value) {
switch (unit) {
case DistanceUnit.milesDecimal:
return value;
case DistanceUnit.kilometers:
return value / DistanceUnitService.kmPerMile;
case DistanceUnit.milesChains:
// Value already represents miles when parsed via parseMilesChains.
return value;
}
}
double? parseInputMiles(String input) {
final trimmed = input.trim();
if (trimmed.isEmpty) return null;
switch (unit) {
case DistanceUnit.milesDecimal:
return double.tryParse(trimmed.replaceAll(',', ''));
case DistanceUnit.kilometers:
final km = double.tryParse(trimmed.replaceAll(',', ''));
if (km == null) return null;
return km / DistanceUnitService.kmPerMile;
case DistanceUnit.milesChains:
return _parseMilesChains(trimmed);
}
}
NumberFormat _numberFormat(int decimals) {
final pattern =
decimals == 1 ? '#,##0.0' : '#,##0.00';
return NumberFormat(pattern);
}
String _formatMilesChains(double miles) {
final totalChains = miles * DistanceUnitService.chainsPerMile;
var milesPart = totalChains ~/ DistanceUnitService.chainsPerMile;
final chainRemainder =
totalChains - (milesPart * DistanceUnitService.chainsPerMile);
// Always show chains as two digits (00-79), rounded to the nearest chain.
var roundedChains = chainRemainder.roundToDouble();
if (roundedChains >= DistanceUnitService.chainsPerMile) {
milesPart += 1;
roundedChains -= DistanceUnitService.chainsPerMile;
}
final chainText = NumberFormat('00').format(roundedChains);
return '$milesPart.$chainText';
}
double? _parseMilesChains(String raw) {
final cleaned = raw
.toLowerCase()
.replaceAll(',', '')
.replaceAll('m', '.')
.replaceAll('c', '.')
.replaceAll(RegExp(r'\s+'), '.')
.replaceAll(RegExp(r'\.+'), '.')
.trim();
if (cleaned.isEmpty) return null;
final parts = cleaned.split('.');
if (parts.isEmpty) return null;
final milesPart =
int.tryParse(parts[0].isEmpty ? '0' : parts[0]);
if (milesPart == null) return null;
double chainsPart = 0;
if (parts.length >= 2) {
final chainRaw = parts
.sublist(1)
.join()
.trim();
if (chainRaw.isNotEmpty) {
final parsedChains = double.tryParse(chainRaw);
if (parsedChains == null) return null;
chainsPart = parsedChains;
}
}
final totalMiles =
milesPart +
(chainsPart / DistanceUnitService.chainsPerMile);
return totalMiles;
}
}

View File

@@ -1,3 +1,5 @@
import 'dart:async';
import 'package:dynamic_color/dynamic_color.dart'; import 'package:dynamic_color/dynamic_color.dart';
import 'package:flutter/gestures.dart'; import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
@@ -11,12 +13,16 @@ import 'package:mileograph_flutter/components/pages/loco_legs.dart';
import 'package:mileograph_flutter/components/pages/loco_timeline.dart'; import 'package:mileograph_flutter/components/pages/loco_timeline.dart';
import 'package:mileograph_flutter/components/pages/logbook.dart'; import 'package:mileograph_flutter/components/pages/logbook.dart';
import 'package:mileograph_flutter/components/pages/more.dart'; import 'package:mileograph_flutter/components/pages/more.dart';
import 'package:mileograph_flutter/components/pages/badges.dart';
import 'package:mileograph_flutter/components/pages/new_entry.dart'; import 'package:mileograph_flutter/components/pages/new_entry.dart';
import 'package:mileograph_flutter/components/pages/new_traction.dart'; import 'package:mileograph_flutter/components/pages/new_traction.dart';
import 'package:mileograph_flutter/components/pages/profile.dart'; import 'package:mileograph_flutter/components/pages/profile.dart';
import 'package:mileograph_flutter/components/pages/settings.dart'; import 'package:mileograph_flutter/components/pages/settings.dart';
import 'package:mileograph_flutter/components/pages/stats.dart'; import 'package:mileograph_flutter/components/pages/stats.dart';
import 'package:mileograph_flutter/components/pages/traction.dart'; import 'package:mileograph_flutter/components/pages/traction.dart';
import 'package:mileograph_flutter/components/widgets/friend_request_notification_card.dart';
import 'package:mileograph_flutter/components/widgets/leg_share_notification_card.dart';
import 'package:mileograph_flutter/objects/objects.dart';
import 'package:mileograph_flutter/services/authservice.dart'; import 'package:mileograph_flutter/services/authservice.dart';
import 'package:mileograph_flutter/services/data_service.dart'; import 'package:mileograph_flutter/services/data_service.dart';
import 'package:mileograph_flutter/services/navigation_guard.dart'; import 'package:mileograph_flutter/services/navigation_guard.dart';
@@ -204,7 +210,15 @@ class _MyAppState extends State<MyApp> {
path: '/traction/new', path: '/traction/new',
builder: (context, state) => const NewTractionPage(), builder: (context, state) => const NewTractionPage(),
), ),
GoRoute(path: '/add', builder: (context, state) => NewEntryPage()), GoRoute(
path: '/add',
builder: (context, state) {
final extra = state.extra;
return NewEntryPage(
legShare: extra is LegShareData ? extra : null,
);
},
),
GoRoute( GoRoute(
path: '/more', path: '/more',
builder: (context, state) => const MorePage(), builder: (context, state) => const MorePage(),
@@ -213,6 +227,10 @@ class _MyAppState extends State<MyApp> {
path: '/more/profile', path: '/more/profile',
builder: (context, state) => const ProfilePage(), builder: (context, state) => const ProfilePage(),
), ),
GoRoute(
path: '/more/badges',
builder: (context, state) => const BadgesPage(),
),
GoRoute( GoRoute(
path: '/more/stats', path: '/more/stats',
builder: (context, state) => const StatsPage(), builder: (context, state) => const StatsPage(),
@@ -221,6 +239,10 @@ class _MyAppState extends State<MyApp> {
path: '/more/settings', path: '/more/settings',
builder: (context, state) => const SettingsPage(), builder: (context, state) => const SettingsPage(),
), ),
GoRoute(
path: '/more/admin',
builder: (context, state) => const AdminPage(),
),
GoRoute( GoRoute(
path: '/legs/edit/:id', path: '/legs/edit/:id',
builder: (_, state) { builder: (_, state) {
@@ -307,6 +329,7 @@ class _MyHomePageState extends State<MyHomePage> {
bool _fetched = false; bool _fetched = false;
bool _railCollapsed = false; bool _railCollapsed = false;
Timer? _notificationsTimer;
@override @override
void didChangeDependencies() { void didChangeDependencies() {
@@ -343,10 +366,35 @@ class _MyHomePageState extends State<MyHomePage> {
if (data.notifications.isEmpty) { if (data.notifications.isEmpty) {
data.fetchNotifications(); data.fetchNotifications();
} }
if (data.friendships.isEmpty && !data.isFriendshipsLoading) {
data.fetchFriendships();
}
if ((data.pendingIncoming.isEmpty && data.pendingOutgoing.isEmpty) &&
!data.isPendingFriendshipsLoading) {
data.fetchPendingFriendships();
}
_startNotificationPolling();
}); });
}); });
} }
void _startNotificationPolling() {
_notificationsTimer?.cancel();
final auth = context.read<AuthService>();
if (!auth.isLoggedIn) return;
_notificationsTimer = Timer.periodic(const Duration(minutes: 2), (_) async {
if (!mounted) return;
final auth = context.read<AuthService>();
if (!auth.isLoggedIn) return;
final data = context.read<DataService>();
try {
await data.fetchNotifications();
} catch (_) {
// Errors already logged inside data service.
}
});
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final uri = GoRouterState.of(context).uri; final uri = GoRouterState.of(context).uri;
@@ -410,6 +458,11 @@ class _MyHomePageState extends State<MyHomePage> {
), ),
actions: [ actions: [
_buildNotificationAction(context, data), _buildNotificationAction(context, data),
IconButton(
tooltip: 'Profile',
onPressed: () => context.go('/more/profile'),
icon: const Icon(Icons.person),
),
IconButton( IconButton(
tooltip: 'Settings', tooltip: 'Settings',
onPressed: () => context.go('/more/settings'), onPressed: () => context.go('/more/settings'),
@@ -620,6 +673,13 @@ class _MyHomePageState extends State<MyHomePage> {
Widget _buildNotificationsContent(BuildContext context, bool isWide) { Widget _buildNotificationsContent(BuildContext context, bool isWide) {
final data = context.watch<DataService>(); final data = context.watch<DataService>();
final notifications = data.notifications; final notifications = data.notifications;
final dismissibleIds = notifications
.where(
(n) =>
!_isFriendRequestNotification(n) && !_isLegShareNotification(n),
)
.map((e) => e.id)
.toList();
final loading = data.isNotificationsLoading; final loading = data.isNotificationsLoading;
final listHeight = isWide final listHeight = isWide
? 380.0 ? 380.0
@@ -646,6 +706,9 @@ class _MyHomePageState extends State<MyHomePage> {
separatorBuilder: (_, index) => const SizedBox(height: 8), separatorBuilder: (_, index) => const SizedBox(height: 8),
itemBuilder: (ctx, index) { itemBuilder: (ctx, index) {
final item = notifications[index]; final item = notifications[index];
final isFriendRequest = _isFriendRequestNotification(item);
final isLegShare = _isLegShareNotification(item);
final isSpecial = isFriendRequest || isLegShare;
return Card( return Card(
child: Padding( child: Padding(
padding: const EdgeInsets.all(12.0), padding: const EdgeInsets.all(12.0),
@@ -668,7 +731,11 @@ class _MyHomePageState extends State<MyHomePage> {
), ),
const SizedBox(height: 4), const SizedBox(height: 4),
Text( Text(
item.body, isFriendRequest || isLegShare
? isFriendRequest
? 'Accept to share entries'
: 'Shared entry details below.'
: item.body,
style: Theme.of(context).textTheme.bodyMedium, style: Theme.of(context).textTheme.bodyMedium,
), ),
if (item.createdAt != null) ...[ if (item.createdAt != null) ...[
@@ -694,6 +761,7 @@ class _MyHomePageState extends State<MyHomePage> {
], ],
), ),
), ),
if (!isSpecial) ...[
const SizedBox(width: 8), const SizedBox(width: 8),
TextButton( TextButton(
onPressed: () => onPressed: () =>
@@ -701,6 +769,19 @@ class _MyHomePageState extends State<MyHomePage> {
child: const Text('Dismiss'), child: const Text('Dismiss'),
), ),
], ],
],
),
if (isFriendRequest)
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: FriendRequestNotificationCard(
notification: item,
),
),
if (isLegShare)
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: LegShareNotificationCard(notification: item),
), ),
], ],
), ),
@@ -731,10 +812,7 @@ class _MyHomePageState extends State<MyHomePage> {
TextButton( TextButton(
onPressed: notifications.isEmpty onPressed: notifications.isEmpty
? null ? null
: () => _dismissNotifications( : () => _dismissNotifications(context, dismissibleIds),
context,
notifications.map((e) => e.id).toList(),
),
child: const Text('Dismiss all'), child: const Text('Dismiss all'),
), ),
], ],
@@ -769,6 +847,29 @@ class _MyHomePageState extends State<MyHomePage> {
return '$y-$m-$d $hh:$mm'; return '$y-$m-$d $hh:$mm';
} }
bool _isFriendRequestNotification(UserNotification notification) {
final type = notification.type.trim().toLowerCase();
final channel = notification.channel.trim().toLowerCase();
final title = notification.title.trim().toLowerCase();
bool matchesChannel =
channel == 'friend_request' || channel == 'friend-request';
if (!matchesChannel) {
matchesChannel = channel.contains('friend_request') ||
channel.contains('friend-request') ||
channel.contains('friend');
}
return matchesChannel ||
type == 'friend_request' ||
type == 'friend-request' ||
title.contains('friend request');
}
bool _isLegShareNotification(UserNotification notification) {
final channel = notification.channel.trim().toLowerCase();
final type = notification.type.trim().toLowerCase();
return channel.contains('leg_share') || type.contains('leg_share');
}
Widget _buildBadge(String label) { Widget _buildBadge(String label) {
return Container( return Container(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
@@ -895,4 +996,10 @@ class _MyHomePageState extends State<MyHomePage> {
_forwardHistory.clear(); _forwardHistory.clear();
context.go(tabDestinations[index]); context.go(tabDestinations[index]);
} }
@override
void dispose() {
_notificationsTimer?.cancel();
super.dispose();
}
} }

View File

@@ -16,7 +16,7 @@ publish_to: "none" # Remove this line if you wish to publish to pub.dev
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts # In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix. # of the product and file versions while build-number is used as the build suffix.
version: 0.5.0+1 version: 0.6.1+4
environment: environment:
sdk: ^3.8.1 sdk: ^3.8.1
@@ -102,7 +102,16 @@ flutter:
flutter_launcher_icons: flutter_launcher_icons:
android: true android: true
ios: true ios: true
remove_alpha_ios: true
linux:
generate: true
web:
generate: true
background_colour: "#000000"
theme_color: "#0175C2"
windows:
generate: true
image_path: assets/icons/app_icon.png image_path: assets/icons/app_icon.png
adaptive_icon_background: "#ffffff" adaptive_icon_background: "#000000"
adaptive_icon_foreground: assets/icons/app_icon.png adaptive_icon_foreground: assets/icons/app_icon.png
min_sdk_android: 21 min_sdk_android: 21

Binary file not shown.

Before

Width:  |  Height:  |  Size: 917 B

After

Width:  |  Height:  |  Size: 304 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.2 KiB

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.1 KiB

After

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.5 KiB

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

After

Width:  |  Height:  |  Size: 6.5 KiB

View File

@@ -18,18 +18,19 @@
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta content="IE=Edge" http-equiv="X-UA-Compatible"> <meta content="IE=Edge" http-equiv="X-UA-Compatible">
<meta name="description" content="A new Flutter project."> <meta name="description" content="Log and explore your Mileograph journeys.">
<meta name="theme-color" content="#0175C2">
<!-- iOS meta tags & icons --> <!-- iOS meta tags & icons -->
<meta name="mobile-web-app-capable" content="yes"> <meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black"> <meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="mileograph_flutter"> <meta name="apple-mobile-web-app-title" content="Mileograph">
<link rel="apple-touch-icon" href="icons/Icon-192.png"> <link rel="apple-touch-icon" href="icons/Icon-192.png">
<!-- Favicon --> <!-- Favicon -->
<link rel="icon" type="image/png" href="favicon.png"/> <link rel="icon" type="image/png" href="favicon.png"/>
<title>mileograph_flutter</title> <title>Mileograph</title>
<link rel="manifest" href="manifest.json"> <link rel="manifest" href="manifest.json">
</head> </head>
<body> <body>

View File

@@ -1,11 +1,12 @@
{ {
"name": "mileograph_flutter", "name": "Mileograph",
"short_name": "mileograph_flutter", "short_name": "Mileograph",
"start_url": ".", "start_url": "/",
"scope": "/",
"display": "standalone", "display": "standalone",
"background_color": "#0175C2", "background_color": "#0175C2",
"theme_color": "#0175C2", "theme_color": "#0175C2",
"description": "A new Flutter project.", "description": "Log and explore your Mileograph journeys.",
"orientation": "portrait-primary", "orientation": "portrait-primary",
"prefer_related_applications": false, "prefer_related_applications": false,
"icons": [ "icons": [

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

After

Width:  |  Height:  |  Size: 711 B