Compare commits
5 Commits
v0.5.1-dev
...
v0.5.5-dev
| Author | SHA1 | Date | |
|---|---|---|---|
| 2fa66ff9c6 | |||
| 29cecf0ded | |||
| f9c392bb07 | |||
| e5b145b4b2 | |||
| 59458484aa |
@@ -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:
|
||||||
@@ -154,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
|
||||||
@@ -200,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
|
||||||
@@ -255,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
|
||||||
@@ -262,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: |
|
||||||
@@ -279,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
|
||||||
@@ -293,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' }}
|
||||||
@@ -338,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
|
||||||
@@ -345,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: |
|
||||||
@@ -362,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
|
||||||
@@ -371,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' }}
|
||||||
@@ -409,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
@@ -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;"]
|
||||||
71
README.md
@@ -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.
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ android {
|
|||||||
|
|
||||||
defaultConfig {
|
defaultConfig {
|
||||||
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
|
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
|
||||||
applicationId = "com.petegregoryy.mileograph_flutter"
|
applicationId = "com.iwdac.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 = flutter.minSdkVersion
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 4.7 KiB After Width: | Height: | Size: 2.1 KiB |
|
Before Width: | Height: | Size: 3.0 KiB After Width: | Height: | Size: 1.4 KiB |
|
Before Width: | Height: | Size: 7.6 KiB After Width: | Height: | Size: 2.8 KiB |
|
Before Width: | Height: | Size: 13 KiB After Width: | Height: | Size: 4.0 KiB |
|
Before Width: | Height: | Size: 18 KiB After Width: | Height: | Size: 5.5 KiB |
|
Before Width: | Height: | Size: 2.0 KiB After Width: | Height: | Size: 1014 B |
|
Before Width: | Height: | Size: 1.3 KiB After Width: | Height: | Size: 689 B |
|
Before Width: | Height: | Size: 2.7 KiB After Width: | Height: | Size: 1.3 KiB |
|
Before Width: | Height: | Size: 4.1 KiB After Width: | Height: | Size: 1.9 KiB |
|
Before Width: | Height: | Size: 5.3 KiB After Width: | Height: | Size: 2.4 KiB |
@@ -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>
|
||||||
|
Before Width: | Height: | Size: 5.2 KiB After Width: | Height: | Size: 6.0 KiB |
BIN
assets/icons/app_icon_old.png
Normal file
|
After Width: | Height: | Size: 5.2 KiB |
28
deploy/web/nginx.conf
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Before Width: | Height: | Size: 55 KiB After Width: | Height: | Size: 12 KiB |
|
Before Width: | Height: | Size: 598 B After Width: | Height: | Size: 346 B |
|
Before Width: | Height: | Size: 1.1 KiB After Width: | Height: | Size: 497 B |
|
Before Width: | Height: | Size: 1.6 KiB After Width: | Height: | Size: 738 B |
|
Before Width: | Height: | Size: 834 B After Width: | Height: | Size: 425 B |
|
Before Width: | Height: | Size: 1.6 KiB After Width: | Height: | Size: 697 B |
|
Before Width: | Height: | Size: 2.4 KiB After Width: | Height: | Size: 1017 B |
|
Before Width: | Height: | Size: 1.1 KiB After Width: | Height: | Size: 497 B |
|
Before Width: | Height: | Size: 2.3 KiB After Width: | Height: | Size: 876 B |
|
Before Width: | Height: | Size: 3.3 KiB After Width: | Height: | Size: 1.3 KiB |
|
Before Width: | Height: | Size: 1.4 KiB After Width: | Height: | Size: 632 B |
|
Before Width: | Height: | Size: 2.8 KiB After Width: | Height: | Size: 1.1 KiB |
|
Before Width: | Height: | Size: 1.6 KiB After Width: | Height: | Size: 698 B |
|
Before Width: | Height: | Size: 3.2 KiB After Width: | Height: | Size: 1.2 KiB |
|
Before Width: | Height: | Size: 3.3 KiB After Width: | Height: | Size: 1.3 KiB |
|
Before Width: | Height: | Size: 5.1 KiB After Width: | Height: | Size: 1.8 KiB |
|
Before Width: | Height: | Size: 2.0 KiB After Width: | Height: | Size: 834 B |
|
Before Width: | Height: | Size: 4.1 KiB After Width: | Height: | Size: 1.5 KiB |
|
Before Width: | Height: | Size: 2.1 KiB After Width: | Height: | Size: 841 B |
|
Before Width: | Height: | Size: 4.3 KiB After Width: | Height: | Size: 1.6 KiB |
|
Before Width: | Height: | Size: 4.8 KiB After Width: | Height: | Size: 1.7 KiB |
@@ -111,12 +111,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,
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ class _DashboardState extends State<Dashboard> {
|
|||||||
final distanceUnits = context.watch<DistanceUnitService>();
|
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 {
|
||||||
@@ -513,9 +513,9 @@ class _DashboardState extends State<Dashboard> {
|
|||||||
Widget _buildTripsCard(
|
Widget _buildTripsCard(
|
||||||
BuildContext context, DataService data, DistanceUnitService distanceUnits) {
|
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,
|
||||||
|
|||||||
@@ -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'),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
476
lib/components/pages/more/admin_page.dart
Normal 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),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
53
lib/components/pages/more/more_home_page.dart
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
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.emoji_events),
|
||||||
|
title: const Text('Badges'),
|
||||||
|
onTap: () => context.go('/more/profile'),
|
||||||
|
),
|
||||||
|
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'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -128,10 +128,6 @@ class _NewEntryPageState extends State<NewEntryPage> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
double _manualMilesFromInput(DistanceUnitService units) {
|
|
||||||
return units.milesFromInput(_mileageController.text) ?? 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
double _milesFromInputWithUnit(DistanceUnit unit) {
|
double _milesFromInputWithUnit(DistanceUnit unit) {
|
||||||
return DistanceFormatter(unit)
|
return DistanceFormatter(unit)
|
||||||
.parseInputMiles(_mileageController.text.trim()) ??
|
.parseInputMiles(_mileageController.text.trim()) ??
|
||||||
@@ -155,7 +151,7 @@ class _NewEntryPageState extends State<NewEntryPage> {
|
|||||||
|
|
||||||
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))
|
||||||
@@ -276,6 +272,7 @@ class _NewEntryPageState extends State<NewEntryPage> {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
if (!mounted) return;
|
||||||
if (result != null) {
|
if (result != null) {
|
||||||
final units = _distanceUnits(context);
|
final units = _distanceUnits(context);
|
||||||
setState(() {
|
setState(() {
|
||||||
@@ -1536,43 +1533,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 {
|
||||||
|
|||||||
@@ -52,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()
|
||||||
|
|||||||
@@ -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(
|
||||||
|
|||||||
@@ -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();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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 {
|
||||||
|
|||||||
@@ -232,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),
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
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:mileograph_flutter/services/distance_unit_service.dart';
|
||||||
import 'package:provider/provider.dart';
|
import 'package:provider/provider.dart';
|
||||||
|
|
||||||
@@ -210,6 +211,11 @@ Future<void> showTractionDetails(
|
|||||||
) async {
|
) async {
|
||||||
final hasMileageOrTrips = _hasMileageOrTrips(loco);
|
final hasMileageOrTrips = _hasMileageOrTrips(loco);
|
||||||
final distanceUnits = context.read<DistanceUnitService>();
|
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,
|
||||||
@@ -295,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(),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -307,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(
|
||||||
|
|||||||
@@ -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,64 @@ 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 HomepageStats {
|
class HomepageStats {
|
||||||
@@ -147,10 +210,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),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -443,7 +509,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'] ?? "",
|
||||||
@@ -722,9 +788,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 +801,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 +863,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 {
|
||||||
@@ -941,6 +1062,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 +1222,7 @@ class UserNotification {
|
|||||||
final int id;
|
final int id;
|
||||||
final String title;
|
final String title;
|
||||||
final String body;
|
final String body;
|
||||||
|
final String channel;
|
||||||
final DateTime? createdAt;
|
final DateTime? createdAt;
|
||||||
final bool dismissed;
|
final bool dismissed;
|
||||||
|
|
||||||
@@ -1080,6 +1230,7 @@ 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.createdAt,
|
required this.createdAt,
|
||||||
required this.dismissed,
|
required this.dismissed,
|
||||||
});
|
});
|
||||||
@@ -1096,6 +1247,7 @@ 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']),
|
||||||
createdAt: createdAt,
|
createdAt: createdAt,
|
||||||
dismissed: _asBool(json['dismissed'] ?? false, false),
|
dismissed: _asBool(json['dismissed'] ?? false, false),
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -151,7 +151,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;
|
||||||
|
|||||||
@@ -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) {
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
@@ -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();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -158,7 +158,7 @@ class DistanceFormatter {
|
|||||||
return NumberFormat(pattern);
|
return NumberFormat(pattern);
|
||||||
}
|
}
|
||||||
|
|
||||||
String _formatMilesChains(double miles, {int decimals = 1}) {
|
String _formatMilesChains(double miles) {
|
||||||
final totalChains = miles * DistanceUnitService.chainsPerMile;
|
final totalChains = miles * DistanceUnitService.chainsPerMile;
|
||||||
var milesPart = totalChains ~/ DistanceUnitService.chainsPerMile;
|
var milesPart = totalChains ~/ DistanceUnitService.chainsPerMile;
|
||||||
final chainRemainder =
|
final chainRemainder =
|
||||||
|
|||||||
@@ -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';
|
||||||
@@ -221,6 +223,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 +313,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 +350,28 @@ class _MyHomePageState extends State<MyHomePage> {
|
|||||||
if (data.notifications.isEmpty) {
|
if (data.notifications.isEmpty) {
|
||||||
data.fetchNotifications();
|
data.fetchNotifications();
|
||||||
}
|
}
|
||||||
|
_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;
|
||||||
@@ -895,4 +920,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();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
11
pubspec.yaml
@@ -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.1+1
|
version: 0.5.5+1
|
||||||
|
|
||||||
environment:
|
environment:
|
||||||
sdk: ^3.8.1
|
sdk: ^3.8.1
|
||||||
@@ -102,6 +102,15 @@ 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: "#000000"
|
adaptive_icon_background: "#000000"
|
||||||
adaptive_icon_foreground: assets/icons/app_icon.png
|
adaptive_icon_foreground: assets/icons/app_icon.png
|
||||||
|
|||||||
BIN
web/favicon.png
|
Before Width: | Height: | Size: 917 B After Width: | Height: | Size: 304 B |
|
Before Width: | Height: | Size: 5.2 KiB After Width: | Height: | Size: 2.4 KiB |
|
Before Width: | Height: | Size: 8.1 KiB After Width: | Height: | Size: 6.5 KiB |
|
Before Width: | Height: | Size: 5.5 KiB After Width: | Height: | Size: 2.4 KiB |
|
Before Width: | Height: | Size: 20 KiB After Width: | Height: | Size: 6.5 KiB |
@@ -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>
|
||||||
|
|||||||
@@ -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": [
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 33 KiB After Width: | Height: | Size: 711 B |