Compare commits
16 Commits
27880b2355
...
driver_ui
| Author | SHA1 | Date | |
|---|---|---|---|
| ebcc485f51 | |||
| c09b3f3f66 | |||
| 9d1a37e248 | |||
| fdbdb98b21 | |||
| 0d37750855 | |||
| e95b10abbb | |||
| 9a56b40f50 | |||
| 0e19aa0521 | |||
| 73de0d713e | |||
| 0e10757c49 | |||
| ad48e79db2 | |||
| b04dfba4c7 | |||
| 6e62a9cac1 | |||
| 1e41c05214 | |||
| 86ffce07b0 | |||
| 8caf189c4c |
@@ -0,0 +1,252 @@
|
||||
name: Build and Push Docker Images
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- dev
|
||||
- auth-api
|
||||
- employee-api
|
||||
- transit-api
|
||||
- error-log-api
|
||||
- admin-ui
|
||||
pull_request:
|
||||
branches:
|
||||
- dev
|
||||
|
||||
env:
|
||||
REGISTRY: gitea.testinstance.nl
|
||||
IMAGE_NAMESPACE: sven/the-transit-project
|
||||
|
||||
jobs:
|
||||
detect-changes:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
auth_api: ${{ steps.filter.outputs.auth_api }}
|
||||
employee_api: ${{ steps.filter.outputs.employee_api }}
|
||||
transit_api: ${{ steps.filter.outputs.transit_api }}
|
||||
error_log_api: ${{ steps.filter.outputs.error_log_api }}
|
||||
admin_ui: ${{ steps.filter.outputs.admin_ui }}
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Detect changed paths
|
||||
id: filter
|
||||
uses: dorny/paths-filter@v3
|
||||
with:
|
||||
filters: |
|
||||
auth_api:
|
||||
- 'auth_api/**'
|
||||
- 'docker-compose.yml'
|
||||
- '.gitea/workflows/docker-build.yml'
|
||||
employee_api:
|
||||
- 'employee_api/**'
|
||||
- 'docker-compose.yml'
|
||||
- '.gitea/workflows/docker-build.yml'
|
||||
transit_api:
|
||||
- 'transit_api/**'
|
||||
- 'docker-compose.yml'
|
||||
- '.gitea/workflows/docker-build.yml'
|
||||
error_log_api:
|
||||
- 'error_log_api/**'
|
||||
- 'docker-compose.yml'
|
||||
- '.gitea/workflows/docker-build.yml'
|
||||
admin_ui:
|
||||
- 'admin_ui/**'
|
||||
- 'docker-compose.yml'
|
||||
- '.gitea/workflows/docker-build.yml'
|
||||
|
||||
build-auth-api:
|
||||
needs: detect-changes
|
||||
if: ${{ (gitea.ref_name == 'auth-api' || gitea.ref_name == 'dev') && needs.detect-changes.outputs.auth_api == 'true' }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to Gitea Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ secrets.REGISTRY_USERNAME }}
|
||||
password: ${{ secrets.REGISTRY_PASSWORD }}
|
||||
|
||||
- name: Set image tags
|
||||
id: tags
|
||||
shell: bash
|
||||
run: |
|
||||
image_base="${{ env.REGISTRY }}/${{ env.IMAGE_NAMESPACE }}/auth_api"
|
||||
echo "tags<<EOF" >> "$GITHUB_OUTPUT"
|
||||
echo "${image_base}:${{ gitea.ref_name }}" >> "$GITHUB_OUTPUT"
|
||||
echo "${image_base}:${{ gitea.sha }}" >> "$GITHUB_OUTPUT"
|
||||
echo "EOF" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Build and push auth_api
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: ./auth_api
|
||||
push: ${{ gitea.event_name == 'push' }}
|
||||
tags: ${{ steps.tags.outputs.tags }}
|
||||
|
||||
build-employee-api:
|
||||
needs: detect-changes
|
||||
if: ${{ (gitea.ref_name == 'employee-api' || gitea.ref_name == 'dev') && needs.detect-changes.outputs.employee_api == 'true' }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to Gitea Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ secrets.REGISTRY_USERNAME }}
|
||||
password: ${{ secrets.REGISTRY_PASSWORD }}
|
||||
|
||||
- name: Set image tags
|
||||
id: tags
|
||||
shell: bash
|
||||
run: |
|
||||
image_base="${{ env.REGISTRY }}/${{ env.IMAGE_NAMESPACE }}/employee_api"
|
||||
echo "tags<<EOF" >> "$GITHUB_OUTPUT"
|
||||
echo "${image_base}:${{ gitea.ref_name }}" >> "$GITHUB_OUTPUT"
|
||||
echo "${image_base}:${{ gitea.sha }}" >> "$GITHUB_OUTPUT"
|
||||
echo "EOF" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Build and push employee_api
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: ./employee_api
|
||||
push: ${{ gitea.event_name == 'push' }}
|
||||
tags: ${{ steps.tags.outputs.tags }}
|
||||
|
||||
build-transit-api:
|
||||
needs: detect-changes
|
||||
if: ${{ (gitea.ref_name == 'transit-api' || gitea.ref_name == 'dev') && needs.detect-changes.outputs.transit_api == 'true' }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to Gitea Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ secrets.REGISTRY_USERNAME }}
|
||||
password: ${{ secrets.REGISTRY_PASSWORD }}
|
||||
|
||||
- name: Set image tags
|
||||
id: tags
|
||||
shell: bash
|
||||
run: |
|
||||
image_base="${{ env.REGISTRY }}/${{ env.IMAGE_NAMESPACE }}/transit_api"
|
||||
echo "tags<<EOF" >> "$GITHUB_OUTPUT"
|
||||
echo "${image_base}:${{ gitea.ref_name }}" >> "$GITHUB_OUTPUT"
|
||||
echo "${image_base}:${{ gitea.sha }}" >> "$GITHUB_OUTPUT"
|
||||
echo "EOF" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Build and push transit_api
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: ./transit_api
|
||||
push: ${{ gitea.event_name == 'push' }}
|
||||
tags: ${{ steps.tags.outputs.tags }}
|
||||
|
||||
build-error-log-api:
|
||||
needs: detect-changes
|
||||
if: ${{ (gitea.ref_name == 'error-log-api' || gitea.ref_name == 'dev') && needs.detect-changes.outputs.error_log_api == 'true' }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to Gitea Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ secrets.REGISTRY_USERNAME }}
|
||||
password: ${{ secrets.REGISTRY_PASSWORD }}
|
||||
|
||||
- name: Set image tags
|
||||
id: tags
|
||||
shell: bash
|
||||
run: |
|
||||
image_base="${{ env.REGISTRY }}/${{ env.IMAGE_NAMESPACE }}/error_log_api"
|
||||
echo "tags<<EOF" >> "$GITHUB_OUTPUT"
|
||||
echo "${image_base}:${{ gitea.ref_name }}" >> "$GITHUB_OUTPUT"
|
||||
echo "${image_base}:${{ gitea.sha }}" >> "$GITHUB_OUTPUT"
|
||||
echo "EOF" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Build and push error_log_api
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: ./error_log_api
|
||||
push: ${{ gitea.event_name == 'push' }}
|
||||
tags: ${{ steps.tags.outputs.tags }}
|
||||
|
||||
build-admin-ui:
|
||||
needs: detect-changes
|
||||
if: ${{ (gitea.ref_name == 'admin-ui' || gitea.ref_name == 'dev') && needs.detect-changes.outputs.admin_ui == 'true' }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to Gitea Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ secrets.REGISTRY_USERNAME }}
|
||||
password: ${{ secrets.REGISTRY_PASSWORD }}
|
||||
|
||||
- name: Set image tags
|
||||
id: tags
|
||||
shell: bash
|
||||
run: |
|
||||
image_base="${{ env.REGISTRY }}/${{ env.IMAGE_NAMESPACE }}/admin_ui"
|
||||
echo "tags<<EOF" >> "$GITHUB_OUTPUT"
|
||||
echo "${image_base}:${{ gitea.ref_name }}" >> "$GITHUB_OUTPUT"
|
||||
echo "${image_base}:${{ gitea.sha }}" >> "$GITHUB_OUTPUT"
|
||||
echo "EOF" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Build and push admin_ui
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: ./admin_ui
|
||||
push: ${{ gitea.event_name == 'push' }}
|
||||
tags: ${{ steps.tags.outputs.tags }}
|
||||
|
||||
deploy-test-node:
|
||||
needs:
|
||||
[
|
||||
detect-changes,
|
||||
build-auth-api,
|
||||
build-employee-api,
|
||||
build-transit-api,
|
||||
build-error-log-api,
|
||||
build-admin-ui,
|
||||
]
|
||||
if: ${{ gitea.event_name == 'push' && gitea.ref_name == 'dev' }}
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Redeploy Portainer stack
|
||||
shell: bash
|
||||
run: curl --fail --silent --show-error --retry 3 --max-time 30 -X POST "$PORTAINER_WEBHOOK_URL"
|
||||
env:
|
||||
PORTAINER_WEBHOOK_URL: ${{ secrets.PORTAINER_WEBHOOK_URL }}
|
||||
@@ -1,196 +0,0 @@
|
||||
name: Build and Push Docker Images
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- develop
|
||||
paths:
|
||||
- 'auth_api/**'
|
||||
- 'employee_api/**'
|
||||
- 'transit_api/**'
|
||||
- 'admin_ui/**'
|
||||
- '.github/workflows/docker-build.yml'
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
- develop
|
||||
|
||||
env:
|
||||
# GitHub Container Registry
|
||||
REGISTRY: ghcr.io
|
||||
# Dockerhub alternative (uncomment to use instead)
|
||||
# REGISTRY: docker.io
|
||||
# REGISTRY_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
|
||||
jobs:
|
||||
build-auth-api:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
# For DockerHub, use instead:
|
||||
# username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
# password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Extract metadata
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ github.repository }}/auth_api
|
||||
tags: |
|
||||
type=ref,event=branch
|
||||
type=semver,pattern={{version}}
|
||||
type=semver,pattern={{major}}.{{minor}}
|
||||
type=sha,prefix={{branch}}-
|
||||
type=raw,value=latest,enable={{is_default_branch}}
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: ./auth_api
|
||||
push: ${{ github.event_name != 'pull_request' }}
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
|
||||
build-employee-api:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Extract metadata
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ github.repository }}/employee_api
|
||||
tags: |
|
||||
type=ref,event=branch
|
||||
type=semver,pattern={{version}}
|
||||
type=semver,pattern={{major}}.{{minor}}
|
||||
type=sha,prefix={{branch}}-
|
||||
type=raw,value=latest,enable={{is_default_branch}}
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: ./employee_api
|
||||
push: ${{ github.event_name != 'pull_request' }}
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
|
||||
build-transit-api:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Extract metadata
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ github.repository }}/transit_api
|
||||
tags: |
|
||||
type=ref,event=branch
|
||||
type=semver,pattern={{version}}
|
||||
type=semver,pattern={{major}}.{{minor}}
|
||||
type=sha,prefix={{branch}}-
|
||||
type=raw,value=latest,enable={{is_default_branch}}
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: ./transit_api
|
||||
push: ${{ github.event_name != 'pull_request' }}
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
|
||||
build-admin-ui:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Extract metadata
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ github.repository }}/admin_ui
|
||||
tags: |
|
||||
type=ref,event=branch
|
||||
type=semver,pattern={{version}}
|
||||
type=semver,pattern={{major}}.{{minor}}
|
||||
type=sha,prefix={{branch}}-
|
||||
type=raw,value=latest,enable={{is_default_branch}}
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: ./admin_ui
|
||||
push: ${{ github.event_name != 'pull_request' }}
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
@@ -1,21 +1,60 @@
|
||||
# Environment and secrets
|
||||
.env
|
||||
/*.env
|
||||
transit_api/.env
|
||||
.env.*
|
||||
!.env.example
|
||||
**/.env
|
||||
**/.env.*
|
||||
!**/.env.example
|
||||
|
||||
# Local build / node_modules
|
||||
# Node.js
|
||||
node_modules/
|
||||
admin_ui/node_modules/
|
||||
admin_ui/dist/
|
||||
coverage/
|
||||
dist/
|
||||
build/
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
|
||||
# Sensitive docs to keep private
|
||||
# Flutter / Dart
|
||||
**/.dart_tool/
|
||||
**/.pub-cache/
|
||||
**/.pub/
|
||||
**/build/
|
||||
**/.flutter-plugins
|
||||
**/.flutter-plugins-dependencies
|
||||
|
||||
# Database and local artifacts
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
*.db
|
||||
dump.sql
|
||||
|
||||
# Certificates and keys
|
||||
*.pem
|
||||
*.key
|
||||
*.crt
|
||||
*.p12
|
||||
|
||||
# OS/editor files
|
||||
.DS_Store
|
||||
.vscode/
|
||||
.idea/
|
||||
|
||||
# Sensitive project docs
|
||||
ADMIN_DEPLOYMENT_SUMMARY.md
|
||||
CI_CD_PORTAINER_GUIDE.md
|
||||
DEPLOYMENT.md
|
||||
GETTING_STARTED.md
|
||||
handoff.md
|
||||
INTERNAL_*.md
|
||||
SETUP_*.md
|
||||
DEPLOY_*.md
|
||||
|
||||
# Custom instruction files (private)
|
||||
# Private instructions and tooling files
|
||||
.instructions.md
|
||||
.prompt.md
|
||||
.agent.md
|
||||
@@ -23,15 +62,26 @@ SKILL.md
|
||||
copilot-instructions.md
|
||||
AGENTS.md
|
||||
|
||||
# Private scripts
|
||||
# Local/private scripts
|
||||
scripts/private/
|
||||
scripts/*.local.*
|
||||
scripts/.env
|
||||
|
||||
# Private timetable note
|
||||
# Project-specific private notes
|
||||
transit_api/LOCAL_BUS_TIMETABLE_README.md
|
||||
|
||||
# Runtime files
|
||||
*.log
|
||||
*.sqlite3
|
||||
.DS_Store
|
||||
# Deprecated app backups and legacy artifacts
|
||||
deprecated/build/
|
||||
deprecated/.dart_tool/
|
||||
deprecated/.pub-cache/
|
||||
deprecated/.idea/
|
||||
deprecated/.vscode/
|
||||
|
||||
# Runtime logs
|
||||
auth_api.log
|
||||
transit_api.log
|
||||
error_log_api.log
|
||||
|
||||
# Temporary files
|
||||
tmp/
|
||||
temp/
|
||||
|
||||
@@ -24,7 +24,7 @@ POSTGRES_PASSWORD_AUTH=your_password
|
||||
POSTGRES_USER_TRANSIT=transitAPI
|
||||
POSTGRES_PASSWORD_TRANSIT=your_password
|
||||
JWT_SECRET=your-secure-secret
|
||||
ADMIN_USER_CODES=42
|
||||
# ADMIN_USER_CODES should be set in auth_api/.env (comma-separated admin user codes)
|
||||
```
|
||||
|
||||
### Step 3: Start Services
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
# Transit Project
|
||||
|
||||
Dit repository bevat een suite van drie Node.js microservices (APIs) en bijbehorende tooling:
|
||||
Dit repository bevat een suite van Node.js microservices, een admin webapp en een legacy desktop client die momenteel als deprecated wordt bewaard.
|
||||
|
||||
- `auth_api` — Authenticatie en token-uitgifte (standaard port 5000)
|
||||
- `employee_api` — Employee onboarding / management (standaard port 4000)
|
||||
- `transit_api` — Transit/schedule endpoints (standaard port 5001)
|
||||
- `error_log_api` — Centrale foutlogging en viewer (standaard port 5003)
|
||||
- `admin_ui` — React + Vite beheerinterface
|
||||
- `deprecated/` — legacy Flutter bus terminal, retained for reference while moving the client to a Windows XP-era build path
|
||||
|
||||
Er is ook een GitHub Actions workflow aanwezig die Docker images bouwt en pusht naar GitHub Container Registry (GHCR).
|
||||
|
||||
@@ -22,6 +25,7 @@ Belangrijk: deze README bevat geen wachtwoorden of andere gevoelige gegevens. Sl
|
||||
- Guidelines for adding new private files
|
||||
|
||||
**Private files are excluded** (not in git/docker):
|
||||
|
||||
- `GETTING_STARTED.md` - Internal setup guide
|
||||
- `ADMIN_DEPLOYMENT_SUMMARY.md` - Deployment status
|
||||
- `CI_CD_PORTAINER_GUIDE.md` - Infrastructure docs
|
||||
@@ -77,9 +81,14 @@ POSTGRES_USER_EMPLOYEE=employee_user
|
||||
POSTGRES_PASSWORD_EMPLOYEE=strong_password_employee
|
||||
POSTGRES_USER_TRANSIT=transit_user
|
||||
POSTGRES_PASSWORD_TRANSIT=strong_password_transit
|
||||
POSTGRES_USER_ERROR_LOG=error_logger
|
||||
POSTGRES_PASSWORD_ERROR_LOG=strong_password_error_log
|
||||
|
||||
# JWT secret voor services die JWT gebruiken
|
||||
JWT_SECRET=super_secret_jwt_key_here
|
||||
|
||||
# Optioneel: centraal error log endpoint voor clients/services
|
||||
ERROR_LOG_API_URL=http://error_log_api:5003/error_log
|
||||
```
|
||||
|
||||
Opmerking: de exacte variabelen worden gelezen door `docker-compose.yml`. Pas de namen/waarden aan naar jouw omgeving.
|
||||
@@ -119,6 +128,7 @@ Tip: tijdens development kun je één Postgres instance gebruiken en schema/roll
|
||||
Deze repository bevat `docker-compose.yml` die images vanuit GHCR trekt. De compose is aangepast om een externe Postgres te gebruiken.
|
||||
|
||||
Voordat je start:
|
||||
|
||||
- Zorg dat je `.env` met database credentials en `JWT_SECRET` klaar staat op de server.
|
||||
- Zorg dat de host waar je compose draait netwerk-connectiviteit heeft naar de Postgres host.
|
||||
|
||||
@@ -156,10 +166,12 @@ Het project bevat een workflow in `.github/workflows/docker-build.yml` die bij p
|
||||
- Genereert tags (`latest`, branch/sha, semver als aanwezig)
|
||||
|
||||
Om GHCR te gebruiken op je server:
|
||||
|
||||
1. Maak een Personal Access Token (PAT) met `read:packages` (en `write:packages` indien je zelf ook wilt pushen).
|
||||
2. Login op de server: `docker login ghcr.io` (gebruik PAT als wachtwoord).
|
||||
|
||||
Image naam voorbeeld:
|
||||
|
||||
```
|
||||
ghcr.io/<github-username>/<repo>/auth_api:latest
|
||||
```
|
||||
@@ -185,6 +197,7 @@ docker logs -f auth_api
|
||||
```
|
||||
|
||||
Problemen met DB-verbinding:
|
||||
|
||||
- Controleer netwerkconnectiviteit naar `POSTGRES_HOST`
|
||||
- Controleer users/permissions in Postgres
|
||||
- Controleer dat de juiste schema (zoals `workers`) bestaat als de queries die verwachten
|
||||
@@ -215,9 +228,34 @@ docker login ghcr.io
|
||||
## Migraties & Database schema
|
||||
|
||||
Database schema en migraties zitten niet in deze repository. Zorg dat je:
|
||||
|
||||
- de juiste schema's (`workers`, `routes`, etc.) aanmaakt
|
||||
- gebruikers en rechten configureert voor de verschillende services
|
||||
|
||||
### Error logging schema
|
||||
|
||||
Voor de centrale foutlogging maak je schema `data` en tabel `data.errors` aan:
|
||||
|
||||
```sql
|
||||
CREATE SCHEMA IF NOT EXISTS data;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS data.errors (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
"date" TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
"service" TEXT NOT NULL,
|
||||
"partOfService" TEXT,
|
||||
"error" TEXT NOT NULL
|
||||
);
|
||||
```
|
||||
|
||||
Gebruik een aparte gebruiker met minimale rechten, bijvoorbeeld `error_logger`:
|
||||
|
||||
```sql
|
||||
CREATE ROLE error_logger LOGIN PASSWORD 'strong_password_error_log';
|
||||
GRANT USAGE ON SCHEMA data TO error_logger;
|
||||
GRANT INSERT, SELECT ON data.errors TO error_logger;
|
||||
```
|
||||
|
||||
Als je nog geen database hebt, kun je lokaal een Postgres container gebruiken (development):
|
||||
|
||||
```bash
|
||||
@@ -310,20 +348,23 @@ docker-compose up admin_ui
|
||||
The Transit API exposes public (unauthenticated) schedule endpoints:
|
||||
|
||||
**Endpoints:**
|
||||
|
||||
- `GET /schedules?date=YYYY-MM-DD&lineId=ID` — Get schedules for a date/line
|
||||
- `GET /schedules/:scheduleId` — Get schedule details
|
||||
- `GET /schedules/:scheduleId/stops` — Get stops on a schedule's line
|
||||
|
||||
**Example:**
|
||||
|
||||
```bash
|
||||
curl http://localhost:5001/schedules?date=2026-05-06
|
||||
```
|
||||
|
||||
**TimetableViewer Component:**
|
||||
```jsx
|
||||
import TimetableViewer from './components/TimetableViewer'
|
||||
|
||||
<TimetableViewer apiBaseUrl="http://api.transit.local:5001" />
|
||||
```jsx
|
||||
import TimetableViewer from "./components/TimetableViewer";
|
||||
|
||||
<TimetableViewer apiBaseUrl="http://api.transit.local:5001" />;
|
||||
```
|
||||
|
||||
### Schedule Maker Documentation
|
||||
@@ -340,10 +381,11 @@ Admin dashboard uses simple JWT-based authentication:
|
||||
2. Receive JWT token from `auth_api`
|
||||
3. Use token for admin operations (`/admin/*` endpoints)
|
||||
|
||||
Admin authorization is controlled by `ADMIN_USER_CODES` environment variable:
|
||||
Admin authorization is controlled by `ADMIN_USER_CODES` environment variable configured in the `auth_api` service:
|
||||
|
||||
```bash
|
||||
ADMIN_USER_CODES=42,101,205 # Comma-separated admin user codes
|
||||
# Set admin user codes for the auth service (comma-separated)
|
||||
ADMIN_USER_CODES=42,101,205
|
||||
```
|
||||
|
||||
---
|
||||
@@ -355,7 +397,8 @@ ADMIN_USER_CODES=42,101,205 # Comma-separated admin user codes
|
||||
Use `DEV_MOCK=1` to work without a database (in-memory mock storage):
|
||||
|
||||
```bash
|
||||
ADMIN_USER_CODES=42 DEV_MOCK=1 JWT_SECRET=devsecret npm --prefix ./transit_api start
|
||||
# For local development set admin codes on the auth_api and start services
|
||||
ADMIN_USER_CODES=42 DEV_MOCK=1 JWT_SECRET=devsecret npm --prefix ./auth_api start
|
||||
```
|
||||
|
||||
### Production Mode
|
||||
@@ -364,4 +407,4 @@ Set up real PostgreSQL database and provide credentials via environment variable
|
||||
|
||||
---
|
||||
|
||||
Als je wilt, kan ik deze README nog aanpassen met specifieke voorbeelden van database schema's of exacte environment-variabele namen voor lokaal draaien. Zeg welke details je wil toevoegen (bijv. example SQL voor `workers` schema).
|
||||
Als je wilt, kan ik deze README nog aanpassen met specifieke voorbeelden van database schema's of exacte environment-variabele namen voor lokaal draaien. Zeg welke details je wil toevoegen (bijv. example SQL voor `workers` schema).
|
||||
|
||||
@@ -5,15 +5,17 @@ This document explains which files are kept private and why.
|
||||
## Files Excluded from Git & Docker
|
||||
|
||||
### Deployment Documentation (Private)
|
||||
|
||||
- `ADMIN_DEPLOYMENT_SUMMARY.md` - Internal deployment status and setup details
|
||||
- `CI_CD_PORTAINER_GUIDE.md` - Private CI/CD and Portainer configuration
|
||||
- `DEPLOYMENT.md` - Deployment procedures and configuration guidance
|
||||
- `GETTING_STARTED.md` - Internal setup instructions
|
||||
- `INTERNAL_*.md` - Any file prefixed with INTERNAL_ (pattern-based exclusion)
|
||||
- `SETUP_*.md` - Any file prefixed with SETUP_ (pattern-based exclusion)
|
||||
- `DEPLOY_*.md` - Any file prefixed with DEPLOY_ (pattern-based exclusion)
|
||||
- `INTERNAL_*.md` - Any file prefixed with INTERNAL\_ (pattern-based exclusion)
|
||||
- `SETUP_*.md` - Any file prefixed with SETUP\_ (pattern-based exclusion)
|
||||
- `DEPLOY_*.md` - Any file prefixed with DEPLOY\_ (pattern-based exclusion)
|
||||
|
||||
### Custom Instruction Files (Private)
|
||||
|
||||
- `.instructions.md` - GitHub Copilot custom instructions
|
||||
- `.prompt.md` - Custom prompt templates
|
||||
- `.agent.md` - Custom agent definitions
|
||||
@@ -22,26 +24,30 @@ This document explains which files are kept private and why.
|
||||
- `AGENTS.md` - Agent configuration
|
||||
|
||||
These are kept private to prevent exposure of:
|
||||
|
||||
- Development workflow details
|
||||
- Copilot customization strategies
|
||||
- Internal coding guidelines and preferences
|
||||
- Prompt engineering techniques
|
||||
|
||||
### Private Scripts
|
||||
|
||||
- `scripts/private/` - Directory for private deployment scripts
|
||||
- `scripts/*.local.*` - Local-specific script configurations
|
||||
|
||||
## Files Included in Public Repo
|
||||
|
||||
### Public Documentation
|
||||
|
||||
- `README.md` - Main project documentation
|
||||
- `DOCKER_README.md` - Docker usage documentation
|
||||
- `admin_ui/README.md` - Admin UI documentation
|
||||
- `admin_ui/SCHEDULE_API.md` - Public API documentation
|
||||
- `transit_api/README.md` - API documentation
|
||||
- `bus_terminal/README.md` - Flutter app documentation
|
||||
- `deprecated/README.md` - Legacy Flutter bus terminal documentation kept for historical reference
|
||||
|
||||
### Configuration
|
||||
|
||||
- `.env.example` - Environment variable template (no secrets)
|
||||
- `.gitignore` - Git exclusion rules
|
||||
- `.dockerignore` - Docker build exclusion rules
|
||||
@@ -49,13 +55,15 @@ These are kept private to prevent exposure of:
|
||||
- `Dockerfile` files - Container definitions
|
||||
|
||||
### Code & Configuration
|
||||
- All source code in `auth_api/`, `transit_api/`, `employee_api/`, `admin_ui/`, `bus_terminal/`
|
||||
|
||||
- All source code in `auth_api/`, `transit_api/`, `employee_api/`, `admin_ui/`, and the legacy `deprecated/` app
|
||||
- `package.json` files (no secrets, only dependencies)
|
||||
- GitHub Actions workflows in `.github/workflows/`
|
||||
|
||||
## Environment Variables - NEVER Commit
|
||||
|
||||
Always keep the following OUT of git:
|
||||
|
||||
- `.env` - Local environment variables (in `.gitignore`)
|
||||
- Database credentials
|
||||
- JWT secrets
|
||||
@@ -67,6 +75,7 @@ Use `.env.example` as a template and create local `.env` files for development.
|
||||
## Docker Build Security
|
||||
|
||||
All `.dockerignore` files (root and per-service) ensure that:
|
||||
|
||||
1. Sensitive documentation never enters Docker images
|
||||
2. Private scripts and configs are excluded from builds
|
||||
3. Only necessary source code and dependencies are included
|
||||
@@ -75,6 +84,7 @@ All `.dockerignore` files (root and per-service) ensure that:
|
||||
## GitHub Actions Security
|
||||
|
||||
The CI/CD workflow in `.github/workflows/docker-build.yml`:
|
||||
|
||||
- Only builds from specific service directories (auth_api, transit_api, etc.)
|
||||
- Respects `.dockerignore` rules
|
||||
- Uses GitHub secrets for credentials (never hardcoded)
|
||||
@@ -93,12 +103,14 @@ The CI/CD workflow in `.github/workflows/docker-build.yml`:
|
||||
To keep new private files out of the repo and Docker:
|
||||
|
||||
1. Add pattern to `.gitignore`:
|
||||
|
||||
```
|
||||
MYFILE_*.md
|
||||
new_private_thing.*
|
||||
```
|
||||
|
||||
2. Add pattern to `.dockerignore` (root and per-service):
|
||||
|
||||
```
|
||||
/MYFILE_*.md
|
||||
/new_private_thing.*
|
||||
|
||||
@@ -10,6 +10,7 @@ Modern React + Vite web application for comprehensive transit system administrat
|
||||
✅ **Stop Linking** - Assign stops to bus lines with order and ETA
|
||||
✅ **JWT Authentication** - Secure authentication with role-based access
|
||||
✅ **Production Ready** - Docker containerized with runtime env configuration
|
||||
✅ **Error Log Viewer** - Inspect centralized error logs from all services
|
||||
|
||||
## Local Development
|
||||
|
||||
@@ -31,6 +32,7 @@ Create a `.env` file in the `admin_ui` directory:
|
||||
```env
|
||||
VITE_AUTH_API=http://localhost:5000
|
||||
VITE_TRANSIT_API=http://localhost:5001
|
||||
VITE_ERROR_LOG_API=http://localhost:5003
|
||||
```
|
||||
|
||||
### Run Development Server
|
||||
@@ -109,12 +111,14 @@ When running in Docker, environment variables are injected at runtime via `docke
|
||||
- `BusLinesManager.jsx` - Create/list bus routes
|
||||
- `FleetManager.jsx` - View fleet vehicles
|
||||
- `LinkStop.jsx` - Link stops to bus lines
|
||||
- `ErrorLogViewer.jsx` - Central error log viewer
|
||||
|
||||
### API Integration
|
||||
|
||||
The app communicates with:
|
||||
- **Auth API** (/login, /me)
|
||||
- **Transit API** (/admin/stops, /admin/bus-lines, /admin/fleet/buses)
|
||||
- **Error Log API** (/error_log)
|
||||
|
||||
All requests include JWT Bearer token for authentication.
|
||||
|
||||
@@ -130,7 +134,7 @@ All requests include JWT Bearer token for authentication.
|
||||
|
||||
### Admin Authorization
|
||||
|
||||
Users must have a `userCode` in their JWT that matches `ADMIN_USER_CODES` environment variable in the transit API to access admin endpoints.
|
||||
Users must have a `userCode` in their JWT and, for admin access, the `isAdmin` flag set by the `auth_api` based on the `ADMIN_USER_CODES` environment variable.
|
||||
|
||||
### Production Setup
|
||||
|
||||
@@ -139,6 +143,7 @@ Users must have a `userCode` in their JWT that matches `ADMIN_USER_CODES` enviro
|
||||
3. Configure proper JWT generation in auth_api
|
||||
4. Set strong `JWT_SECRET` environment variable
|
||||
5. Configure `ADMIN_USER_CODES` with actual admin user IDs
|
||||
6. Configure `VITE_ERROR_LOG_API` if you use a custom logging endpoint
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
|
||||
@@ -4,7 +4,8 @@ set -e
|
||||
cat > /usr/share/nginx/html/env-config.js <<EOF
|
||||
window.__ENV__ = {
|
||||
AUTH_API: "${AUTH_API:-http://localhost:5000}",
|
||||
TRANSIT_API: "${TRANSIT_API:-http://localhost:5001}"
|
||||
TRANSIT_API: "${TRANSIT_API:-http://localhost:5001}",
|
||||
ERROR_LOG_API: "${ERROR_LOG_API:-http://localhost:5003}"
|
||||
}
|
||||
EOF
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import LinkStop from './components/LinkStop'
|
||||
import BusLinesManager from './components/BusLinesManager'
|
||||
import FleetManager from './components/FleetManager'
|
||||
import ScheduleMaker from './components/ScheduleMaker'
|
||||
import ErrorLogViewer from './components/ErrorLogViewer'
|
||||
|
||||
export default function App() {
|
||||
const [token, setToken] = useState(localStorage.getItem('token'))
|
||||
@@ -46,6 +47,7 @@ export default function App() {
|
||||
<FleetManager token={token} user={user} />
|
||||
<LinkStop token={token} user={user} />
|
||||
<ScheduleMaker token={token} user={user} />
|
||||
<ErrorLogViewer token={token} />
|
||||
</main>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -14,9 +14,38 @@ const normalizeApiBaseUrl = (value, fallbackPath) => {
|
||||
|
||||
const AUTH_API = normalizeApiBaseUrl(RUNTIME.AUTH_API || import.meta.env.VITE_AUTH_API, 'http://localhost:5000')
|
||||
const TRANSIT_API = normalizeApiBaseUrl(RUNTIME.TRANSIT_API || import.meta.env.VITE_TRANSIT_API, 'http://localhost:5001')
|
||||
const ERROR_LOG_API = normalizeApiBaseUrl(RUNTIME.ERROR_LOG_API || import.meta.env.VITE_ERROR_LOG_API, 'http://localhost:5003')
|
||||
|
||||
const reportClientError = async ({ service, partOfService, error }) => {
|
||||
try {
|
||||
await fetch(`${ERROR_LOG_API}/error_log`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
service,
|
||||
partOfService,
|
||||
error: typeof error === 'string' ? error : JSON.stringify(error),
|
||||
}),
|
||||
})
|
||||
} catch (e) {
|
||||
// ignore logging failures
|
||||
}
|
||||
}
|
||||
|
||||
export const authClient = axios.create({ baseURL: AUTH_API })
|
||||
|
||||
authClient.interceptors.response.use(
|
||||
response => response,
|
||||
error => {
|
||||
void reportClientError({
|
||||
service: 'admin_ui',
|
||||
partOfService: 'authClient',
|
||||
error: error?.response?.data?.error || error?.message || 'authClient_error',
|
||||
})
|
||||
return Promise.reject(error)
|
||||
}
|
||||
)
|
||||
|
||||
export const transitClient = (token) => {
|
||||
const client = axios.create({
|
||||
baseURL: TRANSIT_API,
|
||||
@@ -35,6 +64,11 @@ export const transitClient = (token) => {
|
||||
// reload to let App show the Login screen
|
||||
if (typeof window !== 'undefined') window.location.reload()
|
||||
}
|
||||
void reportClientError({
|
||||
service: 'admin_ui',
|
||||
partOfService: 'transitClient',
|
||||
error: error?.response?.data?.error || error?.message || 'transitClient_error',
|
||||
})
|
||||
} catch (e) {
|
||||
// ignore
|
||||
}
|
||||
@@ -44,3 +78,10 @@ export const transitClient = (token) => {
|
||||
|
||||
return client
|
||||
}
|
||||
|
||||
export const errorLogClient = (token) => axios.create({
|
||||
baseURL: ERROR_LOG_API,
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : {},
|
||||
})
|
||||
|
||||
export { reportClientError }
|
||||
|
||||
@@ -11,7 +11,7 @@ export default function BusLinesManager({ token, user }) {
|
||||
const [estimatedDurationMinutes, setEstimatedDurationMinutes] = useState('')
|
||||
const [description, setDescription] = useState('')
|
||||
const [message, setMessage] = useState(null)
|
||||
const [isAdmin] = useState(Boolean(user?.userCode))
|
||||
const [isAdmin] = useState(Boolean(user?.isAdmin))
|
||||
const [deleteConfirm, setDeleteConfirm] = useState(null)
|
||||
const [editingLine, setEditingLine] = useState(null)
|
||||
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import React, { useEffect, useMemo, useState } from 'react'
|
||||
import { errorLogClient } from '../api'
|
||||
|
||||
const formatDate = (value) => {
|
||||
if (!value) return '—'
|
||||
try {
|
||||
return new Date(value).toLocaleString()
|
||||
} catch (_) {
|
||||
return String(value)
|
||||
}
|
||||
}
|
||||
|
||||
export default function ErrorLogViewer({ token }) {
|
||||
const client = useMemo(() => errorLogClient(token), [token])
|
||||
const [logs, setLogs] = useState([])
|
||||
const [service, setService] = useState('')
|
||||
const [partOfService, setPartOfService] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [message, setMessage] = useState(null)
|
||||
|
||||
const loadLogs = async () => {
|
||||
setLoading(true)
|
||||
setMessage(null)
|
||||
try {
|
||||
const params = { limit: 100 }
|
||||
if (service) params.service = service
|
||||
if (partOfService) params.partOfService = partOfService
|
||||
const res = await client.get('/error_log', { params })
|
||||
setLogs(res.data.errors || [])
|
||||
} catch (err) {
|
||||
setMessage(err.response?.data?.error || err.message || 'Kon fouten niet laden')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
loadLogs()
|
||||
}, [service, partOfService])
|
||||
|
||||
return (
|
||||
<section className="card">
|
||||
<div className="section-header">
|
||||
<div>
|
||||
<h2>Error log</h2>
|
||||
<p>Laatste foutmeldingen uit de centrale logging service.</p>
|
||||
</div>
|
||||
<button className="secondary" onClick={loadLogs} disabled={loading}>
|
||||
{loading ? 'Laden...' : 'Ververs'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="form-row">
|
||||
<input placeholder="Service filter" value={service} onChange={e => setService(e.target.value)} />
|
||||
<input placeholder="Part of service filter" value={partOfService} onChange={e => setPartOfService(e.target.value)} />
|
||||
</div>
|
||||
|
||||
{message && <div className="message">{message}</div>}
|
||||
|
||||
<div className="list-grid">
|
||||
{logs.map(log => (
|
||||
<article className="mini-card" key={log.id}>
|
||||
<strong>{log.service}</strong>
|
||||
<div>{formatDate(log.date)}</div>
|
||||
<div className="muted" style={{ marginTop: 6 }}>{log.partOfService || '—'}</div>
|
||||
<div style={{ marginTop: 8 }}>{log.error}</div>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{!logs.length && !message && <div className="muted">Nog geen foutmeldingen gevonden.</div>}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -9,7 +9,7 @@ export default function FleetManager({ token, user }) {
|
||||
const [licensePlate, setLicensePlate] = useState('')
|
||||
const [message, setMessage] = useState(null)
|
||||
const [canCreateBus, setCanCreateBus] = useState(true)
|
||||
const [isAdmin] = useState(Boolean(user?.userCode))
|
||||
const [isAdmin] = useState(Boolean(user?.isAdmin))
|
||||
const [editingBus, setEditingBus] = useState(null)
|
||||
const [deleteConfirm, setDeleteConfirm] = useState(null)
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ export default function LinkStop({ token, user }) {
|
||||
const [draggedItem, setDraggedItem] = useState(null)
|
||||
const [deleteConfirm, setDeleteConfirm] = useState(null)
|
||||
|
||||
const isAdmin = Boolean(user?.userCode)
|
||||
const isAdmin = Boolean(user?.isAdmin)
|
||||
|
||||
const nextOrder = useMemo(() => stops.length + 1, [stops])
|
||||
|
||||
|
||||
@@ -1,52 +1,25 @@
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { transitClient } from '../api'
|
||||
|
||||
const WEEKDAYS = ['Ma', 'Di', 'Wo', 'Do', 'Vr', 'Za', 'Zo']
|
||||
const WEEKDAY_VALUES = [1, 2, 3, 4, 5, 6, 0] // 0=Sun, 1=Mon...
|
||||
import TimetableDisplay from './TimetableDisplay'
|
||||
import FixedScheduleEditor from './FixedScheduleEditor'
|
||||
|
||||
export default function ScheduleMaker({ token, user }) {
|
||||
const client = transitClient(token)
|
||||
const [schedules, setSchedules] = useState([])
|
||||
const [overviewSchedules, setOverviewSchedules] = useState([])
|
||||
const [scheduleTemplates, setScheduleTemplates] = useState([])
|
||||
const [busLines, setBusLines] = useState([])
|
||||
const [buses, setBuses] = useState([])
|
||||
const [drivers, setDrivers] = useState([])
|
||||
const [selectedDriverFilter, setSelectedDriverFilter] = useState('')
|
||||
const [message, setMessage] = useState(null)
|
||||
const [isAdmin] = useState(Boolean(user?.userCode))
|
||||
const [deleteConfirm, setDeleteConfirm] = useState(null)
|
||||
const [expandedSchedule, setExpandedSchedule] = useState(null)
|
||||
const [routeStopsByLine, setRouteStopsByLine] = useState({})
|
||||
|
||||
// Form state
|
||||
const [selectedLine, setSelectedLine] = useState('')
|
||||
const [selectedBus, setSelectedBus] = useState('')
|
||||
const [selectedDate, setSelectedDate] = useState(new Date().toISOString().split('T')[0])
|
||||
const [isAdmin] = useState(Boolean(user?.isAdmin))
|
||||
const [overviewDate, setOverviewDate] = useState(new Date().toISOString().split('T')[0])
|
||||
const [startTime, setStartTime] = useState('08:00')
|
||||
const [driverId, setDriverId] = useState('')
|
||||
const [selectedWeekdays, setSelectedWeekdays] = useState([])
|
||||
|
||||
const loadSchedules = async () => {
|
||||
const loadScheduleTemplates = async () => {
|
||||
try {
|
||||
const res = await client.get('/admin/schedules')
|
||||
setSchedules(res.data.schedules || [])
|
||||
const res = await client.get('/admin/schedules?templates=1')
|
||||
setScheduleTemplates((res.data.schedules || []).filter(schedule => Array.isArray(schedule.weekdays) && schedule.weekdays.length > 0))
|
||||
} catch (err) {
|
||||
setMessage('Error loading schedules: ' + (err.response?.data?.error || err.message))
|
||||
}
|
||||
}
|
||||
|
||||
const loadOverviewSchedules = async () => {
|
||||
try {
|
||||
const params = new URLSearchParams({ date: overviewDate })
|
||||
if (selectedDriverFilter) {
|
||||
params.set('driverId', selectedDriverFilter)
|
||||
}
|
||||
|
||||
const res = await client.get(`/schedules/overview?${params.toString()}`)
|
||||
setOverviewSchedules(res.data.schedules || [])
|
||||
} catch (err) {
|
||||
setMessage('Error loading timetable: ' + (err.response?.data?.error || err.message))
|
||||
setMessage('Error loading fixed schedules: ' + (err.response?.data?.error || err.message))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,529 +51,43 @@ export default function ScheduleMaker({ token, user }) {
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
loadSchedules()
|
||||
loadScheduleTemplates()
|
||||
loadBusLines()
|
||||
loadBuses()
|
||||
loadDrivers()
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
loadOverviewSchedules()
|
||||
}, [overviewDate, selectedDriverFilter])
|
||||
|
||||
const createSchedule = async (e) => {
|
||||
e.preventDefault()
|
||||
setMessage(null)
|
||||
|
||||
if (!selectedLine || !selectedBus || !startTime) {
|
||||
setMessage('Lijn, voertuig en start-tijd zijn verplicht')
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const startDateTime = `${selectedDate}T${startTime}:00`
|
||||
const normalizedWeekdays = [...selectedWeekdays].sort((a, b) => a - b)
|
||||
|
||||
const res = await client.post('/admin/schedules', {
|
||||
busLineId: Number(selectedLine),
|
||||
busId: Number(selectedBus),
|
||||
driverId: driverId ? Number(driverId) : null,
|
||||
startTime: startDateTime,
|
||||
weekdays: normalizedWeekdays,
|
||||
})
|
||||
|
||||
const dayLabels = normalizedWeekdays.length > 0
|
||||
? normalizedWeekdays.map(d => WEEKDAYS[WEEKDAY_VALUES.indexOf(d)]).join(', ')
|
||||
: 'eenmalig'
|
||||
setMessage(`Dienst aangemaakt: #${res.data.schedule.id} (${dayLabels})`)
|
||||
setSelectedLine('')
|
||||
setSelectedBus('')
|
||||
setStartTime('08:00')
|
||||
setDriverId('')
|
||||
setSelectedWeekdays([])
|
||||
await loadSchedules()
|
||||
await loadOverviewSchedules()
|
||||
} catch (err) {
|
||||
const errMsg = err.response?.data?.error || err.message
|
||||
setMessage('Error: ' + errMsg)
|
||||
}
|
||||
const handleScheduleChange = async () => {
|
||||
await loadScheduleTemplates()
|
||||
}
|
||||
|
||||
const deleteSchedule = async (scheduleId, lineNumber, busName) => {
|
||||
setMessage(null)
|
||||
try {
|
||||
await client.delete(`/admin/schedules/${scheduleId}`)
|
||||
setMessage(`Dienst verwijderd: Lijn ${lineNumber}, ${busName}`)
|
||||
setDeleteConfirm(null)
|
||||
await loadSchedules()
|
||||
await loadOverviewSchedules()
|
||||
} catch (err) {
|
||||
const errMsg = err.response?.data?.error || err.message
|
||||
setMessage('Error: ' + errMsg)
|
||||
}
|
||||
}
|
||||
|
||||
const toggleWeekday = (dayValue) => {
|
||||
setSelectedWeekdays(prev =>
|
||||
prev.includes(dayValue)
|
||||
? prev.filter(d => d !== dayValue)
|
||||
: [...prev, dayValue]
|
||||
)
|
||||
}
|
||||
|
||||
const getWeekdayLabel = (weekdayValues) => {
|
||||
if (!weekdayValues || weekdayValues.length === 0) return 'Eenmalig'
|
||||
if (weekdayValues.length === 7) return 'Dagelijks'
|
||||
const labels = weekdayValues
|
||||
.slice()
|
||||
.sort((a, b) => a - b)
|
||||
.map(w => WEEKDAYS[WEEKDAY_VALUES.indexOf(w)])
|
||||
return labels.join(', ')
|
||||
}
|
||||
|
||||
const formatTime = (timeString) => {
|
||||
const date = new Date(timeString)
|
||||
return date.toLocaleTimeString('nl-NL', { hour: '2-digit', minute: '2-digit' })
|
||||
}
|
||||
|
||||
// Fetch route stops for a given line and cache them in state
|
||||
const loadRouteStops = async (busLineId) => {
|
||||
if (!busLineId) return
|
||||
try {
|
||||
const res = await client.get(`/admin/bus-lines/${busLineId}/stops`)
|
||||
const routeStops = res.data.routeStops || []
|
||||
setRouteStopsByLine(prev => ({ ...prev, [busLineId]: routeStops }))
|
||||
} catch (err) {
|
||||
// ignore silently, message already used elsewhere
|
||||
}
|
||||
}
|
||||
|
||||
const getCandidateWindow = () => {
|
||||
const line = busLines.find(l => String(l.id) === String(selectedLine))
|
||||
if (!line || !selectedDate || !startTime) return null
|
||||
|
||||
const start = new Date(`${selectedDate}T${startTime}:00`)
|
||||
const end = new Date(start)
|
||||
end.setMinutes(end.getMinutes() + (line.estimatedDurationMinutes || 60))
|
||||
return { start, end }
|
||||
}
|
||||
|
||||
const hasOverlap = (candidate, existing) => {
|
||||
if (!candidate || !existing?.startTime || !existing?.endTime) return false
|
||||
|
||||
const cStart = candidate.start.getTime()
|
||||
const cEnd = candidate.end.getTime()
|
||||
const eStart = new Date(existing.startTime).getTime()
|
||||
const eEnd = new Date(existing.endTime).getTime()
|
||||
const timeOverlap = cStart < eEnd && cEnd > eStart
|
||||
if (!timeOverlap) return false
|
||||
|
||||
const cWeekdays = selectedWeekdays || []
|
||||
const eWeekdays = Array.isArray(existing.weekdays) ? existing.weekdays : []
|
||||
|
||||
if (cWeekdays.length === 0 && eWeekdays.length === 0) {
|
||||
return candidate.start.toDateString() === new Date(existing.startTime).toDateString()
|
||||
}
|
||||
|
||||
if (cWeekdays.length > 0 && eWeekdays.length > 0) {
|
||||
return cWeekdays.some(d => eWeekdays.includes(d))
|
||||
}
|
||||
|
||||
if (cWeekdays.length > 0 && eWeekdays.length === 0) {
|
||||
return cWeekdays.includes(new Date(existing.startTime).getDay())
|
||||
}
|
||||
|
||||
return eWeekdays.includes(candidate.start.getDay())
|
||||
}
|
||||
|
||||
const candidateWindow = getCandidateWindow()
|
||||
const busyDriverIds = new Set(
|
||||
schedules
|
||||
.filter(s => s.driverId && hasOverlap(candidateWindow, s))
|
||||
.map(s => Number(s.driverId))
|
||||
)
|
||||
const busyBusIds = new Set(
|
||||
schedules
|
||||
.filter(s => s.busId && hasOverlap(candidateWindow, s))
|
||||
.map(s => Number(s.busId))
|
||||
)
|
||||
|
||||
const scheduleHasDriverConflict = (schedule) => {
|
||||
if (!schedule?.driverId) return false
|
||||
return schedules.some(other =>
|
||||
other.id !== schedule.id &&
|
||||
Number(other.driverId) === Number(schedule.driverId) &&
|
||||
hasOverlap({ start: new Date(schedule.startTime), end: new Date(schedule.endTime) }, other)
|
||||
)
|
||||
}
|
||||
|
||||
const scheduleHasBusConflict = (schedule) => {
|
||||
if (!schedule?.busId) return false
|
||||
return schedules.some(other =>
|
||||
other.id !== schedule.id &&
|
||||
Number(other.busId) === Number(schedule.busId) &&
|
||||
hasOverlap({ start: new Date(schedule.startTime), end: new Date(schedule.endTime) }, other)
|
||||
)
|
||||
}
|
||||
|
||||
// Group schedules by date and time using the API-backed overview
|
||||
const timeSlots = generateTimeSlots()
|
||||
const schedulesBySlot = groupSchedulesByTimeSlot(overviewSchedules, timeSlots)
|
||||
|
||||
return (
|
||||
<section className="card">
|
||||
<div className="section-header">
|
||||
<div>
|
||||
<h2>Diensten Inplannen</h2>
|
||||
<p>Maak diensten aan met automatische eindtijd, vertrektijden per halte en herhaald rooster.</p>
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center' }}>
|
||||
<button className="secondary" onClick={loadSchedules}>Refresh</button>
|
||||
<select
|
||||
value={selectedDriverFilter}
|
||||
onChange={e => setSelectedDriverFilter(e.target.value)}
|
||||
style={{ padding: '6px', borderRadius: '6px', border: '1px solid #ccc' }}
|
||||
>
|
||||
<option value="">Alle chauffeurs</option>
|
||||
{drivers.map(d => (
|
||||
<option key={d.id} value={d.id}>{d.name}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
{/* Timetable widget - compact daily view */}
|
||||
<TimetableDisplay
|
||||
client={client}
|
||||
overviewDate={overviewDate}
|
||||
setOverviewDate={setOverviewDate}
|
||||
selectedDriverFilter={selectedDriverFilter}
|
||||
setSelectedDriverFilter={setSelectedDriverFilter}
|
||||
drivers={drivers}
|
||||
/>
|
||||
|
||||
{/* Fixed service editor - separate widget */}
|
||||
{isAdmin && (
|
||||
<form onSubmit={createSchedule} className="stack-form">
|
||||
<div className="form-row">
|
||||
<select value={selectedLine} onChange={e => setSelectedLine(e.target.value)}>
|
||||
<option value="">Kies lijn</option>
|
||||
{busLines.map(line => (
|
||||
<option key={line.id} value={line.id}>
|
||||
Lijn {line.lineNumber} ({line.startStop} → {line.endStop})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<select value={selectedBus} onChange={e => setSelectedBus(e.target.value)}>
|
||||
<option value="">Kies voertuig</option>
|
||||
{buses.map(bus => (
|
||||
<option key={bus.id} value={bus.id} disabled={busyBusIds.has(Number(bus.id))}>
|
||||
{bus.name} ({bus.licensePlate}) {busyBusIds.has(Number(bus.id)) ? '- in gebruik' : ''}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="form-row">
|
||||
<select value={driverId} onChange={e => setDriverId(e.target.value)}>
|
||||
<option value="">Bestuurder (optioneel)</option>
|
||||
{drivers.map(driver => (
|
||||
<option key={driver.id} value={driver.id} disabled={busyDriverIds.has(Number(driver.id))}>
|
||||
{driver.name} {busyDriverIds.has(Number(driver.id)) ? '- in gebruik' : ''}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<input
|
||||
type="date"
|
||||
value={selectedDate}
|
||||
onChange={e => setSelectedDate(e.target.value)}
|
||||
/>
|
||||
<input
|
||||
type="time"
|
||||
value={startTime}
|
||||
onChange={e => setStartTime(e.target.value)}
|
||||
placeholder="Start time"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div style={{ marginBottom: '1rem' }}>
|
||||
<label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: 500 }}>
|
||||
Herhaal op weekdagen (optioneel):
|
||||
</label>
|
||||
<div style={{ display: 'flex', gap: '0.5rem', flexWrap: 'wrap' }}>
|
||||
{WEEKDAYS.map((day, idx) => (
|
||||
<button
|
||||
key={day}
|
||||
type="button"
|
||||
onClick={() => toggleWeekday(WEEKDAY_VALUES[idx])}
|
||||
style={{
|
||||
padding: '0.5rem 1rem',
|
||||
backgroundColor: selectedWeekdays.includes(WEEKDAY_VALUES[idx]) ? '#1D4ED8' : '#e0e0e0',
|
||||
color: selectedWeekdays.includes(WEEKDAY_VALUES[idx]) ? '#fff' : '#000',
|
||||
border: 'none',
|
||||
borderRadius: '4px',
|
||||
cursor: 'pointer',
|
||||
fontSize: '0.9rem',
|
||||
}}
|
||||
>
|
||||
{day}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="form-row">
|
||||
<button type="submit">Dienst Aanmaken</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
|
||||
<h3 style={{ marginTop: '2rem' }}>Timetable</h3>
|
||||
<div className="form-row" style={{ marginBottom: '1rem' }}>
|
||||
<input
|
||||
type="date"
|
||||
value={overviewDate}
|
||||
onChange={e => setOverviewDate(e.target.value)}
|
||||
<FixedScheduleEditor
|
||||
client={client}
|
||||
token={token}
|
||||
user={user}
|
||||
scheduleTemplates={scheduleTemplates}
|
||||
busLines={busLines}
|
||||
buses={buses}
|
||||
drivers={drivers}
|
||||
message={message}
|
||||
setMessage={setMessage}
|
||||
onScheduleChange={handleScheduleChange}
|
||||
/>
|
||||
<button type="button" onClick={() => setOverviewDate(new Date().toISOString().split('T')[0])}>
|
||||
Vandaag
|
||||
</button>
|
||||
</div>
|
||||
<div className="timetable-container">
|
||||
<table className="timetable">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Tijdvak</th>
|
||||
<th>Lijnen en Voertuigen</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{timeSlots.map((slot, idx) => (
|
||||
<tr key={idx}>
|
||||
<td className="time-cell">{slot}</td>
|
||||
<td className="schedule-cell">
|
||||
<div className="schedule-items">
|
||||
{schedulesBySlot[slot]?.map(schedule => (
|
||||
<article
|
||||
key={schedule.id}
|
||||
className="schedule-card"
|
||||
style={{ position: 'relative' }}
|
||||
>
|
||||
<div className="schedule-header">
|
||||
<strong>Lijn {schedule.lineNumber}</strong>
|
||||
<span className="schedule-time">
|
||||
{formatTime(schedule.startTime)} - {formatTime(schedule.endTime)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="schedule-details">
|
||||
<div>{schedule.busName}</div>
|
||||
<div className="schedule-plate">{schedule.licensePlate}</div>
|
||||
{schedule.driverName && (
|
||||
<div style={{ fontSize: '0.85rem', color: '#666', marginTop: '0.25rem' }}>
|
||||
{schedule.driverName}
|
||||
</div>
|
||||
)}
|
||||
{scheduleHasDriverConflict(schedule) && (
|
||||
<div style={{ fontSize: '0.75rem', color: '#b45309', marginTop: '0.25rem', fontWeight: 600 }}>
|
||||
Chauffeur in gebruik
|
||||
</div>
|
||||
)}
|
||||
{scheduleHasBusConflict(schedule) && (
|
||||
<div style={{ fontSize: '0.75rem', color: '#b45309', marginTop: '0.25rem', fontWeight: 600 }}>
|
||||
Voertuig in gebruik
|
||||
</div>
|
||||
)}
|
||||
<div style={{ fontSize: '0.85rem', color: '#666', marginTop: '0.25rem' }}>
|
||||
{schedule.recurrenceLabel || getWeekdayLabel(schedule.weekdays)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Expandable stops list */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setExpandedSchedule(expandedSchedule === schedule.id ? null : schedule.id)}
|
||||
style={{
|
||||
marginTop: '0.5rem',
|
||||
width: '100%',
|
||||
padding: '0.4rem',
|
||||
fontSize: '0.85rem',
|
||||
backgroundColor: '#f0f0f0',
|
||||
border: '1px solid #ddd',
|
||||
borderRadius: '3px',
|
||||
cursor: 'pointer',
|
||||
}}
|
||||
>
|
||||
{expandedSchedule === schedule.id ? '▼' : '▶'} Haltes ({schedule.departureTimes?.length || 0})
|
||||
</button>
|
||||
|
||||
{expandedSchedule === schedule.id && (
|
||||
<div style={{ marginTop: '0.5rem', paddingTop: '0.5rem', borderTop: '1px solid #eee' }}>
|
||||
{(() => {
|
||||
const lineId = schedule.busLineId
|
||||
const cached = routeStopsByLine[lineId]
|
||||
if (!cached) {
|
||||
// Load and show loading text
|
||||
loadRouteStops(lineId)
|
||||
return <p style={{ fontSize: '0.85rem', color: '#999' }}>Laden haltes...</p>
|
||||
}
|
||||
|
||||
if (cached.length === 0) {
|
||||
return <p style={{ fontSize: '0.85rem', color: '#999' }}>Geen haltes gekoppeld</p>
|
||||
}
|
||||
|
||||
// Render editable list of stops with ETA inputs
|
||||
return (
|
||||
<table style={{ width: '100%', fontSize: '0.8rem' }}>
|
||||
<tbody>
|
||||
{cached.map(rs => {
|
||||
const departureDate = new Date(schedule.startTime)
|
||||
departureDate.setMinutes(departureDate.getMinutes() + (rs.estimatedArrivalMinutes || 0))
|
||||
return (
|
||||
<tr key={rs.id}>
|
||||
<td style={{ paddingRight: '0.5rem' }}><strong>{rs.stopOrder}.</strong></td>
|
||||
<td style={{ flex: 1 }}>{rs.name}</td>
|
||||
<td style={{ textAlign: 'right', color: '#666' }}>{formatTime(departureDate.toISOString())}</td>
|
||||
<td style={{ paddingLeft: '0.5rem' }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
|
||||
<input
|
||||
type="range"
|
||||
min="0"
|
||||
max="240"
|
||||
value={Number(rs.estimatedArrivalMinutes ?? 0)}
|
||||
onChange={e => {
|
||||
const val = Number(e.target.value)
|
||||
setRouteStopsByLine(prev => ({
|
||||
...prev,
|
||||
[lineId]: prev[lineId].map(item => item.id === rs.id ? { ...item, estimatedArrivalMinutes: val } : item)
|
||||
}))
|
||||
}}
|
||||
style={{ width: '8rem' }}
|
||||
/>
|
||||
<input
|
||||
type="number"
|
||||
value={Number(rs.estimatedArrivalMinutes ?? 0)}
|
||||
onChange={e => {
|
||||
const val = e.target.value === '' ? 0 : Number(e.target.value)
|
||||
setRouteStopsByLine(prev => ({
|
||||
...prev,
|
||||
[lineId]: prev[lineId].map(item => item.id === rs.id ? { ...item, estimatedArrivalMinutes: val } : item)
|
||||
}))
|
||||
}}
|
||||
style={{ width: '4.5rem' }}
|
||||
/>
|
||||
</div>
|
||||
<button type="button" onClick={async () => {
|
||||
const newVal = Number((routeStopsByLine[lineId].find(i => i.id === rs.id)?.estimatedArrivalMinutes) || 0)
|
||||
try {
|
||||
await client.post(`/admin/bus-lines/${lineId}/stops`, {
|
||||
stopId: rs.stopId,
|
||||
stopOrder: rs.stopOrder,
|
||||
estimatedArrivalMinutes: newVal,
|
||||
})
|
||||
setMessage('ETA updated')
|
||||
await loadRouteStops(lineId)
|
||||
await loadSchedules()
|
||||
await loadOverviewSchedules()
|
||||
} catch (err) {
|
||||
setMessage('Error: ' + (err.response?.data?.error || err.message))
|
||||
}
|
||||
}} style={{ marginLeft: '0.5rem' }}>Save</button>
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
)
|
||||
})()}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isAdmin && (
|
||||
<button
|
||||
className="danger"
|
||||
style={{ marginTop: '0.5rem', width: '100%', fontSize: '0.85rem', padding: '0.4rem' }}
|
||||
onClick={() => setDeleteConfirm(schedule)}
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
)}
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{message && <div className="message">{message}</div>}
|
||||
|
||||
{deleteConfirm && (
|
||||
<div style={overlay}>
|
||||
<div style={modal}>
|
||||
<h3>Delete Service?</h3>
|
||||
<p>
|
||||
<strong>Lijn {deleteConfirm.lineNumber}</strong> - {deleteConfirm.busName} ({deleteConfirm.licensePlate})
|
||||
</p>
|
||||
<p style={{ color: '#999', fontSize: '0.9rem' }}>
|
||||
{new Date(deleteConfirm.startTime).toLocaleString()}
|
||||
</p>
|
||||
<div className="form-row" style={{ marginTop: '1rem' }}>
|
||||
<button className="secondary" onClick={() => setDeleteConfirm(null)}>Cancel</button>
|
||||
<button
|
||||
className="danger"
|
||||
onClick={() =>
|
||||
deleteSchedule(deleteConfirm.id, deleteConfirm.lineNumber, deleteConfirm.busName)
|
||||
}
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function generateTimeSlots() {
|
||||
const slots = []
|
||||
for (let hour = 0; hour < 24; hour++) {
|
||||
slots.push(`${String(hour).padStart(2, '0')}:00-${String((hour + 1) % 24).padStart(2, '0')}:00`)
|
||||
}
|
||||
return slots
|
||||
}
|
||||
|
||||
function groupSchedulesByTimeSlot(schedules, slots) {
|
||||
const grouped = {}
|
||||
slots.forEach(slot => {
|
||||
grouped[slot] = []
|
||||
})
|
||||
|
||||
schedules.forEach(schedule => {
|
||||
const startHour = new Date(schedule.startTime).getHours()
|
||||
const slot = `${String(startHour).padStart(2, '0')}:00-${String((startHour + 1) % 24).padStart(2, '0')}:00`
|
||||
if (grouped[slot]) {
|
||||
grouped[slot].push(schedule)
|
||||
}
|
||||
})
|
||||
|
||||
return grouped
|
||||
}
|
||||
|
||||
function formatTime(timeString) {
|
||||
const date = new Date(timeString)
|
||||
return date.toLocaleTimeString('nl-NL', { hour: '2-digit', minute: '2-digit' })
|
||||
}
|
||||
|
||||
const overlay = {
|
||||
position: 'fixed',
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
backgroundColor: 'rgba(0,0,0,0.5)',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
zIndex: 1000,
|
||||
}
|
||||
|
||||
const modal = {
|
||||
backgroundColor: '#fff',
|
||||
padding: '2rem',
|
||||
borderRadius: '8px',
|
||||
maxWidth: '400px',
|
||||
boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ export default function StopsManager({ token, user }) {
|
||||
const [lat, setLat] = useState('')
|
||||
const [lon, setLon] = useState('')
|
||||
const [message, setMessage] = useState(null)
|
||||
const [isAdmin] = useState(Boolean(user?.userCode))
|
||||
const [isAdmin] = useState(Boolean(user?.isAdmin))
|
||||
const [deleteConfirm, setDeleteConfirm] = useState(null)
|
||||
const [editingStop, setEditingStop] = useState(null)
|
||||
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
import React, { useState, useEffect } from 'react'
|
||||
|
||||
const TimetableDisplay = ({ client, overviewDate, setOverviewDate, selectedDriverFilter, setSelectedDriverFilter, drivers }) => {
|
||||
const [overviewSchedules, setOverviewSchedules] = useState([])
|
||||
const [message, setMessage] = useState(null)
|
||||
const [expandedSchedule, setExpandedSchedule] = useState(null)
|
||||
const [routeStopsByLine, setRouteStopsByLine] = useState({})
|
||||
|
||||
const loadOverviewSchedules = async () => {
|
||||
try {
|
||||
const params = new URLSearchParams({ date: overviewDate })
|
||||
if (selectedDriverFilter) {
|
||||
params.set('driverId', selectedDriverFilter)
|
||||
}
|
||||
|
||||
const res = await client.get(`/schedules/overview?${params.toString()}`)
|
||||
setOverviewSchedules(res.data.schedules || [])
|
||||
} catch (err) {
|
||||
setMessage('Error loading timetable: ' + (err.response?.data?.error || err.message))
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
loadOverviewSchedules()
|
||||
}, [overviewDate, selectedDriverFilter])
|
||||
|
||||
const formatTime = (timeString) => {
|
||||
const date = new Date(timeString)
|
||||
return date.toLocaleTimeString('nl-NL', { hour: '2-digit', minute: '2-digit' })
|
||||
}
|
||||
|
||||
const loadRouteStops = async (busLineId) => {
|
||||
if (!busLineId) return
|
||||
try {
|
||||
const res = await client.get(`/admin/bus-lines/${busLineId}/stops`)
|
||||
const routeStops = res.data.routeStops || []
|
||||
setRouteStopsByLine(prev => ({ ...prev, [busLineId]: routeStops }))
|
||||
} catch (err) {
|
||||
// ignore silently
|
||||
}
|
||||
}
|
||||
|
||||
const getWeekdayLabel = (weekdayValues) => {
|
||||
const WEEKDAYS = ['Ma', 'Di', 'Wo', 'Do', 'Vr', 'Za', 'Zo']
|
||||
const WEEKDAY_VALUES = [1, 2, 3, 4, 5, 6, 0]
|
||||
if (!weekdayValues || weekdayValues.length === 0) return 'Eenmalig'
|
||||
if (weekdayValues.length === 7) return 'Dagelijks'
|
||||
const labels = weekdayValues
|
||||
.slice()
|
||||
.sort((a, b) => a - b)
|
||||
.map(w => WEEKDAYS[WEEKDAY_VALUES.indexOf(w)])
|
||||
return labels.join(', ')
|
||||
}
|
||||
|
||||
const timeSlots = (() => {
|
||||
const slots = []
|
||||
for (let hour = 0; hour < 24; hour++) {
|
||||
slots.push(`${String(hour).padStart(2, '0')}:00-${String((hour + 1) % 24).padStart(2, '0')}:00`)
|
||||
}
|
||||
return slots
|
||||
})()
|
||||
|
||||
const schedulesBySlot = (() => {
|
||||
const grouped = {}
|
||||
timeSlots.forEach(slot => {
|
||||
grouped[slot] = []
|
||||
})
|
||||
|
||||
overviewSchedules.forEach(schedule => {
|
||||
const startHour = new Date(schedule.startTime).getHours()
|
||||
const slot = `${String(startHour).padStart(2, '0')}:00-${String((startHour + 1) % 24).padStart(2, '0')}:00`
|
||||
if (grouped[slot]) {
|
||||
grouped[slot].push(schedule)
|
||||
}
|
||||
})
|
||||
|
||||
return grouped
|
||||
})()
|
||||
|
||||
return (
|
||||
<section className="card" style={{ marginTop: '2rem' }}>
|
||||
<div className="section-header">
|
||||
<div>
|
||||
<h3>Dagelijks Overzicht</h3>
|
||||
<p>Alle geplande diensten voor de geselecteerde dag</p>
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center' }}>
|
||||
<input
|
||||
type="date"
|
||||
value={overviewDate}
|
||||
onChange={e => setOverviewDate(e.target.value)}
|
||||
/>
|
||||
<button type="button" onClick={() => setOverviewDate(new Date().toISOString().split('T')[0])}>
|
||||
Vandaag
|
||||
</button>
|
||||
<select
|
||||
value={selectedDriverFilter}
|
||||
onChange={e => setSelectedDriverFilter(e.target.value)}
|
||||
style={{ padding: '6px', borderRadius: '6px', border: '1px solid #ccc' }}
|
||||
>
|
||||
<option value="">Alle chauffeurs</option>
|
||||
{drivers.map(d => (
|
||||
<option key={d.id} value={d.id}>{d.name}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="timetable-container">
|
||||
<table className="timetable">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Tijdvak</th>
|
||||
<th>Lijnen en Voertuigen</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{timeSlots.map((slot, idx) => (
|
||||
<tr key={idx}>
|
||||
<td className="time-cell">{slot}</td>
|
||||
<td className="schedule-cell">
|
||||
<div className="schedule-items">
|
||||
{schedulesBySlot[slot]?.map(schedule => (
|
||||
<article
|
||||
key={schedule.id}
|
||||
className="schedule-card"
|
||||
style={{ position: 'relative' }}
|
||||
>
|
||||
<div className="schedule-header">
|
||||
<strong>Lijn {schedule.lineNumber}</strong>
|
||||
<span className="schedule-time">
|
||||
{formatTime(schedule.startTime)} - {formatTime(schedule.endTime)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="schedule-details">
|
||||
<div>{schedule.busName}</div>
|
||||
<div className="schedule-plate">{schedule.licensePlate}</div>
|
||||
{schedule.driverName && (
|
||||
<div style={{ fontSize: '0.85rem', color: '#666', marginTop: '0.25rem' }}>
|
||||
{schedule.driverName}
|
||||
</div>
|
||||
)}
|
||||
<div style={{ fontSize: '0.85rem', color: '#666', marginTop: '0.25rem' }}>
|
||||
{schedule.recurrenceLabel || getWeekdayLabel(schedule.weekdays)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Expandable stops list */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setExpandedSchedule(expandedSchedule === schedule.id ? null : schedule.id)}
|
||||
style={{
|
||||
marginTop: '0.5rem',
|
||||
width: '100%',
|
||||
padding: '0.4rem',
|
||||
fontSize: '0.85rem',
|
||||
backgroundColor: '#f0f0f0',
|
||||
border: '1px solid #ddd',
|
||||
borderRadius: '3px',
|
||||
cursor: 'pointer',
|
||||
}}
|
||||
>
|
||||
{expandedSchedule === schedule.id ? '▼' : '▶'} Haltes ({schedule.departureTimes?.length || 0})
|
||||
</button>
|
||||
|
||||
{expandedSchedule === schedule.id && (
|
||||
<div style={{ marginTop: '0.5rem', paddingTop: '0.5rem', borderTop: '1px solid #eee' }}>
|
||||
{(() => {
|
||||
const lineId = schedule.busLineId
|
||||
const cached = routeStopsByLine[lineId]
|
||||
if (!cached) {
|
||||
loadRouteStops(lineId)
|
||||
return <p style={{ fontSize: '0.85rem', color: '#999' }}>Laden haltes...</p>
|
||||
}
|
||||
|
||||
if (cached.length === 0) {
|
||||
return <p style={{ fontSize: '0.85rem', color: '#999' }}>Geen haltes gekoppeld</p>
|
||||
}
|
||||
|
||||
return (
|
||||
<table style={{ width: '100%', fontSize: '0.8rem' }}>
|
||||
<tbody>
|
||||
{cached.map(rs => {
|
||||
const departureDate = new Date(schedule.startTime)
|
||||
departureDate.setMinutes(departureDate.getMinutes() + (rs.estimatedArrivalMinutes || 0))
|
||||
return (
|
||||
<tr key={rs.id}>
|
||||
<td style={{ paddingRight: '0.5rem' }}><strong>{rs.stopOrder}.</strong></td>
|
||||
<td style={{ flex: 1 }}>{rs.name}</td>
|
||||
<td style={{ textAlign: 'right', color: '#666' }}>{formatTime(departureDate.toISOString())}</td>
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
)
|
||||
})()}
|
||||
</div>
|
||||
)}
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{message && <div className="message">{message}</div>}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
export default TimetableDisplay
|
||||
@@ -2,6 +2,7 @@ import React, { useEffect, useState } from 'react'
|
||||
|
||||
export default function TimetableViewer({ apiBaseUrl = 'http://localhost:5001' }) {
|
||||
const [schedules, setSchedules] = useState([])
|
||||
const [summary, setSummary] = useState(null)
|
||||
const [selectedDate, setSelectedDate] = useState(new Date().toISOString().split('T')[0])
|
||||
const [selectedLineId, setSelectedLineId] = useState('')
|
||||
const [lines, setLines] = useState([])
|
||||
@@ -28,13 +29,14 @@ export default function TimetableViewer({ apiBaseUrl = 'http://localhost:5001' }
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
try {
|
||||
let url = `${apiBaseUrl}/schedules?date=${selectedDate}`
|
||||
let url = `${apiBaseUrl}/schedules/overview?date=${selectedDate}`
|
||||
if (selectedLineId) {
|
||||
url += `&lineId=${selectedLineId}`
|
||||
}
|
||||
const res = await fetch(url)
|
||||
const data = await res.json()
|
||||
setSchedules(data.schedules || [])
|
||||
setSummary(data.summary || null)
|
||||
} catch (err) {
|
||||
setError('Failed to load schedules: ' + err.message)
|
||||
} finally {
|
||||
@@ -72,6 +74,20 @@ export default function TimetableViewer({ apiBaseUrl = 'http://localhost:5001' }
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{summary && (
|
||||
<div style={{ marginBottom: '16px', display: 'flex', gap: '12px', flexWrap: 'wrap' }}>
|
||||
<span style={{ padding: '6px 10px', borderRadius: '999px', backgroundColor: '#eef2ff', color: '#3730a3' }}>
|
||||
Total: {summary.total}
|
||||
</span>
|
||||
<span style={{ padding: '6px 10px', borderRadius: '999px', backgroundColor: '#ecfeff', color: '#155e75' }}>
|
||||
Vast: {summary.recurring}
|
||||
</span>
|
||||
<span style={{ padding: '6px 10px', borderRadius: '999px', backgroundColor: '#f8fafc', color: '#334155' }}>
|
||||
Eenmalig: {summary.oneTime}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{loading && <p>Loading schedules...</p>}
|
||||
{error && <p style={{ color: 'red' }}>{error}</p>}
|
||||
|
||||
@@ -81,7 +97,8 @@ export default function TimetableViewer({ apiBaseUrl = 'http://localhost:5001' }
|
||||
<th style={{ padding: '12px', textAlign: 'left', borderBottom: '2px solid #ddd' }}>Time</th>
|
||||
<th style={{ padding: '12px', textAlign: 'left', borderBottom: '2px solid #ddd' }}>Line</th>
|
||||
<th style={{ padding: '12px', textAlign: 'left', borderBottom: '2px solid #ddd' }}>Vehicle</th>
|
||||
<th style={{ padding: '12px', textAlign: 'left', borderBottom: '2px solid #ddd' }}>Status</th>
|
||||
<th style={{ padding: '12px', textAlign: 'left', borderBottom: '2px solid #ddd' }}>Day status</th>
|
||||
<th style={{ padding: '12px', textAlign: 'left', borderBottom: '2px solid #ddd' }}>Delay</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -104,14 +121,19 @@ export default function TimetableViewer({ apiBaseUrl = 'http://localhost:5001' }
|
||||
style={{
|
||||
padding: '4px 8px',
|
||||
borderRadius: '4px',
|
||||
backgroundColor: schedule.status === 'active' ? '#dcfce7' : '#f3f4f6',
|
||||
color: schedule.status === 'active' ? '#166534' : '#374151',
|
||||
backgroundColor: schedule.status === 'in_progress' ? '#dbeafe' : schedule.status === 'completed' ? '#dcfce7' : '#f3f4f6',
|
||||
color: schedule.status === 'in_progress' ? '#1d4ed8' : schedule.status === 'completed' ? '#166534' : '#374151',
|
||||
fontSize: '0.9rem',
|
||||
}}
|
||||
>
|
||||
{schedule.status}
|
||||
</span>
|
||||
</td>
|
||||
<td style={{ padding: '12px' }}>
|
||||
{typeof schedule.currentDelayMinutes === 'number' && schedule.currentDelayMinutes !== null
|
||||
? `${schedule.currentDelayMinutes > 0 ? '+' : ''}${schedule.currentDelayMinutes} min`
|
||||
: '—'}
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
})}
|
||||
|
||||
@@ -18,7 +18,51 @@ app.use((req, res, next) => {
|
||||
next();
|
||||
});
|
||||
|
||||
const ERROR_LOG_API_URL = process.env.ERROR_LOG_API_URL || 'http://localhost:5003/error_log';
|
||||
|
||||
function friendlyErrorMessage(statusCode) {
|
||||
if (statusCode === 400) return 'Controleer je invoer en probeer opnieuw.';
|
||||
if (statusCode === 401) return 'Je sessie is verlopen. Log opnieuw in.';
|
||||
if (statusCode === 403) return 'Je hebt hier geen toegang toe.';
|
||||
if (statusCode === 404) return 'Niet gevonden.';
|
||||
return 'Er ging iets mis. Probeer het later opnieuw.';
|
||||
}
|
||||
|
||||
async function reportError({ partOfService, error }) {
|
||||
try {
|
||||
await fetch(ERROR_LOG_API_URL, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
service: 'auth_api',
|
||||
partOfService,
|
||||
error,
|
||||
}),
|
||||
});
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
app.use((req, res, next) => {
|
||||
const originalJson = res.json.bind(res);
|
||||
res.json = (body) => {
|
||||
if (res.statusCode >= 400 && body && typeof body === 'object') {
|
||||
const rawError = body.error || body.message || body.details || `HTTP ${res.statusCode}`;
|
||||
void reportError({ partOfService: `${req.method} ${req.originalUrl}`, error: rawError });
|
||||
return originalJson({ error: friendlyErrorMessage(res.statusCode) });
|
||||
}
|
||||
return originalJson(body);
|
||||
};
|
||||
|
||||
next();
|
||||
});
|
||||
|
||||
const JWT_SECRET = process.env.JWT_SECRET;
|
||||
const ADMIN_USER_CODES = new Set(
|
||||
String(process.env.ADMIN_USER_CODES || '')
|
||||
.split(',')
|
||||
.map(c => Number(c.trim()))
|
||||
.filter(Number.isFinite)
|
||||
);
|
||||
|
||||
|
||||
app.post('/login', async (req, res) => {
|
||||
@@ -33,13 +77,15 @@ app.post('/login', async (req, res) => {
|
||||
const ok = await bcrypt.compare(password, user.password);
|
||||
if (!ok) return res.status(401).json({ error: 'invalid_credentials' });
|
||||
|
||||
const payload = { userId: user.id, userCode: user.usercode };
|
||||
const isAdmin = ADMIN_USER_CODES.has(Number(user.usercode));
|
||||
const payload = { userId: user.id, userCode: user.usercode, isAdmin };
|
||||
const token = jwt.sign(payload, JWT_SECRET, { expiresIn: '1h' });
|
||||
|
||||
res.json({ token, user: { id: user.id, userCode: user.userCode, job: user.job } });
|
||||
res.json({ token, user: { id: user.id, userCode: user.usercode, job: user.job, isAdmin } });
|
||||
} catch (err) {
|
||||
await reportError({ partOfService: `${req.method} ${req.originalUrl}`, error: err?.stack || err?.message || String(err) });
|
||||
console.error(err);
|
||||
res.status(500).json({ error: 'internal_error' });
|
||||
res.status(500).json({ error: friendlyErrorMessage(500) });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -51,7 +97,8 @@ app.get('/me', async (req, res) => {
|
||||
const payload = jwt.verify(token, JWT_SECRET);
|
||||
res.json({ user: payload });
|
||||
} catch (err) {
|
||||
res.status(401).json({ error: 'invalid_token' });
|
||||
void reportError({ partOfService: `${req.method} ${req.originalUrl}`, error: err?.stack || err?.message || String(err) });
|
||||
res.status(401).json({ error: friendlyErrorMessage(401) });
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
# Miscellaneous
|
||||
*.class
|
||||
*.log
|
||||
*.pyc
|
||||
*.swp
|
||||
.DS_Store
|
||||
.atom/
|
||||
.build/
|
||||
.buildlog/
|
||||
.history
|
||||
.svn/
|
||||
.swiftpm/
|
||||
migrate_working_dir/
|
||||
|
||||
# IntelliJ related
|
||||
*.iml
|
||||
*.ipr
|
||||
*.iws
|
||||
.idea/
|
||||
|
||||
# The .vscode folder contains launch configuration and tasks you configure in
|
||||
# VS Code which you may wish to be included in version control, so this line
|
||||
# is commented out by default.
|
||||
#.vscode/
|
||||
|
||||
# Flutter/Dart/Pub related
|
||||
**/doc/api/
|
||||
**/ios/Flutter/.last_build_id
|
||||
.dart_tool/
|
||||
.flutter-plugins-dependencies
|
||||
.pub-cache/
|
||||
.pub/
|
||||
/build/
|
||||
/coverage/
|
||||
|
||||
# Symbolication related
|
||||
app.*.symbols
|
||||
|
||||
# Obfuscation related
|
||||
app.*.map.json
|
||||
|
||||
# Android Studio will place build artifacts here
|
||||
/android/app/debug
|
||||
/android/app/profile
|
||||
/android/app/release
|
||||
|
||||
#github
|
||||
.github/
|
||||
@@ -1,3 +0,0 @@
|
||||
# bus_terminal
|
||||
|
||||
A new Flutter project.
|
||||
@@ -1,526 +0,0 @@
|
||||
// ignore_for_file: use_build_context_synchronously
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import '../models/schedule.dart' as sched;
|
||||
import '../models/navigation.dart';
|
||||
import '../services/auth_service.dart';
|
||||
import '../services/schedule_service.dart';
|
||||
import '../screens/navigation_screen.dart';
|
||||
|
||||
class ScheduleOverviewScreen extends StatefulWidget {
|
||||
const ScheduleOverviewScreen({super.key});
|
||||
|
||||
@override
|
||||
State<ScheduleOverviewScreen> createState() => _ScheduleOverviewScreenState();
|
||||
}
|
||||
|
||||
class _ScheduleOverviewScreenState extends State<ScheduleOverviewScreen> {
|
||||
final _scheduleService = ScheduleService();
|
||||
final _authService = AuthService();
|
||||
|
||||
late Future<List<sched.ServiceSchedule>> _scheduleFuture;
|
||||
DateTime _selectedDate = DateTime.now();
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_scheduleFuture = _scheduleService.getSchedules(_selectedDate);
|
||||
}
|
||||
|
||||
Future<void> _handleLogout() async {
|
||||
await _authService.logout();
|
||||
if (mounted) {
|
||||
Navigator.of(context).pushReplacementNamed('/login');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _refreshSchedules() async {
|
||||
setState(() {
|
||||
_scheduleFuture = _scheduleService.getSchedules(_selectedDate);
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _selectDate() async {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
final picked = await showDatePicker(
|
||||
context: context,
|
||||
initialDate: _selectedDate,
|
||||
firstDate: DateTime.now().subtract(const Duration(days: 7)),
|
||||
lastDate: DateTime.now().add(const Duration(days: 30)),
|
||||
builder: (context, child) {
|
||||
return Theme(
|
||||
data: Theme.of(context).copyWith(
|
||||
dialogBackgroundColor: colorScheme.surface,
|
||||
),
|
||||
child: child!,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
if (picked != null && picked != _selectedDate) {
|
||||
setState(() {
|
||||
_selectedDate = picked;
|
||||
});
|
||||
_refreshSchedules();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _showScheduleDetails(sched.ServiceSchedule svc) async {
|
||||
try {
|
||||
final stops = await _scheduleService.getScheduleStops(svc.id);
|
||||
if (!mounted) return;
|
||||
|
||||
await showModalBottomSheet<void>(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
showDragHandle: true,
|
||||
builder: (sheetContext) {
|
||||
return DraggableScrollableSheet(
|
||||
expand: false,
|
||||
initialChildSize: 0.75,
|
||||
minChildSize: 0.45,
|
||||
maxChildSize: 0.95,
|
||||
builder: (context, scrollController) {
|
||||
return ListView(
|
||||
controller: scrollController,
|
||||
padding: const EdgeInsets.fromLTRB(20, 8, 20, 24),
|
||||
children: [
|
||||
Text(
|
||||
'Lijn ${svc.lineNumber}',
|
||||
style: Theme.of(context).textTheme.headlineSmall?.copyWith(
|
||||
fontWeight: FontWeight.w800,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
svc.busName,
|
||||
style: Theme.of(context).textTheme.titleMedium,
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'${_formatTime(svc.startTime)} - ${_formatTime(svc.endTime)}',
|
||||
style: Theme.of(context).textTheme.bodyMedium,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
_InfoChip(label: svc.status),
|
||||
_InfoChip(label: svc.isRecurring ? _weekdayLabel(svc.weekdays) : 'Eenmalig'),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: FilledButton.icon(
|
||||
onPressed: () async {
|
||||
try {
|
||||
await _scheduleService.updateScheduleStatus(svc.id, 'in_progress');
|
||||
|
||||
if (!mounted) return;
|
||||
|
||||
// Close the sheet and start navigation with provided stops
|
||||
Navigator.of(sheetContext).pop();
|
||||
|
||||
final routeObj = sched.Route(
|
||||
id: svc.id,
|
||||
busLine: sched.BusLine(
|
||||
id: svc.busLineId,
|
||||
lineNumber: svc.lineNumber,
|
||||
startStop: '',
|
||||
endStop: '',
|
||||
estimatedDuration: 0,
|
||||
),
|
||||
busType: sched.BusType(
|
||||
id: svc.busId,
|
||||
name: svc.busName,
|
||||
seatCapacity: 0,
|
||||
licensePlate: '',
|
||||
),
|
||||
startTime: svc.startTime,
|
||||
endTime: svc.endTime,
|
||||
status: 'in_progress',
|
||||
);
|
||||
|
||||
final navStops = stops
|
||||
.map((s) => NavigationPoint(
|
||||
latitude: s.latitude,
|
||||
longitude: s.longitude,
|
||||
name: s.name,
|
||||
))
|
||||
.toList();
|
||||
|
||||
Navigator.of(context).push(
|
||||
MaterialPageRoute(
|
||||
builder: (_) => NavigationScreen(route: routeObj, initialStops: navStops),
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('Status bijwerken mislukt: $e')),
|
||||
);
|
||||
}
|
||||
},
|
||||
icon: const Icon(Icons.navigation),
|
||||
label: const Text('Start route'),
|
||||
),
|
||||
),
|
||||
Text(
|
||||
'Haltes',
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
if (stops.isEmpty)
|
||||
Text(
|
||||
'Geen haltes gekoppeld aan deze dienst.',
|
||||
style: Theme.of(context).textTheme.bodyMedium,
|
||||
)
|
||||
else
|
||||
...stops.map((stop) {
|
||||
final departureTime = svc.startTime.add(
|
||||
Duration(minutes: stop.estimatedArrivalMinutes),
|
||||
);
|
||||
return Card(
|
||||
child: ListTile(
|
||||
dense: true,
|
||||
title: Text('${stop.order}. ${stop.name}'),
|
||||
subtitle: Text('${stop.estimatedArrivalMinutes} min na vertrek'),
|
||||
trailing: Text(_formatTime(departureTime)),
|
||||
),
|
||||
);
|
||||
}),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('Kon dienstdetails niet laden: $e')),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
final dateStr =
|
||||
'${_selectedDate.year}-${_selectedDate.month.toString().padLeft(2, '0')}-${_selectedDate.day.toString().padLeft(2, '0')}';
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Today on the Road'),
|
||||
elevation: 0,
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.logout),
|
||||
tooltip: 'Logout',
|
||||
onPressed: _handleLogout,
|
||||
),
|
||||
],
|
||||
),
|
||||
body: Container(
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
colors: Theme.of(context).brightness == Brightness.dark
|
||||
? const [Color(0xFF0B1220), Color(0xFF111827)]
|
||||
: const [Color(0xFFF1F5F9), Color(0xFFE2E8F0)],
|
||||
begin: Alignment.topCenter,
|
||||
end: Alignment.bottomCenter,
|
||||
),
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
Container(
|
||||
margin: const EdgeInsets.fromLTRB(16, 16, 16, 12),
|
||||
padding: const EdgeInsets.all(18),
|
||||
decoration: BoxDecoration(
|
||||
gradient: const LinearGradient(
|
||||
colors: [Color(0xFF0F172A), Color(0xFF1D4ED8)],
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
),
|
||||
borderRadius: BorderRadius.circular(24),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withOpacity(0.16),
|
||||
blurRadius: 22,
|
||||
offset: const Offset(0, 10),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Geplande diensten',
|
||||
style: Theme.of(context).textTheme.labelSmall?.copyWith(
|
||||
color: Colors.white.withOpacity(0.78),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
dateStr,
|
||||
style: Theme.of(context).textTheme.headlineMedium?.copyWith(
|
||||
color: Colors.white,
|
||||
fontWeight: FontWeight.w800,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
'Automatisch berekende eindtijden, haltes en herhalende weekdagen',
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: Colors.white.withOpacity(0.84),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: SizedBox(
|
||||
height: 48,
|
||||
child: OutlinedButton.icon(
|
||||
onPressed: _selectDate,
|
||||
icon: const Icon(Icons.calendar_today, size: 18),
|
||||
label: const Text('Wijzig datum'),
|
||||
style: OutlinedButton.styleFrom(
|
||||
foregroundColor: Colors.white,
|
||||
side: BorderSide(color: Colors.white.withOpacity(0.28)),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: FutureBuilder<List<sched.ServiceSchedule>>(
|
||||
future: _scheduleFuture,
|
||||
builder: (context, snapshot) {
|
||||
if (snapshot.connectionState == ConnectionState.waiting) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
|
||||
if (snapshot.hasError) {
|
||||
return Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 24),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.error_outline,
|
||||
size: 64,
|
||||
color: colorScheme.error,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'Failed to load schedule',
|
||||
style: Theme.of(context).textTheme.titleMedium,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
snapshot.error.toString(),
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
FilledButton.icon(
|
||||
onPressed: _refreshSchedules,
|
||||
icon: const Icon(Icons.refresh),
|
||||
label: const Text('Retry'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
final schedules = snapshot.data ?? [];
|
||||
if (schedules.isEmpty) {
|
||||
return Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 24),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.calendar_today,
|
||||
size: 64,
|
||||
color: colorScheme.outline,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'No routes scheduled',
|
||||
style: Theme.of(context).textTheme.titleMedium,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'Check back later for your schedule',
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return RefreshIndicator(
|
||||
onRefresh: _refreshSchedules,
|
||||
child: ListView.builder(
|
||||
padding: const EdgeInsets.only(bottom: 16),
|
||||
itemCount: schedules.length,
|
||||
itemBuilder: (context, index) {
|
||||
final schedule = schedules[index];
|
||||
return _ScheduleSummaryCard(
|
||||
schedule: schedule,
|
||||
onTap: () => _showScheduleDetails(schedule),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ScheduleSummaryCard extends StatelessWidget {
|
||||
final sched.ServiceSchedule schedule;
|
||||
final VoidCallback onTap;
|
||||
|
||||
const _ScheduleSummaryCard({
|
||||
required this.schedule,
|
||||
required this.onTap,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
|
||||
return Card(
|
||||
margin: const EdgeInsets.fromLTRB(16, 8, 16, 8),
|
||||
elevation: 0,
|
||||
color: colorScheme.surface,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
|
||||
child: InkWell(
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
onTap: onTap,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
colors: [colorScheme.primary, colorScheme.tertiary],
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Text(
|
||||
'Line ${schedule.lineNumber}',
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
color: Colors.white,
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 18,
|
||||
),
|
||||
),
|
||||
),
|
||||
_InfoChip(label: schedule.status),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
schedule.busName,
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'${_formatTime(schedule.startTime)} - ${_formatTime(schedule.endTime)}',
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
schedule.isRecurring ? _weekdayLabel(schedule.weekdays) : 'Eenmalige dienst',
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: TextButton.icon(
|
||||
onPressed: onTap,
|
||||
icon: const Icon(Icons.list_alt, size: 18),
|
||||
label: const Text('Haltes'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _InfoChip extends StatelessWidget {
|
||||
final String label;
|
||||
|
||||
const _InfoChip({required this.label});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context).colorScheme.primaryContainer,
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
),
|
||||
child: Text(
|
||||
label,
|
||||
style: Theme.of(context).textTheme.labelMedium?.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _formatTime(DateTime time) {
|
||||
return '${time.hour.toString().padLeft(2, '0')}:${time.minute.toString().padLeft(2, '0')}';
|
||||
}
|
||||
|
||||
String _weekdayLabel(List<int> weekdays) {
|
||||
const labels = ['Zo', 'Ma', 'Di', 'Wo', 'Do', 'Vr', 'Za'];
|
||||
if (weekdays.isEmpty) {
|
||||
return 'Eenmalige dienst';
|
||||
}
|
||||
if (weekdays.length == 7) {
|
||||
return 'Dagelijks';
|
||||
}
|
||||
return weekdays.where((day) => day >= 0 && day < labels.length).map((day) => labels[day]).join(', ');
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
/// Custom exception for authentication errors
|
||||
class UnauthorizedException implements Exception {
|
||||
final String message;
|
||||
|
||||
UnauthorizedException(this.message);
|
||||
|
||||
@override
|
||||
String toString() => message;
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
{
|
||||
"name": "bus_terminal",
|
||||
"short_name": "bus_terminal",
|
||||
"start_url": ".",
|
||||
"display": "standalone",
|
||||
"background_color": "#0175C2",
|
||||
"theme_color": "#0175C2",
|
||||
"description": "A new Flutter project.",
|
||||
"orientation": "portrait-primary",
|
||||
"prefer_related_applications": false,
|
||||
"icons": [
|
||||
{
|
||||
"src": "icons/Icon-192.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png"
|
||||
},
|
||||
{
|
||||
"src": "icons/Icon-512.png",
|
||||
"sizes": "512x512",
|
||||
"type": "image/png"
|
||||
},
|
||||
{
|
||||
"src": "icons/Icon-maskable-192.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png",
|
||||
"purpose": "maskable"
|
||||
},
|
||||
{
|
||||
"src": "icons/Icon-maskable-512.png",
|
||||
"sizes": "512x512",
|
||||
"type": "image/png",
|
||||
"purpose": "maskable"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
# Flutter / Dart
|
||||
.dart_tool/
|
||||
.flutter-plugins
|
||||
.flutter-plugins-dependencies
|
||||
.pub-cache/
|
||||
.pub/
|
||||
/build/
|
||||
/coverage/
|
||||
**/doc/api/
|
||||
**/ios/Flutter/.last_build_id
|
||||
|
||||
# IDE / editor
|
||||
.idea/
|
||||
.vscode/
|
||||
*.iml
|
||||
*.ipr
|
||||
*.iws
|
||||
|
||||
# OS files
|
||||
.DS_Store
|
||||
*.swp
|
||||
|
||||
# Environment and secrets
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
|
||||
# Generated and platform artifacts
|
||||
android/key.properties
|
||||
android/app/debug
|
||||
android/app/profile
|
||||
android/app/release
|
||||
|
||||
# Logs and temp files
|
||||
*.log
|
||||
*.tmp
|
||||
|
||||
# Symbolication / obfuscation
|
||||
*.symbols
|
||||
*.map.json
|
||||
|
||||
# Legacy migration note
|
||||
legacy_windows_xp_plan.md
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
# Deprecated: Legacy Bus Terminal
|
||||
|
||||
This Flutter application is retained as a legacy reference implementation while the transit client moves away from the Android-era setup toward a Windows XP-era compatibility target.
|
||||
|
||||
## Status
|
||||
|
||||
- Deprecated: yes
|
||||
- Legacy platform target: Android-era Flutter app
|
||||
- Planned migration target: Windows XP-era desktop workflow
|
||||
- Kept in repo: for archival and reference during transition
|
||||
|
||||
## Notes
|
||||
|
||||
This project is not the active client for current operations. It remains available so the older UI, navigation logic, and service integration can be reviewed while the new target is prepared.
|
||||
|
||||
## Local development
|
||||
|
||||
```bash
|
||||
cd deprecated
|
||||
flutter pub get
|
||||
flutter run
|
||||
```
|
||||
|
||||
Use the appropriate device/desktop target when testing the legacy implementation.
|
||||
|
Before Width: | Height: | Size: 544 B After Width: | Height: | Size: 544 B |
|
Before Width: | Height: | Size: 442 B After Width: | Height: | Size: 442 B |
|
Before Width: | Height: | Size: 721 B After Width: | Height: | Size: 721 B |
|
Before Width: | Height: | Size: 1.0 KiB After Width: | Height: | Size: 1.0 KiB |
|
Before Width: | Height: | Size: 1.4 KiB After Width: | Height: | Size: 1.4 KiB |
|
Before Width: | Height: | Size: 11 KiB After Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 295 B After Width: | Height: | Size: 295 B |
|
Before Width: | Height: | Size: 406 B After Width: | Height: | Size: 406 B |
|
Before Width: | Height: | Size: 450 B After Width: | Height: | Size: 450 B |
|
Before Width: | Height: | Size: 282 B After Width: | Height: | Size: 282 B |
|
Before Width: | Height: | Size: 462 B After Width: | Height: | Size: 462 B |
|
Before Width: | Height: | Size: 704 B After Width: | Height: | Size: 704 B |
|
Before Width: | Height: | Size: 406 B After Width: | Height: | Size: 406 B |
|
Before Width: | Height: | Size: 586 B After Width: | Height: | Size: 586 B |
|
Before Width: | Height: | Size: 862 B After Width: | Height: | Size: 862 B |
|
Before Width: | Height: | Size: 862 B After Width: | Height: | Size: 862 B |
|
Before Width: | Height: | Size: 1.6 KiB After Width: | Height: | Size: 1.6 KiB |
|
Before Width: | Height: | Size: 762 B After Width: | Height: | Size: 762 B |
|
Before Width: | Height: | Size: 1.2 KiB After Width: | Height: | Size: 1.2 KiB |
|
Before Width: | Height: | Size: 1.4 KiB After Width: | Height: | Size: 1.4 KiB |
|
Before Width: | Height: | Size: 68 B After Width: | Height: | Size: 68 B |
|
Before Width: | Height: | Size: 68 B After Width: | Height: | Size: 68 B |
|
Before Width: | Height: | Size: 68 B After Width: | Height: | Size: 68 B |
@@ -1,11 +1,51 @@
|
||||
import 'dart:async';
|
||||
import 'dart:ui';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'screens/login_screen.dart';
|
||||
import 'screens/schedule_overview_screen.dart';
|
||||
import 'services/auth_service.dart';
|
||||
import 'theme/app_theme.dart';
|
||||
import 'services/app_navigator.dart';
|
||||
import 'services/error_log_service.dart';
|
||||
|
||||
void main() {
|
||||
runApp(const MainApp());
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
FlutterError.onError = (details) {
|
||||
FlutterError.presentError(details);
|
||||
void report() => ErrorLogService.report(
|
||||
service: 'deprecated',
|
||||
partOfService: 'FlutterError.onError',
|
||||
error: details.exceptionAsString(),
|
||||
);
|
||||
// ignore: unawaited_futures
|
||||
report();
|
||||
};
|
||||
|
||||
PlatformDispatcher.instance.onError = (error, stack) {
|
||||
// ignore: unawaited_futures
|
||||
ErrorLogService.report(
|
||||
service: 'deprecated',
|
||||
partOfService: 'PlatformDispatcher.onError',
|
||||
error: '$error\n$stack',
|
||||
);
|
||||
return true;
|
||||
};
|
||||
|
||||
runZonedGuarded(
|
||||
() {
|
||||
runApp(const MainApp());
|
||||
},
|
||||
(error, stack) {
|
||||
// ignore: unawaited_futures
|
||||
ErrorLogService.report(
|
||||
service: 'deprecated',
|
||||
partOfService: 'runZonedGuarded',
|
||||
error: '$error\n$stack',
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
class MainApp extends StatelessWidget {
|
||||
@@ -15,6 +55,8 @@ class MainApp extends StatelessWidget {
|
||||
Widget build(BuildContext context) {
|
||||
return MaterialApp(
|
||||
title: 'Bus Terminal',
|
||||
navigatorKey: navigatorKey,
|
||||
scaffoldMessengerKey: messengerKey,
|
||||
theme: AppTheme.lightTheme(),
|
||||
darkTheme: AppTheme.darkTheme(),
|
||||
themeMode: ThemeMode.system,
|
||||
@@ -41,10 +83,10 @@ class _InitialRoute extends StatelessWidget {
|
||||
body: Center(child: CircularProgressIndicator()),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
// If logged in, go to schedule; otherwise go to login
|
||||
return snapshot.data == true
|
||||
? const ScheduleOverviewScreen()
|
||||
return snapshot.data == true
|
||||
? const ScheduleOverviewScreen()
|
||||
: const LoginScreen();
|
||||
},
|
||||
);
|
||||
@@ -19,7 +19,8 @@ class User {
|
||||
} else if (rawUserCode is String) {
|
||||
parsedUserCode = int.tryParse(rawUserCode) ?? (throw FormatException('Invalid userCode'));
|
||||
} else {
|
||||
throw FormatException('Missing userCode');
|
||||
// If the backend doesn't return a userCode, treat as unknown (-1)
|
||||
parsedUserCode = -1;
|
||||
}
|
||||
|
||||
return User(
|
||||
@@ -1,5 +1,5 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../models/schedule.dart';
|
||||
import '../models/schedule.dart' as schedule;
|
||||
import '../services/schedule_service.dart';
|
||||
import '../services/auth_service.dart';
|
||||
import '../services/exceptions.dart';
|
||||
@@ -15,7 +15,7 @@ class DailyScheduleScreen extends StatefulWidget {
|
||||
class _DailyScheduleScreenState extends State<DailyScheduleScreen> {
|
||||
final _scheduleService = ScheduleService();
|
||||
final _authService = AuthService();
|
||||
late Future<DailySchedule> _scheduleFuture;
|
||||
late Future<schedule.DailySchedule> _scheduleFuture;
|
||||
DateTime _selectedDate = DateTime.now();
|
||||
|
||||
@override
|
||||
@@ -62,6 +62,16 @@ class _DailyScheduleScreenState extends State<DailyScheduleScreen> {
|
||||
}
|
||||
}
|
||||
|
||||
// Group routes by hour for better visual organization
|
||||
Map<int, List<schedule.Route>> _groupByHour(List<schedule.Route> routes) {
|
||||
final grouped = <int, List<schedule.Route>>{};
|
||||
for (final route in routes) {
|
||||
final hour = route.startTime.hour;
|
||||
grouped.putIfAbsent(hour, () => []).add(route);
|
||||
}
|
||||
return grouped;
|
||||
}
|
||||
|
||||
void _moveDay(int deltaDays) {
|
||||
setState(() {
|
||||
_selectedDate = _selectedDate.add(Duration(days: deltaDays));
|
||||
@@ -198,7 +208,7 @@ class _DailyScheduleScreenState extends State<DailyScheduleScreen> {
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: FutureBuilder<DailySchedule>(
|
||||
child: FutureBuilder<schedule.DailySchedule>(
|
||||
future: _scheduleFuture,
|
||||
builder: (context, snapshot) {
|
||||
if (snapshot.connectionState == ConnectionState.waiting) {
|
||||
@@ -267,12 +277,12 @@ class _DailyScheduleScreenState extends State<DailyScheduleScreen> {
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'No routes scheduled',
|
||||
'Geen actieve ritten',
|
||||
style: Theme.of(context).textTheme.titleMedium,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'Check back later for your schedule',
|
||||
'Je hebt geen geplande ritten voor deze dag',
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
@@ -288,25 +298,64 @@ class _DailyScheduleScreenState extends State<DailyScheduleScreen> {
|
||||
..sort((a, b) => a.startTime.compareTo(b.startTime));
|
||||
final scheduledRoutes = routes.where((r) => r.status == 'scheduled').toList();
|
||||
final inProgressRoutes = routes.where((r) => r.status == 'in_progress').toList();
|
||||
final completedRoutes = routes.where((r) => r.status == 'completed').toList();
|
||||
|
||||
// Merge and group by hour
|
||||
final allActiveRoutes = [...inProgressRoutes, ...scheduledRoutes]
|
||||
..sort((a, b) => a.startTime.compareTo(b.startTime));
|
||||
final hourGroups = _groupByHour(allActiveRoutes);
|
||||
final sortedHours = hourGroups.keys.toList()..sort();
|
||||
|
||||
return RefreshIndicator(
|
||||
onRefresh: _refreshSchedule,
|
||||
child: ListView(
|
||||
padding: const EdgeInsets.only(bottom: 16),
|
||||
children: [
|
||||
if (inProgressRoutes.isNotEmpty) ...[
|
||||
_sectionHeader('In Progress', colorScheme.tertiary),
|
||||
...inProgressRoutes.map((route) => RouteCard(route: route, onTap: () {})),
|
||||
],
|
||||
if (scheduledRoutes.isNotEmpty) ...[
|
||||
_sectionHeader('Scheduled', colorScheme.primary),
|
||||
...scheduledRoutes.map((route) => RouteCard(route: route, onTap: () {})),
|
||||
],
|
||||
if (completedRoutes.isNotEmpty) ...[
|
||||
_sectionHeader('Completed', colorScheme.secondary),
|
||||
...completedRoutes.map((route) => RouteCard(route: route, onTap: () {})),
|
||||
],
|
||||
if (allActiveRoutes.isEmpty)
|
||||
Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 32),
|
||||
child: Text(
|
||||
'Geen actieve ritten voor deze dag',
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
else
|
||||
...sortedHours.map((hour) {
|
||||
final routesForHour = hourGroups[hour] ?? [];
|
||||
return Column(
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(left: 16, top: 16, bottom: 8),
|
||||
child: Row(
|
||||
children: [
|
||||
Text(
|
||||
'${hour.toString().padLeft(2, '0')}:00 uur',
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
color: colorScheme.primary,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Container(
|
||||
height: 1,
|
||||
color: colorScheme.outlineVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
...routesForHour.map((route) => Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
child: RouteCard(route: route, onTap: () {}),
|
||||
)),
|
||||
const SizedBox(height: 4),
|
||||
],
|
||||
);
|
||||
}),
|
||||
const SizedBox(height: 8),
|
||||
],
|
||||
),
|
||||
@@ -319,17 +368,4 @@ class _DailyScheduleScreenState extends State<DailyScheduleScreen> {
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _sectionHeader(String title, Color color) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(left: 16, top: 24, bottom: 8),
|
||||
child: Text(
|
||||
title,
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
color: color,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../services/auth_service.dart';
|
||||
import '../services/error_log_service.dart';
|
||||
import '../widgets/custom_input_field.dart';
|
||||
|
||||
class LoginScreen extends StatefulWidget {
|
||||
@@ -37,7 +38,17 @@ class _LoginScreenState extends State<LoginScreen> {
|
||||
final input = _userCodeController.text.trim();
|
||||
final parsedUserCode = int.tryParse(input);
|
||||
if (parsedUserCode == null) {
|
||||
throw Exception('User code must be a number');
|
||||
await ErrorLogService.report(
|
||||
service: 'bus_terminal',
|
||||
partOfService: 'LoginScreen._handleLogin',
|
||||
error: 'User code must be a number',
|
||||
);
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_errorMessage = 'User code must be a number';
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
await _authService.login(
|
||||
@@ -50,6 +61,11 @@ class _LoginScreenState extends State<LoginScreen> {
|
||||
Navigator.of(context).pushReplacementNamed('/schedule');
|
||||
}
|
||||
} catch (e) {
|
||||
await ErrorLogService.report(
|
||||
service: 'bus_terminal',
|
||||
partOfService: 'LoginScreen._handleLogin.catch',
|
||||
error: e.toString(),
|
||||
);
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_errorMessage = e.toString().replaceAll('Exception: ', '');
|
||||
@@ -0,0 +1,332 @@
|
||||
// ignore_for_file: use_build_context_synchronously
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import '../models/schedule.dart' as sched;
|
||||
import '../services/schedule_service.dart';
|
||||
|
||||
class RecurringSchedulesScreen extends StatefulWidget {
|
||||
const RecurringSchedulesScreen({super.key});
|
||||
|
||||
@override
|
||||
State<RecurringSchedulesScreen> createState() => _RecurringSchedulesScreenState();
|
||||
}
|
||||
|
||||
class _RecurringSchedulesScreenState extends State<RecurringSchedulesScreen> {
|
||||
final _scheduleService = ScheduleService();
|
||||
late Future<List<sched.ServiceSchedule>> _schedulesFuture;
|
||||
String _selectedSortBy = 'line'; // 'line', 'time', 'weekday'
|
||||
final Set<int> _expandedLineIds = {};
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_loadRecurringSchedules();
|
||||
}
|
||||
|
||||
void _loadRecurringSchedules() {
|
||||
_schedulesFuture = _scheduleService.getRecurringSchedules();
|
||||
}
|
||||
|
||||
String _formatWeekdays(List<int> weekdays) {
|
||||
const dayLabels = ['Zo', 'Ma', 'Di', 'Wo', 'Do', 'Vr', 'Za'];
|
||||
if (weekdays.isEmpty) return 'Eenmalig';
|
||||
if (weekdays.length == 7) return 'Dagelijks';
|
||||
|
||||
final sorted = weekdays.toSet().toList()..sort((a, b) => a.compareTo(b));
|
||||
return sorted.map((d) => dayLabels[d]).join(', ');
|
||||
}
|
||||
|
||||
String _formatTime(DateTime dt) {
|
||||
return '${dt.hour.toString().padLeft(2, '0')}:${dt.minute.toString().padLeft(2, '0')}';
|
||||
}
|
||||
|
||||
List<sched.ServiceSchedule> _sortSchedules(List<sched.ServiceSchedule> schedules) {
|
||||
final sorted = List<sched.ServiceSchedule>.from(schedules);
|
||||
|
||||
switch (_selectedSortBy) {
|
||||
case 'line':
|
||||
sorted.sort((a, b) => a.lineNumber.compareTo(b.lineNumber));
|
||||
break;
|
||||
case 'time':
|
||||
sorted.sort((a, b) => a.startTime.compareTo(b.startTime));
|
||||
break;
|
||||
case 'weekday':
|
||||
sorted.sort((a, b) {
|
||||
final aFirst = a.weekdays.isEmpty ? 7 : a.weekdays.first;
|
||||
final bFirst = b.weekdays.isEmpty ? 7 : b.weekdays.first;
|
||||
return aFirst.compareTo(bFirst);
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
return sorted;
|
||||
}
|
||||
|
||||
Map<int, List<sched.ServiceSchedule>> _groupByLine(List<sched.ServiceSchedule> schedules) {
|
||||
final grouped = <int, List<sched.ServiceSchedule>>{};
|
||||
for (final schedule in schedules) {
|
||||
grouped.putIfAbsent(schedule.lineNumber, () => []).add(schedule);
|
||||
}
|
||||
return grouped;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Vaste Diensten'),
|
||||
centerTitle: true,
|
||||
actions: [
|
||||
PopupMenuButton<String>(
|
||||
onSelected: (value) {
|
||||
setState(() => _selectedSortBy = value);
|
||||
},
|
||||
itemBuilder: (context) => [
|
||||
PopupMenuItem(
|
||||
value: 'line',
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(Icons.sort_by_alpha, color: _selectedSortBy == 'line' ? colorScheme.primary : null),
|
||||
const SizedBox(width: 8),
|
||||
const Text('Lijn'),
|
||||
],
|
||||
),
|
||||
),
|
||||
PopupMenuItem(
|
||||
value: 'time',
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(Icons.schedule, color: _selectedSortBy == 'time' ? colorScheme.primary : null),
|
||||
const SizedBox(width: 8),
|
||||
const Text('Tijd'),
|
||||
],
|
||||
),
|
||||
),
|
||||
PopupMenuItem(
|
||||
value: 'weekday',
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(Icons.calendar_today, color: _selectedSortBy == 'weekday' ? colorScheme.primary : null),
|
||||
const SizedBox(width: 8),
|
||||
const Text('Weekdag'),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
child: const Padding(
|
||||
padding: EdgeInsets.symmetric(horizontal: 16),
|
||||
child: Icon(Icons.filter_list),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
body: FutureBuilder<List<sched.ServiceSchedule>>(
|
||||
future: _schedulesFuture,
|
||||
builder: (context, snapshot) {
|
||||
if (snapshot.connectionState == ConnectionState.waiting) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
|
||||
if (snapshot.hasError) {
|
||||
return Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(Icons.error_outline, size: 48, color: colorScheme.error),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'Fout bij laden: ${snapshot.error}',
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
FilledButton(
|
||||
onPressed: () {
|
||||
setState(() => _loadRecurringSchedules());
|
||||
},
|
||||
child: const Text('Opnieuw proberen'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
final allSchedules = snapshot.data ?? [];
|
||||
// Filter to show only truly recurring schedules (with weekdays > 0)
|
||||
final schedules = allSchedules.where((s) => s.weekdays.isNotEmpty).toList();
|
||||
|
||||
if (schedules.isEmpty) {
|
||||
return Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(Icons.event_note_outlined, size: 48, color: colorScheme.outline),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'Geen herhaalde diensten gevonden',
|
||||
style: Theme.of(context).textTheme.titleMedium,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'Herhaalde diensten worden hier weergegeven',
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
final sortedSchedules = _sortSchedules(schedules);
|
||||
final groupedByLine = _groupByLine(sortedSchedules);
|
||||
|
||||
return ListView.builder(
|
||||
padding: const EdgeInsets.fromLTRB(12, 12, 12, 24),
|
||||
itemCount: groupedByLine.length,
|
||||
itemBuilder: (context, lineIndex) {
|
||||
final lineNumber = groupedByLine.keys.toList()[lineIndex];
|
||||
final lineSchedules = groupedByLine[lineNumber] ?? [];
|
||||
final isExpanded = _expandedLineIds.contains(lineNumber);
|
||||
|
||||
return Column(
|
||||
children: [
|
||||
Card(
|
||||
child: InkWell(
|
||||
onTap: () {
|
||||
setState(() {
|
||||
if (isExpanded) {
|
||||
_expandedLineIds.remove(lineNumber);
|
||||
} else {
|
||||
_expandedLineIds.add(lineNumber);
|
||||
}
|
||||
});
|
||||
},
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Lijn $lineNumber',
|
||||
style: Theme.of(context).textTheme.titleLarge?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'${lineSchedules.length} diensten',
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: colorScheme.outline,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
Icon(
|
||||
isExpanded ? Icons.expand_less : Icons.expand_more,
|
||||
color: colorScheme.primary,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
if (isExpanded)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 8),
|
||||
child: ListView.separated(
|
||||
shrinkWrap: true,
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
itemCount: lineSchedules.length,
|
||||
separatorBuilder: (_, _) => const SizedBox(height: 8),
|
||||
itemBuilder: (context, scheduleIndex) {
|
||||
final schedule = lineSchedules[scheduleIndex];
|
||||
return _ScheduleCard(schedule: schedule, formatTime: _formatTime, formatWeekdays: _formatWeekdays);
|
||||
},
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ScheduleCard extends StatelessWidget {
|
||||
final sched.ServiceSchedule schedule;
|
||||
final String Function(DateTime) formatTime;
|
||||
final String Function(List<int>) formatWeekdays;
|
||||
|
||||
const _ScheduleCard({
|
||||
required this.schedule,
|
||||
required this.formatTime,
|
||||
required this.formatWeekdays,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
|
||||
return Card(
|
||||
elevation: 1,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'${formatTime(schedule.startTime)} - ${formatTime(schedule.endTime)}',
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
schedule.busName,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: colorScheme.outline,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
Chip(
|
||||
label: Text(
|
||||
formatWeekdays(schedule.weekdays),
|
||||
style: Theme.of(context).textTheme.labelSmall,
|
||||
),
|
||||
avatar: const Icon(Icons.calendar_today, size: 16),
|
||||
visualDensity: VisualDensity.compact,
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,674 @@
|
||||
// ignore_for_file: use_build_context_synchronously
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import '../models/schedule.dart' as sched;
|
||||
import '../models/navigation.dart';
|
||||
import '../services/auth_service.dart';
|
||||
import '../services/schedule_service.dart';
|
||||
import '../screens/navigation_screen.dart';
|
||||
import '../screens/recurring_schedules_screen.dart';
|
||||
|
||||
class ScheduleOverviewScreen extends StatefulWidget {
|
||||
const ScheduleOverviewScreen({super.key});
|
||||
|
||||
@override
|
||||
State<ScheduleOverviewScreen> createState() => _ScheduleOverviewScreenState();
|
||||
}
|
||||
|
||||
class _ScheduleOverviewScreenState extends State<ScheduleOverviewScreen> with TickerProviderStateMixin {
|
||||
final _scheduleService = ScheduleService();
|
||||
final _authService = AuthService();
|
||||
|
||||
late Future<List<sched.ServiceSchedule>> _scheduleFuture;
|
||||
DateTime _selectedDate = DateTime.now();
|
||||
late TabController _tabController;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_scheduleFuture = _scheduleService.getSchedules(_selectedDate);
|
||||
_tabController = TabController(length: 3, vsync: this);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_tabController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _handleLogout() async {
|
||||
await _authService.logout();
|
||||
if (mounted) {
|
||||
Navigator.of(context).pushReplacementNamed('/login');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _refreshSchedules() async {
|
||||
setState(() {
|
||||
_scheduleFuture = _scheduleService.getSchedules(_selectedDate);
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _selectDate() async {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
final picked = await showDatePicker(
|
||||
context: context,
|
||||
initialDate: _selectedDate,
|
||||
firstDate: DateTime.now().subtract(const Duration(days: 7)),
|
||||
lastDate: DateTime.now().add(const Duration(days: 30)),
|
||||
builder: (context, child) {
|
||||
return Theme(
|
||||
data: Theme.of(context).copyWith(
|
||||
dialogBackgroundColor: colorScheme.surface,
|
||||
),
|
||||
child: child!,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
if (picked != null && picked != _selectedDate) {
|
||||
setState(() {
|
||||
_selectedDate = picked;
|
||||
});
|
||||
_refreshSchedules();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _showScheduleDetails(sched.ServiceSchedule svc) async {
|
||||
try {
|
||||
final stops = await _scheduleService.getScheduleStops(svc.id);
|
||||
if (!mounted) return;
|
||||
|
||||
await showModalBottomSheet<void>(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
showDragHandle: true,
|
||||
builder: (sheetContext) {
|
||||
return DraggableScrollableSheet(
|
||||
expand: false,
|
||||
initialChildSize: 0.75,
|
||||
minChildSize: 0.45,
|
||||
maxChildSize: 0.95,
|
||||
builder: (context, scrollController) {
|
||||
return ListView(
|
||||
controller: scrollController,
|
||||
padding: const EdgeInsets.fromLTRB(20, 8, 20, 24),
|
||||
children: [
|
||||
Text(
|
||||
'Lijn ${svc.lineNumber}',
|
||||
style: Theme.of(context).textTheme.headlineSmall?.copyWith(
|
||||
fontWeight: FontWeight.w800,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
svc.busName,
|
||||
style: Theme.of(context).textTheme.titleMedium,
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'${_formatTime(svc.startTime)} - ${_formatTime(svc.endTime)}',
|
||||
style: Theme.of(context).textTheme.bodyMedium,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
_InfoChip(label: svc.status),
|
||||
_InfoChip(label: svc.isRecurring ? _weekdayLabel(svc.weekdays) : 'Eenmalig'),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: FilledButton.icon(
|
||||
onPressed: () async {
|
||||
try {
|
||||
await _scheduleService.updateScheduleStatus(
|
||||
svc.id,
|
||||
'in_progress',
|
||||
date: svc.startTime,
|
||||
);
|
||||
if (!mounted) return;
|
||||
Navigator.of(sheetContext).pop();
|
||||
|
||||
final routeObj = sched.Route(
|
||||
id: svc.id,
|
||||
busLine: sched.BusLine(
|
||||
id: svc.busLineId,
|
||||
lineNumber: svc.lineNumber,
|
||||
startStop: '',
|
||||
endStop: '',
|
||||
estimatedDuration: 0,
|
||||
),
|
||||
busType: sched.BusType(
|
||||
id: svc.busId,
|
||||
name: svc.busName,
|
||||
seatCapacity: 0,
|
||||
licensePlate: '',
|
||||
),
|
||||
startTime: svc.startTime,
|
||||
endTime: svc.endTime,
|
||||
status: 'in_progress',
|
||||
);
|
||||
|
||||
final navStops = stops
|
||||
.map((s) => NavigationPoint(
|
||||
latitude: s.latitude,
|
||||
longitude: s.longitude,
|
||||
name: s.name,
|
||||
))
|
||||
.toList();
|
||||
|
||||
try {
|
||||
await Navigator.of(context).push(
|
||||
MaterialPageRoute(
|
||||
builder: (_) => NavigationScreen(route: routeObj, initialStops: navStops),
|
||||
),
|
||||
);
|
||||
} catch (navErr) {
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('Navigatiefout: ${navErr.toString()}')),
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('Status bijwerken mislukt: $e')),
|
||||
);
|
||||
}
|
||||
},
|
||||
icon: const Icon(Icons.navigation),
|
||||
label: const Text('Start route'),
|
||||
),
|
||||
),
|
||||
Text(
|
||||
'Haltes',
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
if (stops.isEmpty)
|
||||
Text(
|
||||
'Geen haltes gekoppeld aan deze dienst.',
|
||||
style: Theme.of(context).textTheme.bodyMedium,
|
||||
)
|
||||
else
|
||||
...stops.map((stop) {
|
||||
final departureTime = svc.startTime.add(
|
||||
Duration(minutes: stop.estimatedArrivalMinutes),
|
||||
);
|
||||
return Card(
|
||||
child: ListTile(
|
||||
dense: true,
|
||||
title: Text('${stop.order}. ${stop.name}'),
|
||||
subtitle: Text('${stop.estimatedArrivalMinutes} min na vertrek'),
|
||||
trailing: Text(_formatTime(departureTime)),
|
||||
),
|
||||
);
|
||||
}),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('Kon dienstdetails niet laden: $e')),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Diensten'),
|
||||
centerTitle: true,
|
||||
elevation: 0,
|
||||
bottom: TabBar(
|
||||
controller: _tabController,
|
||||
tabs: const [
|
||||
Tab(icon: Icon(Icons.calendar_today), text: 'Dagschema'),
|
||||
Tab(icon: Icon(Icons.repeat), text: 'Vaste diensten'),
|
||||
Tab(icon: Icon(Icons.timeline), text: 'Voortgang'),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.logout),
|
||||
tooltip: 'Logout',
|
||||
onPressed: _handleLogout,
|
||||
),
|
||||
],
|
||||
),
|
||||
body: TabBarView(
|
||||
controller: _tabController,
|
||||
children: [
|
||||
_DailyScheduleTab(
|
||||
scheduleService: _scheduleService,
|
||||
selectedDate: _selectedDate,
|
||||
onSelectDate: _selectDate,
|
||||
onRefresh: _refreshSchedules,
|
||||
onShowDetails: _showScheduleDetails,
|
||||
scheduleFuture: _scheduleFuture,
|
||||
),
|
||||
const RecurringSchedulesScreen(),
|
||||
_ProgressTab(
|
||||
scheduleService: _scheduleService,
|
||||
selectedDate: _selectedDate,
|
||||
scheduleFuture: _scheduleFuture,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ProgressTab extends StatelessWidget {
|
||||
final ScheduleService scheduleService;
|
||||
final DateTime selectedDate;
|
||||
final Future<List<sched.ServiceSchedule>> scheduleFuture;
|
||||
|
||||
const _ProgressTab({
|
||||
required this.scheduleService,
|
||||
required this.selectedDate,
|
||||
required this.scheduleFuture,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final dateStr = '${selectedDate.year}-${selectedDate.month.toString().padLeft(2, '0')}-${selectedDate.day.toString().padLeft(2, '0')}';
|
||||
|
||||
return Column(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Text('Voortgang voor $dateStr', style: Theme.of(context).textTheme.titleLarge),
|
||||
IconButton(
|
||||
onPressed: () async {
|
||||
// refresh handled by parent via reselecting date; show a simple feedback
|
||||
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Ververs de datum in Dagschema-tab om andere datum te laden')));
|
||||
},
|
||||
icon: const Icon(Icons.info_outline),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: FutureBuilder<List<sched.ServiceSchedule>>(
|
||||
future: scheduleFuture,
|
||||
builder: (context, snapshot) {
|
||||
if (snapshot.connectionState == ConnectionState.waiting) return const Center(child: CircularProgressIndicator());
|
||||
if (snapshot.hasError) return Center(child: Text('Fout bij laden: ${snapshot.error}'));
|
||||
|
||||
final schedules = snapshot.data ?? [];
|
||||
if (schedules.isEmpty) return Center(child: Text('Geen diensten op $dateStr'));
|
||||
|
||||
return ListView.builder(
|
||||
padding: const EdgeInsets.all(12),
|
||||
itemCount: schedules.length,
|
||||
itemBuilder: (context, index) {
|
||||
final svc = schedules[index];
|
||||
return Card(
|
||||
child: ListTile(
|
||||
title: Text('Lijn ${svc.lineNumber} — ${svc.busName}'),
|
||||
subtitle: Text(_formatTime(svc.startTime)),
|
||||
trailing: TextButton(
|
||||
onPressed: () async {
|
||||
try {
|
||||
final progress = await scheduleService.getScheduleProgress(svc.id, selectedDate);
|
||||
if (!context.mounted) return;
|
||||
await showModalBottomSheet<void>(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
builder: (ctx) {
|
||||
final stops = (progress['stops'] as List<dynamic>?) ?? [];
|
||||
return Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 16, 16, 32),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('Voortgang — Lijn ${svc.lineNumber}', style: Theme.of(ctx).textTheme.headlineSmall),
|
||||
const SizedBox(height: 8),
|
||||
Text('Status: ${progress['schedule']?['status'] ?? 'onbekend'}'),
|
||||
Text('Driver state: ${progress['driverState'] ?? 'onbekend'}'),
|
||||
Text('Passed: ${progress['passedStopCount'] ?? 0} / ${progress['totalStopCount'] ?? 0}'),
|
||||
const SizedBox(height: 12),
|
||||
const Text('Haltes:'),
|
||||
const SizedBox(height: 8),
|
||||
Expanded(
|
||||
child: ListView.builder(
|
||||
shrinkWrap: true,
|
||||
itemCount: stops.length,
|
||||
itemBuilder: (c, i) {
|
||||
final s = stops[i] as Map<String, dynamic>;
|
||||
return ListTile(
|
||||
dense: true,
|
||||
title: Text('${s['stopOrder']}. ${s['stopName']}'),
|
||||
subtitle: Text('Scheduled: ${s['scheduledPassedAt'] ?? '-'}\nActual: ${s['actualPassedAt'] ?? '-'}'),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
} catch (e) {
|
||||
if (!context.mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Kon voortgang niet laden: $e')));
|
||||
}
|
||||
},
|
||||
child: const Text('Bekijk voortgang'),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _DailyScheduleTab extends StatelessWidget {
|
||||
final ScheduleService scheduleService;
|
||||
final DateTime selectedDate;
|
||||
final VoidCallback onSelectDate;
|
||||
final VoidCallback onRefresh;
|
||||
final Function(sched.ServiceSchedule) onShowDetails;
|
||||
final Future<List<sched.ServiceSchedule>> scheduleFuture;
|
||||
|
||||
const _DailyScheduleTab({
|
||||
required this.scheduleService,
|
||||
required this.selectedDate,
|
||||
required this.onSelectDate,
|
||||
required this.onRefresh,
|
||||
required this.onShowDetails,
|
||||
required this.scheduleFuture,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
final dateStr =
|
||||
'${selectedDate.year}-${selectedDate.month.toString().padLeft(2, '0')}-${selectedDate.day.toString().padLeft(2, '0')}';
|
||||
|
||||
return Container(
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
colors: Theme.of(context).brightness == Brightness.dark
|
||||
? const [Color(0xFF0B1220), Color(0xFF111827)]
|
||||
: const [Color(0xFFF1F5F9), Color(0xFFE2E8F0)],
|
||||
begin: Alignment.topCenter,
|
||||
end: Alignment.bottomCenter,
|
||||
),
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
Container(
|
||||
margin: const EdgeInsets.fromLTRB(16, 16, 16, 12),
|
||||
padding: const EdgeInsets.all(18),
|
||||
decoration: BoxDecoration(
|
||||
gradient: const LinearGradient(
|
||||
colors: [Color(0xFF0F172A), Color(0xFF1D4ED8)],
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
),
|
||||
borderRadius: BorderRadius.circular(24),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withOpacity(0.16),
|
||||
blurRadius: 22,
|
||||
offset: const Offset(0, 10),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Geplande diensten',
|
||||
style: Theme.of(context).textTheme.labelSmall?.copyWith(
|
||||
color: Colors.white.withOpacity(0.78),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
dateStr,
|
||||
style: Theme.of(context).textTheme.headlineMedium?.copyWith(
|
||||
color: Colors.white,
|
||||
fontWeight: FontWeight.w800,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
'Automatisch berekende eindtijden, haltes en herhalende weekdagen',
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: Colors.white.withOpacity(0.84),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: SizedBox(
|
||||
height: 48,
|
||||
child: OutlinedButton.icon(
|
||||
onPressed: onSelectDate,
|
||||
icon: const Icon(Icons.calendar_today, size: 18),
|
||||
label: const Text('Wijzig datum'),
|
||||
style: OutlinedButton.styleFrom(
|
||||
foregroundColor: Colors.white,
|
||||
side: BorderSide(color: Colors.white.withOpacity(0.28)),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: FutureBuilder<List<sched.ServiceSchedule>>(
|
||||
future: scheduleFuture,
|
||||
builder: (context, snapshot) {
|
||||
if (snapshot.connectionState == ConnectionState.waiting) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
|
||||
if (snapshot.hasError) {
|
||||
return Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(Icons.error_outline, size: 48, color: colorScheme.error),
|
||||
const SizedBox(height: 16),
|
||||
Text('Fout bij laden: ${snapshot.error}', textAlign: TextAlign.center),
|
||||
const SizedBox(height: 16),
|
||||
FilledButton(
|
||||
onPressed: onRefresh,
|
||||
child: const Text('Opnieuw proberen'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
final schedules = snapshot.data ?? [];
|
||||
if (schedules.isEmpty) {
|
||||
return Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(Icons.event_available_outlined, size: 48, color: colorScheme.outline),
|
||||
const SizedBox(height: 16),
|
||||
Text('Geen diensten op $dateStr', style: Theme.of(context).textTheme.titleMedium),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return RefreshIndicator(
|
||||
onRefresh: () async => onRefresh(),
|
||||
child: ListView.builder(
|
||||
padding: const EdgeInsets.fromLTRB(0, 12, 0, 24),
|
||||
itemCount: schedules.length,
|
||||
itemBuilder: (context, index) {
|
||||
final schedule = schedules[index];
|
||||
return _ScheduleSummaryCard(
|
||||
schedule: schedule,
|
||||
onTap: () => onShowDetails(schedule),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ScheduleSummaryCard extends StatelessWidget {
|
||||
final sched.ServiceSchedule schedule;
|
||||
final VoidCallback onTap;
|
||||
|
||||
const _ScheduleSummaryCard({
|
||||
required this.schedule,
|
||||
required this.onTap,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
|
||||
return Card(
|
||||
margin: const EdgeInsets.fromLTRB(16, 8, 16, 8),
|
||||
elevation: 0,
|
||||
color: colorScheme.surface,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
|
||||
child: InkWell(
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
onTap: onTap,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
colors: [colorScheme.primary, colorScheme.tertiary],
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Text(
|
||||
'Line ${schedule.lineNumber}',
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
color: Colors.white,
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 18,
|
||||
),
|
||||
),
|
||||
),
|
||||
// Only show status for one-time schedules; recurring schedules have no fixed status
|
||||
if (!schedule.isRecurring)
|
||||
_InfoChip(label: schedule.status),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
schedule.busName,
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'${_formatTime(schedule.startTime)} - ${_formatTime(schedule.endTime)}',
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
schedule.isRecurring ? _weekdayLabel(schedule.weekdays) : 'Eenmalige dienst',
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: TextButton.icon(
|
||||
onPressed: onTap,
|
||||
icon: const Icon(Icons.list_alt, size: 18),
|
||||
label: const Text('Haltes'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _InfoChip extends StatelessWidget {
|
||||
final String label;
|
||||
|
||||
const _InfoChip({required this.label});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context).colorScheme.primaryContainer,
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
),
|
||||
child: Text(
|
||||
label,
|
||||
style: Theme.of(context).textTheme.labelMedium?.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _formatTime(DateTime time) {
|
||||
return '${time.hour.toString().padLeft(2, '0')}:${time.minute.toString().padLeft(2, '0')}';
|
||||
}
|
||||
|
||||
String _weekdayLabel(List<int> weekdays) {
|
||||
const labels = ['Zo', 'Ma', 'Di', 'Wo', 'Do', 'Vr', 'Za'];
|
||||
if (weekdays.isEmpty) {
|
||||
return 'Eenmalige dienst';
|
||||
}
|
||||
if (weekdays.length == 7) {
|
||||
return 'Dagelijks';
|
||||
}
|
||||
return weekdays.where((day) => day >= 0 && day < labels.length).map((day) => labels[day]).join(', ');
|
||||
}
|
||||