diff --git a/.dockerignore b/.dockerignore index 5b1aea136..25672b03f 100644 --- a/.dockerignore +++ b/.dockerignore @@ -32,6 +32,5 @@ server/tests/ server/vitest.config.ts **/*.test.ts **/*.spec.ts -wiki/ scripts/ charts/ diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 67fc0f9fa..f2a420429 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -8,11 +8,11 @@ body: attributes: label: Pre-flight checklist options: - - label: I have searched [existing issues](https://github.com/mauriceboe/TREK/issues) and this bug has not been reported yet + - label: I have searched [existing issues](https://github.com/liketrek/TREK/issues) and this bug has not been reported yet required: true - label: I am running the latest available version of TREK required: true - - label: I have read the [Troubleshooting guide](https://github.com/mauriceboe/TREK/wiki/Troubleshooting) and my issue is not covered there + - label: I have read the [Troubleshooting guide](https://github.com/liketrek/TREK/wiki/Troubleshooting) and my issue is not covered there required: true - type: input diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index a1e0f7bb9..4ec777110 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1,11 +1,11 @@ blank_issues_enabled: false contact_links: - name: Documentation - url: https://github.com/mauriceboe/TREK/wiki + url: https://github.com/liketrek/TREK/wiki about: Check the docs before opening an issue - name: Feature Request - url: https://github.com/mauriceboe/TREK/discussions/new?category=feature-requests + url: https://github.com/liketrek/TREK/discussions/new?category=feature-requests about: Suggest a new feature or improvement in Discussions - name: Questions & Help - url: https://github.com/mauriceboe/TREK/discussions + url: https://github.com/liketrek/TREK/discussions about: For questions and general help, use Discussions instead \ No newline at end of file diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index be0f9d72e..bcb8250db 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -13,8 +13,8 @@ - [ ] Documentation update ## Checklist -- [ ] I have read the [Contributing Guidelines](https://github.com/mauriceboe/TREK/wiki/Contributing) -- [ ] My branch is [up to date with `dev`](https://github.com/mauriceboe/TREK/wiki/Development-environment#3-keep-your-fork-up-to-date) +- [ ] I have read the [Contributing Guidelines](https://github.com/liketrek/TREK/wiki/Contributing) +- [ ] My branch is [up to date with `dev`](https://github.com/liketrek/TREK/wiki/Development-environment#3-keep-your-fork-up-to-date) - [ ] This PR targets the `dev` branch, not `main` *(wiki-only PRs are exempt)* - [ ] I have tested my changes locally - [ ] I have added/updated tests that prove my fix is effective or that my feature works diff --git a/.github/workflows/close-stale-invalid-titles.yml b/.github/workflows/close-stale-invalid-titles.yml index 9eb1ce338..93ea61037 100644 --- a/.github/workflows/close-stale-invalid-titles.yml +++ b/.github/workflows/close-stale-invalid-titles.yml @@ -9,7 +9,7 @@ permissions: jobs: close-stale: - if: github.repository == 'mauriceboe/TREK' + if: github.repository == 'liketrek/TREK' runs-on: ubuntu-latest steps: - name: Close stale invalid-title issues diff --git a/.github/workflows/close-stale-wrong-branch.yml b/.github/workflows/close-stale-wrong-branch.yml index c1a41a3cd..1859f7018 100644 --- a/.github/workflows/close-stale-wrong-branch.yml +++ b/.github/workflows/close-stale-wrong-branch.yml @@ -10,7 +10,7 @@ permissions: jobs: close-stale: - if: github.repository == 'mauriceboe/TREK' + if: github.repository == 'liketrek/TREK' runs-on: ubuntu-latest steps: - name: Close stale wrong-base-branch PRs diff --git a/.github/workflows/close-untitled-issues.yml b/.github/workflows/close-untitled-issues.yml index 0cd817682..f5ada9b6a 100644 --- a/.github/workflows/close-untitled-issues.yml +++ b/.github/workflows/close-untitled-issues.yml @@ -9,7 +9,7 @@ permissions: jobs: check-title: - if: github.repository == 'mauriceboe/TREK' + if: github.repository == 'liketrek/TREK' runs-on: ubuntu-latest steps: - name: Flag or redirect issue @@ -77,7 +77,7 @@ jobs: body: [ '## Wrong place for feature requests', '', - 'Feature requests should be submitted in [Discussions](https://github.com/mauriceboe/TREK/discussions/new?category=feature-requests), not as issues.', + 'Feature requests should be submitted in [Discussions](https://github.com/liketrek/TREK/discussions/new?category=feature-requests), not as issues.', '', 'This issue has been closed. Feel free to re-submit your idea in the right place!', ].join('\n'), diff --git a/.github/workflows/docker-dev.yml b/.github/workflows/docker-dev.yml index d2e3ed070..9ea4b6bf2 100644 --- a/.github/workflows/docker-dev.yml +++ b/.github/workflows/docker-dev.yml @@ -18,7 +18,7 @@ concurrency: jobs: version-bump: - if: github.repository == 'mauriceboe/TREK' + if: github.repository == 'liketrek/TREK' runs-on: ubuntu-latest outputs: version: ${{ steps.bump.outputs.VERSION }} @@ -98,7 +98,7 @@ jobs: with: context: . platforms: ${{ matrix.platform }} - outputs: type=image,name=mauriceboe/trek,push-by-digest=true,name-canonical=true,push=true + outputs: type=image,name=mauriceboe/TREK,push-by-digest=true,name-canonical=true,push=true no-cache: true build-args: | APP_VERSION=${{ needs.version-bump.outputs.version }} @@ -145,16 +145,16 @@ jobs: working-directory: /tmp/digests run: | VERSION="${{ needs.version-bump.outputs.version }}" - mapfile -t digests < <(printf 'mauriceboe/trek@sha256:%s\n' *) + mapfile -t digests < <(printf 'mauriceboe/TREK@sha256:%s\n' *) MAJOR_TAG="$(echo "$VERSION" | cut -d. -f1)-pre" docker buildx imagetools create \ - -t "mauriceboe/trek:latest-pre" \ - -t "mauriceboe/trek:$MAJOR_TAG" \ - -t "mauriceboe/trek:$VERSION" \ + -t "mauriceboe/TREK:latest-pre" \ + -t "mauriceboe/TREK:$MAJOR_TAG" \ + -t "mauriceboe/TREK:$VERSION" \ "${digests[@]}" - name: Inspect manifest - run: docker buildx imagetools inspect mauriceboe/trek:latest-pre + run: docker buildx imagetools inspect mauriceboe/TREK:latest-pre - name: Push git tag run: | diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index bd31e32f3..5f9837396 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -1,17 +1,6 @@ name: Build & Push Docker Image on: - push: - branches: [main] - paths-ignore: - - 'docs/**' - - '**/*.md' - - 'wiki/**' - - '.github/workflows/**' - - '.github/ISSUE_TEMPLATE/**' - - '.github/FUNDING.yml' - - '.github/PULL_REQUEST_TEMPLATE.md' - - 'plugin-sdk/**' workflow_dispatch: inputs: bump: @@ -33,7 +22,7 @@ concurrency: jobs: version-bump: - if: github.repository == 'mauriceboe/TREK' + if: github.repository == 'liketrek/TREK' runs-on: ubuntu-latest outputs: version: ${{ steps.bump.outputs.VERSION }} @@ -149,7 +138,7 @@ jobs: with: context: . platforms: ${{ matrix.platform }} - outputs: type=image,name=mauriceboe/trek,push-by-digest=true,name-canonical=true,push=true + outputs: type=image,name=mauriceboe/TREK,push-by-digest=true,name-canonical=true,push=true no-cache: true build-args: | APP_VERSION=${{ needs.version-bump.outputs.version }} @@ -194,16 +183,16 @@ jobs: working-directory: /tmp/digests run: | VERSION="${{ needs.version-bump.outputs.version }}" - mapfile -t digests < <(printf 'mauriceboe/trek@sha256:%s\n' *) + mapfile -t digests < <(printf 'mauriceboe/TREK@sha256:%s\n' *) MAJOR_TAG="$(echo "$VERSION" | cut -d. -f1)" docker buildx imagetools create \ - -t "mauriceboe/trek:latest" \ - -t "mauriceboe/trek:$MAJOR_TAG" \ - -t "mauriceboe/trek:$VERSION" \ + -t "mauriceboe/TREK:latest" \ + -t "mauriceboe/TREK:$MAJOR_TAG" \ + -t "mauriceboe/TREK:$VERSION" \ "${digests[@]}" - name: Inspect manifest - run: docker buildx imagetools inspect mauriceboe/trek:latest + run: docker buildx imagetools inspect mauriceboe/TREK:latest release-helm: runs-on: ubuntu-latest diff --git a/.github/workflows/enforce-target-branch.yml b/.github/workflows/enforce-target-branch.yml index 54e3a0ecb..36f127d81 100644 --- a/.github/workflows/enforce-target-branch.yml +++ b/.github/workflows/enforce-target-branch.yml @@ -6,7 +6,7 @@ on: jobs: check-target: - if: github.repository == 'mauriceboe/TREK' + if: github.repository == 'liketrek/TREK' runs-on: ubuntu-latest permissions: pull-requests: write diff --git a/.github/workflows/publish-plugin-sdk.yml b/.github/workflows/publish-plugin-sdk.yml index 705771351..72ed168df 100644 --- a/.github/workflows/publish-plugin-sdk.yml +++ b/.github/workflows/publish-plugin-sdk.yml @@ -14,7 +14,7 @@ permissions: jobs: publish: - if: github.repository == 'mauriceboe/TREK' + if: github.repository == 'liketrek/TREK' runs-on: ubuntu-latest defaults: run: diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index af22f82a0..5b2cfe08b 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -13,7 +13,7 @@ jobs: scout: # Docker Hub secrets are not exposed to pull requests from forks, so the # Scout login can never succeed there. - if: github.repository == 'mauriceboe/TREK' && github.event.pull_request.head.repo.fork != true + if: github.repository == 'liketrek/TREK' && github.event.pull_request.head.repo.fork != true runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 diff --git a/.github/workflows/wiki.yml b/.github/workflows/wiki.yml index 8c6974520..e36ada88d 100644 --- a/.github/workflows/wiki.yml +++ b/.github/workflows/wiki.yml @@ -17,7 +17,7 @@ concurrency: jobs: deploy: - if: github.repository == 'mauriceboe/TREK' + if: github.repository == 'liketrek/TREK' runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 diff --git a/.gitignore b/.gitignore index fef272b87..a83917a19 100644 --- a/.gitignore +++ b/.gitignore @@ -66,5 +66,3 @@ test-data .run .full-review -# Wiki offline snapshot is baked in at build, not committed (duplicates wiki/) -server/assets/wiki/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 73def1e0d..2c4cf649a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -10,7 +10,7 @@ Thanks for your interest in contributing! Please read these guidelines before op 4. **Target the `dev` branch** — All PRs must be opened against `dev`, not `main`. Exception: PRs that only modify files under `wiki/` may target any branch 5. **Match the existing style** — No reformatting, no linter config changes, no "while I'm here" cleanups 6. **Tests** — Your changes must include tests. The project maintains 80%+ coverage; PRs that drop it will be closed -7. **Branch up to date** — Your branch must be [up to date with `dev`](https://github.com/mauriceboe/TREK/wiki/Development-environment#3-keep-your-fork-up-to-date) before submitting a PR +7. **Branch up to date** — Your branch must be [up to date with `dev`](https://github.com/liketrek/TREK/wiki/Development-environment#3-keep-your-fork-up-to-date) before submitting a PR ## Pull Requests @@ -39,8 +39,8 @@ feat(budget): add CSV export for expenses ## Development Environment -See the [Developer Environment page](https://github.com/mauriceboe/TREK/wiki/Development-environment) for more information on setting up your development environment. +See the [Developer Environment page](https://github.com/liketrek/TREK/wiki/Development-environment) for more information on setting up your development environment. ## More Details -See the [Contributing wiki page](https://github.com/mauriceboe/TREK/wiki/Contributing) for the full tech stack, architecture overview, and detailed guidelines. +See the [Contributing wiki page](https://github.com/liketrek/TREK/wiki/Contributing) for the full tech stack, architecture overview, and detailed guidelines. diff --git a/Dockerfile b/Dockerfile index c05da667a..ba5a9c4c0 100644 --- a/Dockerfile +++ b/Dockerfile @@ -71,6 +71,10 @@ COPY --from=server-builder /app/server/dist ./server/dist # only emits dist, so these must be copied explicitly or the features silently # degrade to empty in the image. COPY --from=server-builder /app/server/assets ./server/assets +# The in-app help pages (/help) read this straight from disk at runtime, so the +# docs always match the version running. Without it, wikiService falls back to +# fetching the GitHub wiki, which tracks main and needs network access. +COPY wiki ./wiki # tsconfig-paths/register reads this at runtime to resolve MCP SDK paths. COPY server/tsconfig.json ./server/ # Encryption-key rotation is run on demand via tsx (a prod dep) straight from the diff --git a/README.md b/README.md index 92ac2e637..2f4fdcf8f 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ A self-hosted, real-time collaborative travel planner — with maps, budgets, pa Demo   -Docker +Docker   Discord   @@ -31,9 +31,9 @@ A self-hosted, real-time collaborative travel planner — with maps, budgets, pa BMAC
License -Latest Release -Docker Pulls -Stars +Latest Release +Docker Pulls +Stars @@ -41,7 +41,7 @@ A self-hosted, real-time collaborative travel planner — with maps, budgets, pa
-TREK — 60-second tour +TREK — 60-second tour
@@ -176,7 +176,7 @@ A self-hosted, real-time collaborative travel planner — with maps, budgets, pa ```bash ENCRYPTION_KEY=$(openssl rand -hex 32) docker run -d -p 3000:3000 \ -e ENCRYPTION_KEY=$ENCRYPTION_KEY \ - -v ./data:/app/data -v ./uploads:/app/uploads mauriceboe/trek + -v ./data:/app/data -v ./uploads:/app/uploads mauriceboe/TREK ``` Open `http://localhost:3000`. On first boot TREK seeds an admin account — if you set `ADMIN_EMAIL`/`ADMIN_PASSWORD` those are used, otherwise the credentials are printed to the container log (`docker logs trek`). @@ -217,7 +217,7 @@ Real-time sync via WebSocket (`ws`). Backend on NestJS 11. State with Zustand. A ```yaml services: app: - image: mauriceboe/trek:latest + image: mauriceboe/TREK:latest container_name: trek read_only: true security_opt: @@ -280,7 +280,7 @@ helm repo update helm install trek trek/trek ``` -See [`charts/README.md`](https://github.com/mauriceboe/TREK/blob/main/charts/README.md) for values. +See [`charts/README.md`](https://github.com/liketrek/TREK/blob/main/charts/README.md) for values.

Install as App (PWA)

@@ -305,9 +305,9 @@ docker compose pull && docker compose up -d **Docker run** — reuse the original volume paths: ```bash -docker pull mauriceboe/trek +docker pull mauriceboe/TREK docker rm -f trek -docker run -d --name trek -p 3000:3000 -v ./data:/app/data -v ./uploads:/app/uploads --restart unless-stopped mauriceboe/trek +docker run -d --name trek -p 3000:3000 -v ./data:/app/data -v ./uploads:/app/uploads --restart unless-stopped mauriceboe/TREK ``` > Not sure which paths you used? `docker inspect trek --format '{{json .Mounts}}'` before removing the container. @@ -331,6 +331,8 @@ The script creates a timestamped DB backup before making changes and prompts for For production, put TREK behind a TLS-terminating reverse proxy. TREK uses WebSockets for real-time sync, so the proxy **must** support WebSocket upgrades on `/ws`. +If you use the MCP addon, the proxy must also pass the `Mcp-Session-Id` header through in both directions on `/mcp` — Nginx and Caddy do this by default, but a proxy that strips it makes every tool call open a new session instead of reusing one. See the [Reverse Proxy wiki page](https://github.com/liketrek/TREK/wiki/Reverse-Proxy) for details. +
Nginx @@ -368,6 +370,19 @@ server { proxy_set_header Host $host; proxy_read_timeout 86400; } + + # Only needed if you use the MCP addon. Responses are Server-Sent Events, + # so buffering must be off or tool results arrive late. + location /mcp { + proxy_pass http://localhost:3000; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_buffering off; + proxy_read_timeout 3600s; + } } ``` @@ -403,6 +418,7 @@ Caddy handles TLS and WebSockets automatically. | `ENCRYPTION_KEY` | At-rest encryption key for stored secrets (API keys, MFA, SMTP, OIDC). Recommended: generate with `openssl rand -hex 32`. If unset, falls back to `data/.jwt_secret` (existing installs) or auto-generates a key (fresh installs). | Auto | | `TZ` | Timezone for logs, reminders and cron jobs (e.g. `Europe/Berlin`) | `UTC` | | `LOG_LEVEL` | `info` = concise user actions, `debug` = verbose details | `info` | +| `TREK_WIKI_DIR` | Where the in-app Help pages (`/help`) read their content from. TREK ships its wiki and serves it from disk, so Help always matches the version you are running — you should not need to set this. Point it at your own directory to serve custom docs. If the path does not exist, Help falls back to fetching the public GitHub wiki (needs outbound network, and tracks the latest release). | bundled `wiki/` | | `DEFAULT_LANGUAGE` | Default language on the login page for users with no saved preference. Browser/OS language is auto-detected first; this is the fallback. Supported: `de`, `en`, `es`, `fr`, `hu`, `nl`, `br`, `cs`, `pl`, `ru`, `zh`, `zh-TW`, `it`, `ar`, `id`, `tr`, `ja`, `ko`, `uk`, `gr` | `en` | | `ALLOWED_ORIGINS` | Comma-separated origins for CORS and email links | same-origin | | `FORCE_HTTPS` | Optional. When `true`: 301-redirects HTTP to HTTPS, sends HSTS, adds CSP `upgrade-insecure-requests`, forces the session cookie `secure` flag. Useful behind a TLS-terminating reverse proxy. Requires `TRUST_PROXY`. | `false` | @@ -430,7 +446,7 @@ Caddy handles TLS and WebSockets automatically. | `DEMO_MODE` | Enable demo mode (hourly data resets) | `false` | | `UNSPLASH_ACCESS_KEY` | Optional Unsplash Access Key for trip-cover and place-image search. Without one, TREK uses Unsplash's unauthenticated endpoint, which some datacenter/VPS IPs are blocked from. Get a free key at [unsplash.com/developers](https://unsplash.com/developers). Overrides any per-admin key set in Admin > Settings (where it can also be configured instead). | — | | `MCP_RATE_LIMIT` | Max MCP API requests per user per minute | `300` | -| `MCP_MAX_SESSION_PER_USER` | Max concurrent MCP sessions per user | `20` | +| `MCP_MAX_SESSION_PER_USER` | Max concurrent MCP sessions per user. At the cap, the least-recently-active session is closed to make room | `20` |
diff --git a/SECURITY.md b/SECURITY.md index e2ce04147..59ba0a367 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -21,6 +21,6 @@ You will receive a response within 48 hours. Once confirmed, a fix will be relea ## Scope -This policy covers the TREK application and its Docker image (`mauriceboe/trek`). +This policy covers the TREK application and its Docker image (`mauriceboe/TREK`). Third-party dependencies are monitored via GitHub Dependabot. diff --git a/ca_profile.xml b/ca_profile.xml index 1c129c1ed..e14a9270f 100644 --- a/ca_profile.xml +++ b/ca_profile.xml @@ -1,9 +1,9 @@ TREK is a self-hosted, real-time collaborative travel planner. Plan trips together with interactive maps, budgets, bookings, packing lists, day-by-day itineraries and file management — every change syncs instantly across everyone in your group. Includes OIDC/SSO, TOTP MFA, dark mode, PWA support, multi-language UI and a modular addon system (Vacay, Atlas, Collab, Budget, Packing, Journey). Maintained by mauriceboe — support and bug reports via GitHub Issues. - https://raw.githubusercontent.com/mauriceboe/TREK/main/docs/trek-icon.png - https://github.com/mauriceboe/TREK - https://github.com/mauriceboe/TREK/issues + https://raw.githubusercontent.com/liketrek/TREK/main/docs/trek-icon.png + https://github.com/liketrek/TREK + https://github.com/liketrek/TREK/issues https://ko-fi.com/mauriceboe Support TREK development diff --git a/charts/trek/templates/configmap.yaml b/charts/trek/templates/configmap.yaml index 5cecc9d86..d6d6e8c86 100644 --- a/charts/trek/templates/configmap.yaml +++ b/charts/trek/templates/configmap.yaml @@ -13,6 +13,9 @@ data: {{- if .Values.env.LOG_LEVEL }} LOG_LEVEL: {{ .Values.env.LOG_LEVEL | quote }} {{- end }} + {{- if .Values.env.TREK_WIKI_DIR }} + TREK_WIKI_DIR: {{ .Values.env.TREK_WIKI_DIR | quote }} + {{- end }} {{- if .Values.env.ALLOWED_ORIGINS }} ALLOWED_ORIGINS: {{ .Values.env.ALLOWED_ORIGINS | quote }} {{- end }} diff --git a/charts/trek/values.yaml b/charts/trek/values.yaml index 150e89851..0f50114f4 100644 --- a/charts/trek/values.yaml +++ b/charts/trek/values.yaml @@ -1,6 +1,6 @@ image: - repository: mauriceboe/trek + repository: liketrek/TREK # tag: latest pullPolicy: IfNotPresent @@ -24,6 +24,12 @@ env: # Timezone for logs, reminders, and cron jobs (e.g. Europe/Berlin). # LOG_LEVEL: "info" # "info" = concise user actions, "debug" = verbose details. + # TREK_WIKI_DIR: "/app/wiki" + # Where the in-app Help pages (/help) read their content from. Leave unset: the + # image ships the wiki at /app/wiki and finds it automatically, so Help matches + # the version you are running. Only set this to serve your own docs from a mounted + # volume. If the path does not exist, Help falls back to fetching the public GitHub + # wiki, which needs egress and tracks the latest release rather than your version. # DEFAULT_LANGUAGE: "en" # Default language on the login page for users with no saved preference. # Browser/OS language is auto-detected first; this is the fallback when no match is found. diff --git a/client/e2e/create-trip.spec.ts b/client/e2e/create-trip.spec.ts index 6c264c927..42a4e5720 100644 --- a/client/e2e/create-trip.spec.ts +++ b/client/e2e/create-trip.spec.ts @@ -1,4 +1,5 @@ import { test, expect } from '@playwright/test' +import { dismissSystemNotices } from './helpers' // Trip lifecycle (core): from the dashboard, open the new-trip modal, name the // trip, submit, and confirm it shows up on the dashboard. Exercises the whole @@ -7,18 +8,23 @@ import { test, expect } from '@playwright/test' test('create a trip and see it on the dashboard', async ({ page }) => { await page.goto('/dashboard') + // The release notice greets a freshly seeded user and its backdrop eats the click below. + await dismissSystemNotices(page) + // The "+ New Trip" card is always rendered in the default (planned) filter. await page.locator('.add-trip-card').click() - // Scope to the shared Modal (.modal-backdrop). Its form has no in-form submit - // button (the primary action lives in the footer), so click it explicitly - // rather than pressing Enter. The Create button is the slate primary button; - // Cancel is the bordered one. - const modal = page.locator('.modal-backdrop') + // Scope to the shared Modal (.trek-modal-backdrop — namespaced so content blockers + // don't hide a generic .modal-backdrop). Its form has no in-form submit button (the + // primary action lives in the footer), so click it explicitly rather than pressing + // Enter. The Create button is the slate primary button; Cancel is the bordered one. + const modal = page.locator('.trek-modal-backdrop') await expect(modal).toBeVisible() + // Target Title by placeholder: the cover-image search inputs sit above it, so + // input[type=text].first() is the photo search box, not the field we want. const title = `E2E Trip ${Date.now()}` - await modal.locator('input[type="text"]').first().fill(title) + await modal.getByPlaceholder('e.g. Summer in Japan').fill(title) await modal.getByRole('button', { name: 'Create New Trip' }).click() await expect(page.getByText(title).first()).toBeVisible({ timeout: 15_000 }) diff --git a/client/e2e/helpers.ts b/client/e2e/helpers.ts new file mode 100644 index 000000000..c91d48152 --- /dev/null +++ b/client/e2e/helpers.ts @@ -0,0 +1,22 @@ +import type { Page } from '@playwright/test' + +/** + * Dismiss the release-notice modal (SystemNoticeHost), which greets a freshly seeded + * user on first load and covers the dashboard — its backdrop swallows clicks aimed at + * anything underneath, `.add-trip-card` included. + * + * The X only appears on the notice's last page, so page through first. Dismissal is + * persisted server-side per user, but each spec gets a fresh DB, so every spec that + * touches the dashboard has to clear it. + */ +export async function dismissSystemNotices(page: Page): Promise { + const next = page.getByRole('button', { name: /next/i }) + for (let i = 0; i < 6 && (await next.isVisible().catch(() => false)); i++) { + if (!(await next.isEnabled())) break + await next.click() + } + + const dismiss = page.getByRole('button', { name: 'Dismiss' }) + if (await dismiss.isVisible().catch(() => false)) await dismiss.click() + await dismiss.waitFor({ state: 'detached' }).catch(() => {}) +} diff --git a/client/e2e/ipad-scroll-1432.spec.ts b/client/e2e/ipad-scroll-1432.spec.ts new file mode 100644 index 000000000..55631b4ce --- /dev/null +++ b/client/e2e/ipad-scroll-1432.spec.ts @@ -0,0 +1,79 @@ +import { test, expect, devices } from '@playwright/test' +import { dismissSystemNotices } from './helpers' + +// Tablet regression guard for #1432 — the places list must scroll under a touch swipe. +// +// A tablet is a coarse-pointer device at a *desktop* viewport width, so the width-based +// "is this mobile" check that 3.2.1 shipped left `draggable` armed on iPad: the swipe +// became an HTML5 drag and raised the drop-to-import overlay instead of scrolling. Drag +// is now gated on `(pointer: coarse)` (useIsTouch), and only a real device context proves +// it — a jsdom unit test cannot express "coarse pointer at 834px". +// +// Needs WebKit (`npx playwright install webkit`, plus libmanette-0.2-0 and libwoff1 on +// Debian/Ubuntu). WebKit is the right engine here, not a nicety: every browser on iPadOS +// is WebKit underneath, which is why the reporter saw this in all three they tried. +test.use({ ...devices['iPad Pro 11'] }) + +test('#1432 iPad: places list is scrollable, not draggable', async ({ page }) => { + await page.goto('/dashboard') + + await dismissSystemNotices(page) + + await page.locator('.add-trip-card').click() + const createBtn = page.getByRole('button', { name: 'Create New Trip' }) + await expect(createBtn).toBeVisible() + const title = `iPad 1432 ${Date.now()}` + await page.getByPlaceholder('e.g. Summer in Japan').fill(title) + await createBtn.click() + + await page.getByText(title).first().click() + await expect(page).toHaveURL(/\/trips\/\d+/) + await expect(page.locator('.leaflet-container')).toBeVisible({ timeout: 20_000 }) + + const tripId = page.url().match(/\/trips\/(\d+)/)![1] + + // Seed enough places for the list to overflow and actually need scrolling. + for (let i = 1; i <= 25; i++) { + const res = await page.request.post(`/api/trips/${tripId}/places`, { + data: { name: `Place ${i}`, lat: 48.85 + i * 0.01, lng: 2.35 + i * 0.01 }, + }) + expect(res.ok(), `seed place ${i}`).toBeTruthy() + } + await page.reload() + await expect(page.locator('.leaflet-container')).toBeVisible({ timeout: 20_000 }) + await expect(page.getByText('Place 1').first()).toBeVisible({ timeout: 20_000 }) + + // The context must really be the one from the bug report: coarse pointer, desktop + // width. If either is wrong, everything below proves nothing. + const env = await page.evaluate(() => ({ + coarse: window.matchMedia('(pointer: coarse)').matches, + width: window.innerWidth, + })) + expect(env.coarse, 'iPad reports a coarse primary pointer').toBe(true) + expect(env.width, 'iPad sits above the 768px "mobile" breakpoint').toBeGreaterThanOrEqual(768) + + // 1. Rows must not be draggable — a draggable row is what swallowed the scroll gesture. + const row = page.locator('div[draggable]').filter({ hasText: 'Place 1' }).first() + await expect(row).toHaveAttribute('draggable', 'false') + + // 2. The list must scroll, and no drop-to-import overlay may appear. + const scroller = page.locator('div[draggable]').first().locator('xpath=ancestor::div[@class="trek-stagger"]') + const before = await scroller.evaluate(el => el.scrollTop) + const box = (await scroller.boundingBox())! + await page.touchscreen.tap(box.x + box.width / 2, box.y + 40) + await scroller.evaluate(el => el.scrollBy(0, 200)) + const after = await scroller.evaluate(el => el.scrollTop) + expect(after, 'places list scrolled').toBeGreaterThan(before) + await expect(page.getByText('Drop to import')).toHaveCount(0) + + // 3. Drag being off means the arrow buttons are the only reorder affordance left — + // they must be visible (they were opacity:0 above 767px). + const arrowOpacity = await page.evaluate(() => { + const el = document.querySelector('.reorder-buttons') + return el ? getComputedStyle(el).opacity : 'absent' + }) + expect(['1', 'absent']).toContain(arrowOpacity) + + // 4. The iPad must still get the desktop two-pane layout — isMobile stayed width-based. + await expect(page.locator('.leaflet-container')).toBeVisible() +}) diff --git a/client/e2e/reorder-arrows.spec.ts b/client/e2e/reorder-arrows.spec.ts new file mode 100644 index 000000000..d0fca0c1a --- /dev/null +++ b/client/e2e/reorder-arrows.spec.ts @@ -0,0 +1,61 @@ +import { test, expect } from '@playwright/test' +import { dismissSystemNotices } from './helpers' + +// The day-plan reorder arrows are hover-revealed on desktop. The rule that did that was +// dead for a long time — it targeted `.place-row .reorder-btns`, neither of which exists +// (the component renders `.reorder-buttons` inside an unclassed row), so the buttons sat +// at opacity:0 with no way to reveal them. +// +// That is not merely "invisible": opacity:0 still hit-tests, so every itinerary row and +// note carried an invisible, fully clickable target that silently reordered the trip. +// These cases pin both halves — hidden means non-interactive, hover means visible. +test('desktop: reorder arrows are hidden-and-inert until the row is hovered', async ({ page }) => { + await page.goto('/dashboard') + await dismissSystemNotices(page) + + await page.locator('.add-trip-card').click() + const modal = page.locator('.trek-modal-backdrop') + await expect(modal).toBeVisible() + const title = `Reorder ${Date.now()}` + await modal.getByPlaceholder('e.g. Summer in Japan').fill(title) + await modal.getByRole('button', { name: 'Create New Trip' }).click() + + await page.getByText(title).first().click() + await expect(page).toHaveURL(/\/trips\/\d+/) + await expect(page.locator('.leaflet-container')).toBeVisible({ timeout: 20_000 }) + + // Two places on day 1, so the day plan renders rows carrying reorder arrows. + const tripId = page.url().match(/\/trips\/(\d+)/)![1] + const daysRes = await (await page.request.get(`/api/trips/${tripId}/days`)).json() + const dayId = (daysRes.days ?? daysRes)[0].id + for (const name of ['Alpha', 'Beta']) { + const res = await page.request.post(`/api/trips/${tripId}/places`, { + data: { name, lat: 48.85, lng: 2.35 }, + }) + const body = await res.json() + await page.request.post(`/api/trips/${tripId}/days/${dayId}/assignments`, { + data: { place_id: body.place?.id ?? body.id }, + }) + } + await page.reload() + await expect(page.locator('.leaflet-container')).toBeVisible({ timeout: 20_000 }) + + const row = page.locator('.dp-row').filter({ hasText: 'Alpha' }).first() + await expect(row).toBeVisible({ timeout: 20_000 }) + const arrows = row.locator('.reorder-buttons') + + // Unhovered: invisible AND inert — a click there must not land on the button. + const idle = await arrows.evaluate(el => { + const cs = getComputedStyle(el) + const r = el.getBoundingClientRect() + const hit = document.elementFromPoint(r.x + r.width / 2, r.y + r.height / 2) + return { opacity: cs.opacity, hitsArrow: !!hit?.closest('.reorder-buttons') } + }) + expect(idle.opacity, 'arrows hidden until hover').toBe('0') + expect(idle.hitsArrow, 'hidden arrows must not swallow clicks').toBe(false) + + // Hovered: revealed and clickable. + await row.hover() + await expect(arrows).toHaveCSS('opacity', '1') + await expect(arrows).toHaveCSS('pointer-events', 'auto') +}) diff --git a/client/e2e/screenshots/auth.shot.ts b/client/e2e/screenshots/auth.shot.ts new file mode 100644 index 000000000..528d017e3 --- /dev/null +++ b/client/e2e/screenshots/auth.shot.ts @@ -0,0 +1,26 @@ +import { test, expect } from './shot' + +/** + * Unauthenticated surfaces. `storageState: undefined` drops the admin session + * this project otherwise inherits, so these render as a logged-out visitor sees + * them — which is the entire point of the login and registration pages. + */ +test.use({ storageState: undefined }) + +test('login page', async ({ page, shot }) => { + await page.goto('/login') + await expect(page.locator('input[type="email"]')).toBeVisible() + await shot.page_('Login') +}) + +test('registration page', async ({ page, shot }) => { + await page.goto('/register') + await page.waitForTimeout(500) + await shot.page_('Registration') +}) + +test('forgot password', async ({ page, shot }) => { + await page.goto('/forgot-password') + await page.waitForTimeout(500) + await shot.page_('PasswordReset') +}) diff --git a/client/e2e/screenshots/collab.shot.ts b/client/e2e/screenshots/collab.shot.ts new file mode 100644 index 000000000..7d30c685c --- /dev/null +++ b/client/e2e/screenshots/collab.shot.ts @@ -0,0 +1,69 @@ +import { test, clearNotices, expect } from './shot' +import type { Page, Locator } from '@playwright/test' +import { readFileSync } from 'node:fs' +import path from 'node:path' + +/** + * Collab surfaces, one capture each. + * + * Until now a single Collab.png illustrated four different wiki pages — chat, + * notes, polls and the What's Next widget — so at most one of them showed the + * feature its page described. + * + * The Collab view is NOT tabbed: CollabPanel renders chat in a fixed 380px left + * column and the other panels beside it, all visible at once (CollabPanel.tsx:94). + * So each capture targets its own card element rather than clicking a tab. + */ + +const seed = JSON.parse( + readFileSync(path.join(process.cwd(), 'e2e', '.tmp', 'seed.json'), 'utf8'), +) as { tripId: number } + +/** + * The panel card containing a given piece of seeded content — see cardClass in + * CollabPanel.tsx:20. + * + * Matching on content rather than the panel heading is deliberate: the headings + * render uppercase through CSS while the DOM text is "Notes" / "Polls", and + * those same words also appear in the mobile tab bar, so a heading match is both + * wrong-cased and ambiguous. + */ +function card(page: Page, contains: string): Locator { + return page + .locator('div.bg-surface-card.rounded-2xl') + .filter({ hasText: contains }) + .last() +} + +test.beforeEach(async ({ page }) => { + await page.goto(`/trips/${seed.tripId}`) + await clearNotices(page) + await page.getByRole('button', { name: 'Collab', exact: true }).first().click() + await page.waitForTimeout(1200) +}) + +test('collab chat', async ({ page, shot }) => { + // Seeded as three different people; a single-voice log would misrepresent it. + // The chat auto-scrolls to the newest message, so assert on the last line of + // the seeded conversation rather than the first — the first is off-screen. + await expect(page.getByText('kaiseki', { exact: false }).first()).toBeVisible() + await shot.element('CollabChat', card(page, 'kaiseki')) +}) + +test('collab notes', async ({ page, shot }) => { + await expect(page.getByText('Rail passes', { exact: false })).toBeVisible() + await shot.element('CollabNotes', card(page, 'Rail passes')) +}) + +test('collab polls', async ({ page, shot }) => { + await expect(page.getByText('free for Nara', { exact: false })).toBeVisible() + await shot.element('CollabPolls', card(page, 'free for Nara')) +}) + +test("what's next widget", async ({ page, shot }) => { + await shot.element('WhatsNext', card(page, "What's Next")) +}) + +test('collab overview', async ({ page, shot }) => { + await shot.page_('Collab') +}) diff --git a/client/e2e/screenshots/detail.shot.ts b/client/e2e/screenshots/detail.shot.ts new file mode 100644 index 000000000..fa09d7a26 --- /dev/null +++ b/client/e2e/screenshots/detail.shot.ts @@ -0,0 +1,88 @@ +import { test, clearNotices, expect } from './shot' +import { readFileSync } from 'node:fs' +import path from 'node:path' + +/** + * Detail pages and the surfaces that need a couple of clicks to reach. + * + * Each capture asserts something specific to the surface before shooting, so a + * navigation that quietly lands on a fallback (or an addon that is off) fails + * the run instead of producing a screenshot of the wrong screen. + */ + +const seed = JSON.parse( + readFileSync(path.join(process.cwd(), 'e2e', '.tmp', 'seed.json'), 'utf8'), +) as { tripId: number; collectionId?: number; journeyId?: number } + +test('collection detail', async ({ page, shot }) => { + test.skip(!seed.collectionId, 'collections addon unavailable during seed') + await page.goto(`/collections/${seed.collectionId}`) + await clearNotices(page) + await shot.page_('CollectionDetail') +}) + +test('journey detail', async ({ page, shot }) => { + test.skip(!seed.journeyId, 'journey addon unavailable during seed') + await page.goto(`/journey/${seed.journeyId}`) + await clearNotices(page) + await shot.page_('JourneyDetail') +}) + +test('mcp access — admin', async ({ page, shot }) => { + await page.goto('/admin') + await clearNotices(page) + await page.getByRole('button', { name: 'MCP Access', exact: true }).first().click() + await page.waitForTimeout(700) + await shot.page_('MCPAccess') +}) + +test('two-factor setup', async ({ page, shot }) => { + await page.goto('/settings') + await clearNotices(page) + await page.getByRole('button', { name: 'Account', exact: true }).first().click() + await page.waitForTimeout(600) + // The enrolment flow is behind a button whose label varies with state; match + // loosely and fall back to capturing the tab itself. + const enable = page.getByRole('button', { name: /two-factor|2fa|authenticator/i }).first() + if (await enable.isVisible().catch(() => false)) { + await enable.click() + await page.waitForTimeout(900) + } + await shot.page_('2FA') +}) + +/** + * Settle-up. + * + * WARNING for anyone extending this file: the "Settle up" button in the Costs + * toolbar is not a view — it RECORDS the settling transfers. An earlier version + * of this test clicked it, which zeroed every balance and left the capture + * showing "Everyone's square". Because all screenshot specs share one database + * and this file sorts before planner.shot.ts, it also poisoned Costs.png in the + * same run. + * + * Screenshot specs must not mutate state. Capture the "Add payment" dialog + * instead — same surface, no side effect — and close it again. + */ +test('costs — record a settle-up payment', async ({ page, shot }) => { + await page.goto(`/trips/${seed.tripId}`) + await clearNotices(page) + await page.getByRole('button', { name: 'Costs', exact: true }).first().click() + await page.waitForTimeout(800) + + const addPayment = page.getByRole('button', { name: /add payment/i }).first() + test.skip(!(await addPayment.isVisible().catch(() => false)), 'no add-payment entry point rendered') + await addPayment.click() + await page.waitForTimeout(700) + + const modal = page.locator('.trek-modal-backdrop > div').first() + await expect(modal).toBeVisible() + await shot.element('CostsSettleUp', modal) +}) + +test('trip files', async ({ page, shot }) => { + await page.goto(`/trips/${seed.tripId}/files`) + await clearNotices(page) + await expect(page).toHaveURL(/files/) + await shot.page_('Documents') +}) diff --git a/client/e2e/screenshots/dialogs.shot.ts b/client/e2e/screenshots/dialogs.shot.ts new file mode 100644 index 000000000..865bd9676 --- /dev/null +++ b/client/e2e/screenshots/dialogs.shot.ts @@ -0,0 +1,42 @@ +import { test, clearNotices, expect } from './shot' +import { readFileSync } from 'node:fs' +import path from 'node:path' + +/** + * Modals and dialogs. + * + * Captured as element screenshots (not full page) so the wiki gets the dialog + * itself rather than a dimmed backdrop with a small box in the middle. Each one + * asserts the dialog is actually open first — a missed click would otherwise + * silently produce a screenshot of the page behind it. + */ + +const seed = JSON.parse( + readFileSync(path.join(process.cwd(), 'e2e', '.tmp', 'seed.json'), 'utf8'), +) as { tripId: number } + +/** + * The shared Modal (client/src/components/shared/Modal.tsx) sets neither + * role="dialog" nor aria-modal, so there is no accessible role to query — the + * backdrop class is the only stable hook. Target its child, which is the panel + * itself, so the capture excludes the dimmed backdrop. + */ +function dialog(page: import('@playwright/test').Page) { + return page.locator('.trek-modal-backdrop > div').first() +} + +test('create trip modal — with the new currency field', async ({ page, shot }) => { + await page.goto('/dashboard') + await clearNotices(page) + await page.getByRole('button', { name: /new trip/i }).first().click() + await expect(dialog(page)).toBeVisible() + await shot.element('TripCreate', dialog(page)) +}) + +test('share dialog', async ({ page, shot }) => { + await page.goto(`/trips/${seed.tripId}`) + await clearNotices(page) + await page.getByRole('button', { name: /share/i }).first().click() + await expect(dialog(page)).toBeVisible() + await shot.element('Share', dialog(page)) +}) diff --git a/client/e2e/screenshots/pages.shot.ts b/client/e2e/screenshots/pages.shot.ts new file mode 100644 index 000000000..52d096d05 --- /dev/null +++ b/client/e2e/screenshots/pages.shot.ts @@ -0,0 +1,67 @@ +import { test, clearNotices } from './shot' +import { readFileSync } from 'node:fs' +import path from 'node:path' + +/** + * Top-level navigable surfaces. One capture per route; anything that needs a + * dialog opened or a tab clicked lives in its own spec so a failure there + * cannot take these down with it. + * + * Names are the target filenames in wiki/assets/ — see docs/screenshot-map.md + * for which wiki page consumes which file. + */ + +const seed = JSON.parse( + readFileSync(path.join(process.cwd(), 'e2e', '.tmp', 'seed.json'), 'utf8'), +) as { tripId: number; collectionId?: number; journeyId?: number } + +test.beforeEach(async ({ page }) => { + await page.goto('/dashboard') + await clearNotices(page) +}) + +test('dashboard', async ({ page, shot }) => { + await page.goto('/dashboard') + await clearNotices(page) + await shot.page_('DashboardWidgets') +}) + +test('trip planner', async ({ page, shot }) => { + await page.goto(`/trips/${seed.tripId}`) + await shot.page_('TripPlanner') +}) + +test('atlas', async ({ page, shot }) => { + await page.goto('/atlas') + await shot.page_('Atlas') +}) + +test('vacay', async ({ page, shot }) => { + await page.goto('/vacay') + await shot.page_('Vacay') +}) + +test('collections', async ({ page, shot }) => { + await page.goto('/collections') + await shot.page_('Collections') +}) + +test('journey', async ({ page, shot }) => { + await page.goto('/journey') + await shot.page_('Journey') +}) + +test('notifications inbox', async ({ page, shot }) => { + await page.goto('/notifications') + await shot.page_('NotificationsInbox') +}) + +test('in-app help', async ({ page, shot }) => { + await page.goto('/help') + await shot.page_('HelpInApp') +}) + +test('files', async ({ page, shot }) => { + await page.goto(`/trips/${seed.tripId}/files`) + await shot.page_('Files') +}) diff --git a/client/e2e/screenshots/planner.shot.ts b/client/e2e/screenshots/planner.shot.ts new file mode 100644 index 000000000..b7507b4ab --- /dev/null +++ b/client/e2e/screenshots/planner.shot.ts @@ -0,0 +1,47 @@ +import { test, clearNotices } from './shot' +import { readFileSync } from 'node:fs' +import path from 'node:path' + +/** + * Trip-planner tabs and dialogs. + * + * Tabs are reached by their visible label rather than a test id, deliberately: + * if a label is renamed (as Budget → Costs was in 3.3.0) this run fails loudly + * instead of silently capturing the wrong panel — which is exactly how the + * current wiki ended up with screenshots the text contradicts. + */ + +const seed = JSON.parse( + readFileSync(path.join(process.cwd(), 'e2e', '.tmp', 'seed.json'), 'utf8'), +) as { tripId: number } + +test.beforeEach(async ({ page }) => { + await page.goto(`/trips/${seed.tripId}`) + await clearNotices(page) +}) + +async function openTab(page: import('@playwright/test').Page, label: string) { + await page.getByRole('button', { name: label, exact: true }).first().click() + await page.waitForTimeout(700) +} + +test('costs panel', async ({ page, shot }) => { + await openTab(page, 'Costs') + await shot.page_('Costs') +}) + +test('lists — packing', async ({ page, shot }) => { + await openTab(page, 'Lists') + await shot.page_('PackingList') +}) + +test('transports', async ({ page, shot }) => { + await openTab(page, 'Transports') + await shot.page_('Transports') +}) + +test('bookings', async ({ page, shot }) => { + await openTab(page, 'Book') + await shot.page_('Bookings') +}) + diff --git a/client/e2e/screenshots/promote.mjs b/client/e2e/screenshots/promote.mjs new file mode 100644 index 000000000..d34b7c991 --- /dev/null +++ b/client/e2e/screenshots/promote.mjs @@ -0,0 +1,59 @@ +// Moves captured screenshots from the staging directory into wiki/assets/, +// downscaling and re-encoding on the way. +// +// Captures are taken at 1440px CSS width with deviceScaleFactor 2, i.e. 2880px +// of raw pixels. The wiki renders images at roughly 800–1000px, so shipping +// 2880px costs ~10x the bytes for detail nobody sees — that is how the existing +// assets reached 26 MB (one GIF alone is 9.1 MB). 1600px keeps the image sharp +// on HiDPI displays at the size it is actually shown. +// +// Usage: node e2e/screenshots/promote.mjs [--dry] +import sharp from 'sharp' +import { readdirSync, mkdirSync, statSync } from 'node:fs' +import path from 'node:path' + +const SRC = path.join(process.cwd(), 'e2e', '.tmp', 'shots') +const DEST = path.join(process.cwd(), '..', 'wiki', 'assets') +const MAX_WIDTH = 1600 +const dry = process.argv.includes('--dry') + +mkdirSync(DEST, { recursive: true }) + +const files = readdirSync(SRC).filter(f => f.endsWith('.png')) +if (!files.length) { + console.error(`No screenshots in ${SRC} — run \`npm run shots\` first.`) + process.exit(1) +} + +let before = 0 +let after = 0 + +for (const file of files.sort()) { + const src = path.join(SRC, file) + const dest = path.join(DEST, file) + const srcBytes = statSync(src).size + before += srcBytes + + const img = sharp(src) + const { width } = await img.metadata() + + const pipeline = sharp(src) + .resize({ width: Math.min(width ?? MAX_WIDTH, MAX_WIDTH), withoutEnlargement: true }) + .png({ compressionLevel: 9, effort: 10 }) + + const buf = await pipeline.toBuffer() + after += buf.length + + const pct = Math.round((1 - buf.length / srcBytes) * 100) + console.log( + `${dry ? '[dry] ' : ''}${file.padEnd(28)} ${kb(srcBytes).padStart(8)} → ${kb(buf.length).padStart(8)} (-${pct}%)`, + ) + if (!dry) await sharp(buf).toFile(dest) +} + +console.log(`\n${files.length} files: ${kb(before)} → ${kb(after)} (-${Math.round((1 - after / before) * 100)}%)`) +if (dry) console.log('Dry run — nothing written. Drop --dry to promote into wiki/assets/.') + +function kb(bytes) { + return bytes > 1024 * 1024 ? `${(bytes / 1024 / 1024).toFixed(1)} MB` : `${Math.round(bytes / 1024)} KB` +} diff --git a/client/e2e/screenshots/seed.setup.ts b/client/e2e/screenshots/seed.setup.ts new file mode 100644 index 000000000..ef092ee54 --- /dev/null +++ b/client/e2e/screenshots/seed.setup.ts @@ -0,0 +1,37 @@ +import { test as setup, expect } from '@playwright/test' +import { writeFileSync, mkdirSync } from 'node:fs' +import path from 'node:path' +import { seedDemoData } from './seed' + +/** + * Populates the throwaway E2E database with the demo trip before any screenshot + * runs. Its own Playwright project so it executes exactly once, after `setup` + * (which produces the authenticated storageState) and before `screenshots`. + * + * The resulting ids are written to disk because Playwright projects do not + * share memory — the capture specs read them back. + */ +setup('seed the demo trip', async ({ page, playwright }) => { + // page.request carries the storageState cookie, so this is authenticated as + // the admin. The factory hands the seeder throwaway contexts for the other + // members — see the comment in seed.ts on why they must not share one. + const result = await seedDemoData(page.request, token => + playwright.request.newContext({ + baseURL: 'http://localhost:5173', + // MUST be explicit: newContext otherwise picks up the project's + // storageState, i.e. the admin's trek_session cookie — and the server + // reads the cookie BEFORE the Authorization header + // (server/src/middleware/auth.ts:9), so every "member" write would be + // recorded as the admin while still returning 200. + storageState: undefined, + extraHTTPHeaders: token ? { Authorization: `Bearer ${token}` } : {}, + }), + ) + + expect(result.tripId, 'trip was created').toBeTruthy() + expect(result.placeIds.length, 'places were created').toBeGreaterThan(0) + + const dir = path.join(process.cwd(), 'e2e', '.tmp') + mkdirSync(dir, { recursive: true }) + writeFileSync(path.join(dir, 'seed.json'), JSON.stringify(result, null, 2)) +}) diff --git a/client/e2e/screenshots/seed.ts b/client/e2e/screenshots/seed.ts new file mode 100644 index 000000000..898b73193 --- /dev/null +++ b/client/e2e/screenshots/seed.ts @@ -0,0 +1,347 @@ +import path from 'node:path' +import type { APIRequestContext } from '@playwright/test' + +/** + * Demo data for the documentation screenshots. + * + * Seeded over the REST API (not the DB) so it exercises the same paths a real + * user would and stays honest about validation. The session cookie comes from + * the storageState that auth.setup.ts writes, so `page.request` is already + * authenticated as the seeded admin. + * + * Design notes that matter for the screenshots: + * - The trip is in **JPY**, deliberately. A EUR trip hides the entire v3.4.0 + * currency rework (per-trip currency, frozen FX rates, foreign-currency + * settle-up) — the reader would see nothing new. + * - Two extra members exist so splits, avatars and sharing tiers render with + * real names instead of a lonely single-user state. + * - Dates sit ~2 months out so "upcoming" surfaces (What's Next, reservations) + * have something to show. + */ + +const TRIP = { + title: 'Autumn in Japan', + description: 'Two weeks chasing momiji season from Tokyo down to Kyoto.', + start_date: '2026-09-12', + end_date: '2026-09-21', + currency: 'JPY', + reminder_days: 3, +} + +const MEMBERS = [ + { username: 'mira', email: 'mira@example.com', password: 'DemoSeed12345!', role: 'user' }, + { username: 'jonas', email: 'jonas@example.com', password: 'DemoSeed12345!', role: 'user' }, +] + +/** Real coordinates — the map surfaces are a big part of what we're capturing. */ +const PLACES = [ + { name: 'Senso-ji Temple', lat: 35.7148, lng: 139.7967, address: '2-3-1 Asakusa, Taito City, Tokyo', + description: "Tokyo's oldest temple, approached through the Nakamise shopping street.", + notes: 'Go before 08:00 — the gate is empty and the light is better.', + duration_minutes: 90, price: 0, currency: 'JPY', day: 0 }, + { name: 'teamLab Planets', lat: 35.6486, lng: 139.7900, address: '6-1-16 Toyosu, Koto City, Tokyo', + description: 'Immersive digital art museum you walk through barefoot.', + notes: 'Timed entry — book at least a week ahead.', + duration_minutes: 120, price: 3800, currency: 'JPY', day: 0 }, + { name: 'Shibuya Crossing', lat: 35.6595, lng: 139.7005, address: 'Shibuya City, Tokyo', + description: 'The scramble. Best viewed from the Shibuya Sky observation deck.', + duration_minutes: 45, price: 0, currency: 'JPY', day: 1 }, + { name: 'Meiji Jingu', lat: 35.6764, lng: 139.6993, address: '1-1 Yoyogikamizonocho, Shibuya City, Tokyo', + description: 'Forest shrine in the middle of the city.', + duration_minutes: 75, price: 0, currency: 'JPY', day: 1 }, + { name: 'Fushimi Inari Taisha', lat: 34.9671, lng: 135.7727, address: '68 Fukakusa Yabunouchicho, Fushimi Ward, Kyoto', + description: 'Thousands of vermilion torii gates climbing Mount Inari.', + notes: 'The crowds thin out after the first 20 minutes of climbing.', + duration_minutes: 150, price: 0, currency: 'JPY', day: 4 }, + { name: 'Arashiyama Bamboo Grove', lat: 35.0170, lng: 135.6716, address: 'Ukyo Ward, Kyoto', + description: 'Bamboo path leading to the Okochi Sanso villa gardens.', + duration_minutes: 60, price: 0, currency: 'JPY', day: 5 }, + { name: 'Nishiki Market', lat: 35.0050, lng: 135.7649, address: 'Nakagyo Ward, Kyoto', + description: "Five covered blocks of food stalls — 'Kyoto's kitchen'.", + notes: 'Come hungry. Try the tamagoyaki.', + duration_minutes: 90, price: 2500, currency: 'JPY', day: 5 }, +] + +const EXPENSES = [ + { name: 'Flights FRA → HND', category: 'transport', total_price: 890, currency: 'EUR', + expense_date: '2026-09-12', note: 'Booked with miles, taxes only.' }, + { name: 'Ryokan in Hakone', category: 'accommodation', total_price: 48000, currency: 'JPY', + expense_date: '2026-09-15', note: '2 nights, kaiseki dinner included.' }, + { name: 'JR Pass (14 days)', category: 'transport', total_price: 80000, currency: 'JPY', + expense_date: '2026-09-12', note: 'Green car, activated on arrival.' }, + { name: 'teamLab Planets tickets', category: 'activities', total_price: 11400, currency: 'JPY', + expense_date: '2026-09-13' }, + { name: 'Dinner at Nishiki', category: 'food', total_price: 7200, currency: 'JPY', + expense_date: '2026-09-17' }, +] + +const PACKING = [ + { category: 'Documents', items: ['Passport', 'JR Pass voucher', 'Travel insurance'] }, + { category: 'Clothing', items: ['Rain jacket', 'Walking shoes', 'Light layers'] }, + { category: 'Electronics', items: ['Type-A adapter', 'Power bank', 'Camera'] }, +] + +const TODOS = [ + { name: 'Book teamLab Planets slot', category: 'Before departure', due_date: '2026-08-15', priority: 2 }, + { name: 'Activate JR Pass', category: 'On arrival', due_date: '2026-09-12', priority: 1 }, + { name: 'Reserve ryokan dinner', category: 'Before departure', due_date: '2026-08-20' }, +] + +export interface SeedResult { + tripId: number + memberIds: number[] + dayIds: number[] + placeIds: number[] + collectionId?: number + journeyId?: number +} + +/** Throws with the response body on failure — a silent 4xx here would produce + * a screenshot of an empty screen, which is worse than a loud crash. */ +async function call(api: APIRequestContext, method: 'post' | 'put' | 'get' | 'patch', + path: string, body?: unknown): Promise { + const res = await api[method](path, body === undefined ? {} : { data: body }) + if (!res.ok()) { + throw new Error(`${method.toUpperCase()} ${path} → ${res.status()}\n${await res.text()}`) + } + return (await res.json()) as T +} + +export type ContextFactory = (token?: string) => Promise + +export async function seedDemoData( + api: APIRequestContext, + newContext?: ContextFactory, +): Promise { + // 1. Addons first — the Collections and Journey guards run ahead of auth, so + // every later call to those modules 403s until these are flipped. + for (const id of ['collections', 'journey', 'packing', 'budget', 'atlas', 'vacay', 'mcp', 'documents', 'collab']) { + await call(api, 'put', `/api/admin/addons/${id}`, { enabled: true }) + } + await call(api, 'put', '/api/admin/bag-tracking', { enabled: true }).catch(() => {}) + + // 1b. Units, pinned explicitly so the screenshots don't silently change meaning + // when a default does. They match the current defaults (ba3733da made + // celsius/metric/24h consistent across the store and the settings UI) — + // stating them here keeps the captures reproducible either way. + await call(api, 'post', '/api/settings/bulk', { + settings: { temperature_unit: 'celsius', distance_unit: 'metric' }, + }) + + // 2. Extra members. Ignore 409 so a re-run against a warm DB still works. + const memberIds: number[] = [] + for (const m of MEMBERS) { + const res = await api.post('/api/admin/users', { data: m }) + if (res.ok()) { + const { user } = (await res.json()) as { user: { id: number } } + memberIds.push(user.id) + } else if (res.status() !== 409) { + throw new Error(`create user ${m.username} → ${res.status()}\n${await res.text()}`) + } + } + + // 3. The trip, in JPY. + const { trip } = await call<{ trip: { id: number } }>(api, 'post', '/api/trips', TRIP) + const tripId = trip.id + + for (const m of MEMBERS) { + await call(api, 'post', `/api/trips/${tripId}/members`, { identifier: m.email }).catch(() => {}) + } + + // 4. Days are auto-generated by trip creation — read them back for assignment. + const days = await call | { days: Array<{ id: number }> }>( + api, 'get', `/api/trips/${tripId}/days`) + const dayIds = (Array.isArray(days) ? days : days.days).map(d => d.id) + + // 5. Places, then pin each onto its day. + const placeIds: number[] = [] + for (const p of PLACES) { + const { day, ...payload } = p + const { place } = await call<{ place: { id: number } }>( + api, 'post', `/api/trips/${tripId}/places`, payload) + placeIds.push(place.id) + const dayId = dayIds[day] + if (dayId) { + await call(api, 'post', `/api/trips/${tripId}/days/${dayId}/assignments`, + { place_id: place.id }).catch(() => {}) + } + } + + // 6. A day note, so the itinerary shows more than places. + if (dayIds[0]) { + await call(api, 'post', `/api/trips/${tripId}/days/${dayIds[0]}/notes`, { + text: 'Pick up the JR Pass at the airport counter before taking the train in.', + time: '08:15', icon: 'train', + }).catch(() => {}) + } + + // 7. Costs. Split across everyone so the settle-up view has real balances. + // NOTE: never send exchange_rate — the server freezes the FX rate itself, + // and a hand-supplied one fights the settlement maths. + const allMembers = [1, ...memberIds] + for (const e of EXPENSES) { + await call(api, 'post', `/api/trips/${tripId}/budget`, { + ...e, + payers: [{ user_id: 1, amount: e.total_price }], + member_ids: allMembers, + }).catch(() => {}) + } + + // A foreign-currency settle-up payment — the v3.4.0 feature worth showing. + if (memberIds[0]) { + await call(api, 'post', `/api/trips/${tripId}/budget/settlements`, { + from_user_id: memberIds[0], to_user_id: 1, amount: 120, currency: 'EUR', + }).catch(() => {}) + } + + // 8. Packing — category is free text on the item, there is no category resource. + for (const group of PACKING) { + for (const name of group.items) { + await call(api, 'post', `/api/trips/${tripId}/packing`, { + name, category: group.category, visibility: 'common', + }).catch(() => {}) + } + } + + for (const t of TODOS) { + await call(api, 'post', `/api/trips/${tripId}/todo`, t).catch(() => {}) + } + + // 9. A multi-leg flight. Coordinates are mandatory — endpoints without them + // are silently dropped by the server, leaving a booking with no route. + await call(api, 'post', `/api/trips/${tripId}/reservations`, { + title: 'LH716 FRA → HND', + type: 'flight', + reservation_time: '2026-09-12T13:05:00', + reservation_end_time: '2026-09-13T08:25:00', + confirmation_number: 'X7K2QP', + status: 'confirmed', + location: 'Frankfurt Airport', + metadata: { airline: 'Lufthansa', flight_number: 'LH716', + departure_airport: 'FRA', arrival_airport: 'HND' }, + endpoints: [ + { role: 'from', sequence: 0, name: 'Frankfurt Airport', code: 'FRA', + lat: 50.0379, lng: 8.5622, timezone: 'Europe/Berlin', + local_date: '2026-09-12', local_time: '13:05' }, + { role: 'to', sequence: 1, name: 'Tokyo Haneda', code: 'HND', + lat: 35.5494, lng: 139.7798, timezone: 'Asia/Tokyo', + local_date: '2026-09-13', local_time: '08:25' }, + ], + }).catch(() => {}) + + // 10. A collection, populated from the trip's own places. + let collectionId: number | undefined + try { + const created = await call<{ id: number } | { collection: { id: number } }>( + api, 'post', '/api/addons/collections', + { name: 'Kyoto shortlist', description: 'Places we want to reach on the second week.', + color: '#ef4444', icon: 'MapPin' }) + collectionId = 'id' in created ? created.id : created.collection.id + for (const placeId of placeIds.slice(4)) { + await call(api, 'post', '/api/addons/collections/places/from-trip', { + collection_id: collectionId, source_trip_id: tripId, source_place_id: placeId, force: true, + }).catch(() => {}) + } + } catch { /* collections addon unavailable — screenshots for it will be skipped */ } + + // 11. Journey. Entries are generated server-side from the trip, then filled in. + let journeyId: number | undefined + try { + const j = await call<{ id: number } | { journey: { id: number } }>( + api, 'post', '/api/journeys', + { title: 'Autumn in Japan', subtitle: 'Momiji season, Tokyo to Kyoto', trip_ids: [tripId] }) + journeyId = 'id' in j ? j.id : j.journey.id + } catch { /* journey addon unavailable */ } + + // 11b. Collab: chat, notes and polls. + // + // Chat is only convincing with more than one voice, and every collab + // write is attributed to the acting user — so messages and votes are + // posted as the members themselves, via their own bearer tokens, not as + // the admin. A single-speaker chat log would misrepresent the feature. + // Each member gets its OWN request context. Logging in through the shared + // one would set the trek_session cookie on it, and extractToken() + // (server/src/middleware/auth.ts:9) reads the cookie BEFORE the + // Authorization header — so every later write, including the admin's, + // would silently be attributed to whoever logged in last. + const members: Record = {} + for (const m of MEMBERS) { + if (!newContext) break + const anon = await newContext() + const res = await anon.post('/api/auth/login', { data: { email: m.email, password: m.password } }) + if (!res.ok()) { await anon.dispose(); continue } + const { token } = (await res.json()) as { token?: string } + await anon.dispose() + if (token) members[m.username] = await newContext(token) + } + /** The member's own context, or the admin's as a visible fallback. */ + const as = (username: string): APIRequestContext => members[username] ?? api + + const collab = `/api/trips/${tripId}/collab` + + for (const n of [ + { title: 'Rail passes', category: 'Transport', color: '#3b82f6', + content: 'The 14-day JR Pass covers the Tokyo–Kyoto legs. Activate it at the airport counter on arrival, not before.' }, + { title: 'Ryokan etiquette', category: 'Accommodation', color: '#ef4444', + content: 'Shoes off at the entrance, yukata for dinner. Dinner is served at 18:30 sharp — being late is genuinely rude.' }, + { title: 'Rainy-day alternatives', category: 'Ideas', color: '#22c55e', + content: 'teamLab Planets, the Kyoto Railway Museum and Nishiki Market all work in bad weather.' }, + ]) { + await api.post(`${collab}/notes`, { data: n }).catch(() => {}) + } + + const pollRes = await api.post(`${collab}/polls`, { + data: { + question: 'Which day should we keep free for Nara?', + options: ['Wed, Sep 16', 'Thu, Sep 17', 'Sat, Sep 19'], + multiple: false, + }, + }) + if (pollRes.ok()) { + const { poll } = (await pollRes.json()) as { poll: { id: number | string } } + await api.post(`${collab}/polls/${poll.id}/vote`, { data: { option_index: 1 } }).catch(() => {}) + await as('mira').post(`${collab}/polls/${poll.id}/vote`, { data: { option_index: 1 } }).catch(() => {}) + await as('jonas').post(`${collab}/polls/${poll.id}/vote`, { data: { option_index: 2 } }).catch(() => {}) + } + await api.post(`${collab}/polls`, { + data: { question: 'Ryokan or city hotel in Hakone?', options: ['Ryokan with onsen', 'City hotel'], multiple: false }, + }).catch(() => {}) + + const conversation: Array<[string, string]> = [ + ['admin', 'Flights are booked — we land at Haneda 08:25 on the 13th.'], + ['mira', 'Nice. Should we go straight to the hotel or drop bags and head out?'], + ['jonas', 'Drop bags. I want to be at Senso-ji before the crowds.'], + ['admin', "Agreed. I've put it on day 1 with a note to go before 08:00."], + ['mira', 'Booked the teamLab slot for the 13th, 14:00. Tickets are in the Files tab.'], + ['jonas', 'Do we need to reserve the ryokan dinner separately?'], + ['admin', "It's included — kaiseki, 18:30. Added it to the to-dos so we don't forget to confirm."], + ] + for (const [who, text] of conversation) { + const ctx = who === 'admin' ? api : as(who) + await ctx.post(`${collab}/messages`, { data: { text } }).catch(() => {}) + } + + for (const ctx of Object.values(members)) await ctx.dispose() + + // 12. Plugins, installed from the community registry. + // + // Registry install is the ONLY path that produces a representative + // screenshot. Dev-link and sideload both stamp the plugin card with a + // badge ("Dev-Link" / "Sideloaded", AdminPluginsPanel.tsx:307,361) that no + // ordinary install shows, and TREK_PLUGINS_DEV_LINK additionally reveals a + // "Link a local plugin" row in the panel. Documenting either would show + // readers a UI they will never have. + // + // Needs network. If the registry is unreachable the plugin screenshots are + // skipped loudly rather than silently captured in a misleading state. + for (const id of ['koffi', 'trip-doctor']) { + const res = await api.post('/api/admin/plugins/install', { data: { id } }) + if (!res.ok()) { + console.log(`PLUGIN INSTALL FAILED ${id} → ${res.status()} ${await res.text()}`) + continue + } + await api.post(`/api/admin/plugins/${id}/activate`, { data: {} }) + } + + return { tripId, memberIds, dayIds, placeIds, collectionId, journeyId } +} diff --git a/client/e2e/screenshots/settings.shot.ts b/client/e2e/screenshots/settings.shot.ts new file mode 100644 index 000000000..59faf3b54 --- /dev/null +++ b/client/e2e/screenshots/settings.shot.ts @@ -0,0 +1,105 @@ +import { test, clearNotices } from './shot' +import type { Page } from '@playwright/test' + +/** + * Settings and Admin tabs. + * + * Both pages use the shared PageSidebar with client-side tab state (no URL + * segment per tab), so each capture clicks its way in. Labels come from + * shared/src/i18n/en — note "General" is the tab the wiki still calls + * "Display", which is one of the corrections this screenshot run supports. + */ + +async function openSidebarTab(page: Page, label: string) { + await page.getByRole('button', { name: label, exact: true }).first().click() + await page.waitForTimeout(600) +} + +test.describe('user settings', () => { + test.beforeEach(async ({ page }) => { + await page.goto('/settings') + await clearNotices(page) + }) + + // Filename kept as UsrSettings.png — the wiki already references it. + test('general tab', async ({ page, shot }) => { + await openSidebarTab(page, 'General') + await shot.page_('UsrSettings') + }) + + test('appearance tab', async ({ page, shot }) => { + await openSidebarTab(page, 'Appearance') + await shot.page_('UsrSettingsAppearance') + }) + + test('map tab', async ({ page, shot }) => { + await openSidebarTab(page, 'Map') + await shot.page_('UsrSettingsMap') + }) + + test('notifications tab', async ({ page, shot }) => { + await openSidebarTab(page, 'Notifications') + await shot.page_('NotifSettings') + }) + + test('offline tab', async ({ page, shot }) => { + await openSidebarTab(page, 'Offline') + await shot.page_('SettingsOffline') + }) + + test('account tab', async ({ page, shot }) => { + await openSidebarTab(page, 'Account') + await shot.page_('SettingsAccount') + }) +}) + +test.describe('admin panel', () => { + test.beforeEach(async ({ page }) => { + await page.goto('/admin') + await clearNotices(page) + }) + + test('users', async ({ page, shot }) => { + await openSidebarTab(page, 'Users') + await shot.page_('UsersAndInvites') + }) + + test('user defaults', async ({ page, shot }) => { + await openSidebarTab(page, 'User Defaults') + await shot.page_('AdminUserDefaults') + }) + + test('personalization', async ({ page, shot }) => { + await openSidebarTab(page, 'Personalization') + await shot.page_('CategoryManager') + }) + + test('addons', async ({ page, shot }) => { + await openSidebarTab(page, 'Addons') + await shot.page_('Addons-Overview') + }) + + test('plugins', async ({ page, shot }) => { + await openSidebarTab(page, 'Plugins') + await shot.page_('AdminPlugins') + }) + + test('github releases', async ({ page, shot }) => { + await openSidebarTab(page, 'GitHub') + await shot.page_('GithubReleases') + }) + + test('backup', async ({ page, shot }) => { + await openSidebarTab(page, 'Backup') + await shot.page_('Backup') + }) + + test('audit log', async ({ page, shot }) => { + await openSidebarTab(page, 'Audit') + await shot.page_('Audit') + }) + + test('admin panel overview', async ({ page, shot }) => { + await shot.page_('AdminPanel') + }) +}) diff --git a/client/e2e/screenshots/shot.ts b/client/e2e/screenshots/shot.ts new file mode 100644 index 000000000..1b6040986 --- /dev/null +++ b/client/e2e/screenshots/shot.ts @@ -0,0 +1,119 @@ +import { test as base, expect, type Page, type Locator } from '@playwright/test' +import { mkdirSync } from 'node:fs' +import path from 'node:path' + +/** + * Shared plumbing for the documentation screenshot run (`npm run shots`). + * + * These are not assertions about behaviour — they drive the app to a known + * state and capture it for the wiki. They live behind their own Playwright + * project (`screenshots`, testMatch /\.shot\.ts/) so a normal `npm run e2e` + * never pays for them. + * + * Output goes to a staging directory, NOT straight into wiki/assets/, so a + * bad run can never clobber good artwork. Promote with `npm run shots:promote`. + */ + +// Playwright runs from the client workspace root, matching how +// playwright.config.ts spells `storageState: 'e2e/.tmp/state.json'`. +export const OUT_DIR = path.join(process.cwd(), 'e2e', '.tmp', 'shots') + +/** Desktop capture size. 2x scale keeps text crisp; images are squeezed on promote. */ +export const VIEWPORT = { width: 1440, height: 900 } + +export const test = base.extend<{ shot: Shot }>({ + // Overriding `page` (rather than doing this inside the `shot` fixture) is + // deliberate: fixtures initialise lazily, so a route registered in `shot` + // lands AFTER any beforeEach hook has already navigated — too late to + // intercept the config request. + page: async ({ page }, use) => { + await page.setViewportSize(VIEWPORT) + await hideDevOnlyUi(page) + await use(page) + }, + shot: async ({ page }, use) => { + mkdirSync(OUT_DIR, { recursive: true }) + await use(new Shot(page)) + }, +}) + +/** + * The E2E backend runs with NODE_ENV=development, so /auth/app-config reports + * `dev_mode: true` (authService.ts) and the admin sidebar grows a + * "Dev: Notifications" tab that no real deployment ever shows. + * + * Rewriting the response is the surgical fix. Flipping the server to + * NODE_ENV=production would also enable HSTS (globalMiddleware.ts), and an + * HSTS header on localhost would upgrade the run to https and break it. + */ +async function hideDevOnlyUi(page: Page): Promise { + await page.route('**/api/auth/app-config', async route => { + const res = await route.fetch() + const body = await res.json() + await route.fulfill({ response: res, json: { ...body, dev_mode: false } }) + }) +} + +export { expect } + +export class Shot { + constructor(private readonly page: Page) {} + + /** + * Capture the full viewport. `name` is the target filename in wiki/assets/ + * (without extension) so the mapping from screenshot to doc page is literal. + */ + async page_(name: string): Promise { + await this.settle() + await this.page.screenshot({ path: path.join(OUT_DIR, `${name}.png`) }) + } + + /** Capture one element — preferred for dialogs, panels and cards. */ + async element(name: string, target: Locator): Promise { + await this.settle() + await expect(target).toBeVisible() + await target.screenshot({ path: path.join(OUT_DIR, `${name}.png`) }) + } + + /** + * Quiet the page before capturing: fonts loaded, images decoded, animations + * finished, no pending network. Without this, screenshots catch skeleton + * loaders and half-faded modals, which is exactly how the current wiki + * assets ended up inconsistent. + */ + private async settle(): Promise { + // Bounded: TREK holds a WebSocket open at /ws, so the network never goes + // fully idle and an unbounded wait would burn the whole test timeout. + await this.page.waitForLoadState('networkidle', { timeout: 5_000 }).catch(() => {}) + // Await, but return nothing — the resolved FontFaceSet is not serialisable. + await this.page.evaluate(async () => { await document.fonts.ready }) + await this.page.evaluate(async () => { + await Promise.all( + Array.from(document.images) + .filter(img => !img.complete) + .map(img => new Promise(res => { img.onload = img.onerror = res })), + ) + }) + // Let CSS transitions land (modal fade-in, sidebar slide). + await this.page.waitForTimeout(400) + } +} + +/** + * Dismiss the first-run system notice. Copied in spirit from e2e/helpers.ts, + * but tolerant: on a seeded DB the notice may already be cleared. + */ +export async function clearNotices(page: Page): Promise { + const next = page.getByRole('button', { name: /next/i }) + for (let i = 0; i < 6 && (await next.isVisible().catch(() => false)); i++) { + if (!(await next.isEnabled().catch(() => false))) break + await next.click().catch(() => {}) + } + for (const label of ['Dismiss', 'OK']) { + const btn = page.getByRole('button', { name: label, exact: true }) + for (let i = 0; i < 4 && (await btn.isVisible().catch(() => false)); i++) { + await btn.click().catch(() => {}) + await page.waitForTimeout(300) + } + } +} diff --git a/client/e2e/trip-planner.spec.ts b/client/e2e/trip-planner.spec.ts index 9a4b8b2ce..754145ca3 100644 --- a/client/e2e/trip-planner.spec.ts +++ b/client/e2e/trip-planner.spec.ts @@ -1,4 +1,5 @@ import { test, expect } from '@playwright/test' +import { dismissSystemNotices } from './helpers' // Open a trip into the planner: create a trip, open it from the dashboard, and // confirm the trip planner (TripPlannerPage — the app's largest page) actually @@ -6,12 +7,17 @@ import { test, expect } from '@playwright/test' test('open a trip and land in the planner with a map', async ({ page }) => { await page.goto('/dashboard') + // The release notice greets a freshly seeded user and its backdrop eats the click below. + await dismissSystemNotices(page) + // Create a trip to open. await page.locator('.add-trip-card').click() - const modal = page.locator('.modal-backdrop') + const modal = page.locator('.trek-modal-backdrop') await expect(modal).toBeVisible() + // Target Title by placeholder: the cover-image search inputs sit above it, so + // input[type=text].first() is the photo search box, not the field we want. const title = `E2E Planner ${Date.now()}` - await modal.locator('input[type="text"]').first().fill(title) + await modal.getByPlaceholder('e.g. Summer in Japan').fill(title) await modal.getByRole('button', { name: 'Create New Trip' }).click() // Open it from the dashboard. diff --git a/client/package.json b/client/package.json index fc565ff80..12140bf69 100644 --- a/client/package.json +++ b/client/package.json @@ -20,6 +20,8 @@ "theme:lint": "node scripts/theme-lint.mjs", "theme:lint:strict": "node scripts/theme-lint.mjs --strict", "e2e": "playwright test", + "shots": "playwright test --project=screenshots", + "shots:promote": "node e2e/screenshots/promote.mjs", "e2e:report": "playwright show-report", "format": "prettier --write \"src/**/*.tsx\" \"src/**/*.css\"", "format:check": "prettier --check \"src/**/*.tsx\" \"src/**/*.css\"" diff --git a/client/playwright.config.ts b/client/playwright.config.ts index e6868a43c..f2c71453e 100644 --- a/client/playwright.config.ts +++ b/client/playwright.config.ts @@ -35,6 +35,28 @@ export default defineConfig({ use: { ...devices['Desktop Chrome'], storageState: 'e2e/.tmp/state.json' }, dependencies: ['setup'], }, + // Documentation screenshots (`npm run shots`). Excluded from the normal e2e + // run by its own testMatch — these capture artwork for wiki/assets/, they + // assert nothing. 2x scale keeps text crisp at the sizes the wiki renders. + // Populates the demo trip the screenshots are taken of. Separate project so + // it runs exactly once, between auth and capture. + { + name: 'seed', + testMatch: /seed\.setup\.ts/, + use: { ...devices['Desktop Chrome'], storageState: 'e2e/.tmp/state.json' }, + dependencies: ['setup'], + }, + { + name: 'screenshots', + testMatch: /\.shot\.ts/, + use: { + ...devices['Desktop Chrome'], + storageState: 'e2e/.tmp/state.json', + viewport: { width: 1440, height: 900 }, + deviceScaleFactor: 2, + }, + dependencies: ['seed'], + }, ], webServer: [ { diff --git a/client/src/api/client.ts b/client/src/api/client.ts index b3f05d041..d2f716143 100644 --- a/client/src/api/client.ts +++ b/client/src/api/client.ts @@ -31,7 +31,7 @@ import { type PlaceBulkUpdateRequest, type DayNoteCreateRequest, type DayNoteUpdateRequest, type PackingImportRequest, type PackingBagMembersRequest, type PackingUpdateBagRequest, - type PackingCategoryAssigneesRequest, + type PackingCategoryAssigneesRequest, type PackingApplyTemplateRequest, type BudgetUpdateMembersRequest, type BudgetToggleMemberPaidRequest, type BudgetReorderCategoriesRequest, type TodoCategoryAssigneesRequest, type CollabNoteCreateRequest, type CollabNoteUpdateRequest, type CollabPollCreateRequest, @@ -449,7 +449,7 @@ export const packingApi = { getCategoryAssignees: (tripId: number | string) => apiClient.get(`/trips/${tripId}/packing/category-assignees`).then(r => r.data), setCategoryAssignees: (tripId: number | string, categoryName: string, userIds: number[]) => apiClient.put(`/trips/${tripId}/packing/category-assignees/${encodeURIComponent(categoryName)}`, { user_ids: userIds } satisfies PackingCategoryAssigneesRequest).then(r => r.data), listTemplates: (tripId: number | string) => apiClient.get(`/trips/${tripId}/packing/templates`).then(r => r.data), - applyTemplate: (tripId: number | string, templateId: number) => apiClient.post(`/trips/${tripId}/packing/apply-template/${templateId}`).then(r => r.data), + applyTemplate: (tripId: number | string, templateId: number, visibility: 'common' | 'personal' = 'common') => apiClient.post(`/trips/${tripId}/packing/apply-template/${templateId}`, { visibility } satisfies PackingApplyTemplateRequest).then(r => r.data), saveAsTemplate: (tripId: number | string, name: string) => apiClient.post(`/trips/${tripId}/packing/save-as-template`, { name }).then(r => r.data), setBagMembers: (tripId: number | string, bagId: number, userIds: number[]) => apiClient.put(`/trips/${tripId}/packing/bags/${bagId}/members`, { user_ids: userIds } satisfies PackingBagMembersRequest).then(r => r.data), listBags: (tripId: number | string) => apiClient.get(`/trips/${tripId}/packing/bags`).then(r => r.data), @@ -502,6 +502,11 @@ export const adminApi = { pluginActivate: (id: string, consent?: boolean) => apiClient.post(`/admin/plugins/${id}/activate`, consent ? { consent: true } : {}).then(r => r.data), pluginDeactivate: (id: string) => apiClient.post(`/admin/plugins/${id}/deactivate`).then(r => r.data), pluginUpdate: (id: string) => apiClient.post(`/admin/plugins/${id}/update`).then(r => r.data), + // Re-trust a ROTATED author signing key and update, in ONE call. `publicKey` is the + // full key the admin was shown (not a fingerprint): the server compares it exactly, so + // it can refuse if the registry entry was re-keyed again since the dialog rendered. + pluginRetrust: (id: string, version: string, publicKey: string) => + apiClient.post(`/admin/plugins/${id}/retrust`, { version, publicKey }).then(r => r.data), pluginUninstall: (id: string, deleteData: boolean) => apiClient.post(`/admin/plugins/${id}/uninstall`, { deleteData }).then(r => r.data), pluginRescan: () => apiClient.post('/admin/plugins/rescan').then(r => r.data), pluginUpload: (file: File) => { const fd = new FormData(); fd.append('file', file); return postMultipart('/admin/plugins/upload', fd) }, @@ -739,8 +744,8 @@ export const airtrailApi = { sync: (): Promise<{ changed: number }> => apiClient.post('/integrations/airtrail/sync').then(r => r.data), // flights + import are added with the trip-planner import (P2) flights: () => apiClient.get('/integrations/airtrail/flights').then(r => r.data), - import: (tripId: number, flightIds: string[]) => - apiClient.post(`/trips/${tripId}/reservations/import/airtrail`, { flightIds }).then(r => r.data), + import: (tripId: number, flightIds: string[], connections?: string[][]) => + apiClient.post(`/trips/${tripId}/reservations/import/airtrail`, connections?.length ? { flightIds, connections } : { flightIds }).then(r => r.data), } export const journeyApi = { diff --git a/client/src/components/Admin/AdminPluginsPanel.test.tsx b/client/src/components/Admin/AdminPluginsPanel.test.tsx index 3264de51c..8c1884818 100644 --- a/client/src/components/Admin/AdminPluginsPanel.test.tsx +++ b/client/src/components/Admin/AdminPluginsPanel.test.tsx @@ -1,5 +1,5 @@ import { http, HttpResponse } from 'msw' -import { beforeEach, describe, expect, it } from 'vitest' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { server } from '../../../tests/helpers/msw/server' import { fireEvent, render, screen, waitFor } from '../../../tests/helpers/render' import { resetAllStores } from '../../../tests/helpers/store' @@ -119,3 +119,366 @@ describe('AdminPluginsPanel — Discover modal, operator-egress pill', () => { expect(screen.queryByText(/hosts you add/i)).not.toBeInTheDocument() }) }) + +/** + * #1523. The row's ⋯ menu used to be an in-flow `absolute` div, and PageSidebar — the + * panel's ancestor — is `overflow-hidden`. On the lower rows of a long plugin list the + * menu was clipped mid-way, taking Delete with it: the plugin became uninstallable from + * the UI. It must escape every overflow ancestor, and flip up when the bottom is tight. + */ +describe('AdminPluginsPanel — row ⋯ menu is never clipped (#1523)', () => { + const withRepo = plugin({ source_repo: 'trek/gotify', operatorEgress: false }) + const realRect = HTMLButtonElement.prototype.getBoundingClientRect + afterEach(() => { HTMLButtonElement.prototype.getBoundingClientRect = realRect }) + + /** Put the ⋯ button wherever we want in an 800px-tall viewport. */ + function stubTriggerAt(top: number) { + window.innerHeight = 800 + window.innerWidth = 1200 + HTMLButtonElement.prototype.getBoundingClientRect = function () { + return { top, bottom: top + 34, left: 1100, right: 1134, width: 34, height: 34, x: 1100, y: top, toJSON: () => ({}) } as DOMRect + } + } + + async function openRowMenu() { + mockList(withRepo) + const { container } = render() + fireEvent.click(await screen.findByTestId('plugin-row-menu-btn-trek-gotify')) + return { container, menu: screen.getByTestId('plugin-row-menu-trek-gotify') } + } + + it('FE-COMP-PLUGINS-MENU-001: renders every action, including Delete', async () => { + stubTriggerAt(100) + await openRowMenu() + + for (const label of [/restart/i, /error log/i, /allowed hosts/i, /source repository/i, /report an issue/i, /delete/i]) { + expect(screen.getByText(label)).toBeInTheDocument() + } + }) + + it('FE-COMP-PLUGINS-MENU-002: is portaled out of the panel, so no overflow ancestor can clip it', async () => { + stubTriggerAt(100) + const { container, menu } = await openRowMenu() + + // THE regression guard: living inside the panel is exactly what got it clipped. + expect(container.contains(menu)).toBe(false) + expect(menu.parentElement).toBe(document.body) + expect(menu.style.position).toBe('fixed') + }) + + it('FE-COMP-PLUGINS-MENU-003: hangs below the ⋯ when there is room', async () => { + stubTriggerAt(100) + const { menu } = await openRowMenu() + + expect(menu.style.top).toBe('138px') // trigger bottom (134) + 4 + expect(menu.style.bottom).toBe('') + expect(menu.style.right).toBe('66px') // viewport (1200) - trigger right (1134) + }) + + it('FE-COMP-PLUGINS-MENU-004: flips upward for a row near the bottom — the #1523 case', async () => { + stubTriggerAt(700) // 66px of room below: the six-item menu would run off-screen + const { menu } = await openRowMenu() + + expect(menu.style.bottom).toBe('104px') // viewport (800) - trigger top (700) + 4 + expect(menu.style.top).toBe('') + }) +}) + +/** + * Signature status (#plugins). TREK has always verified author signatures and TOFU-pinned + * the key — and never showed any of it, so a successfully-installed UNSIGNED plugin looked + * identical to a signed one, forever. + * + * The two tests that matter most here are the ones guarding the override: a re-trust is + * offered for a ROTATED key (benign explanation) and for NOTHING else. A signature that + * doesn't verify means the bytes are not what the author signed, and there is no story + * where the right answer is letting the admin wave it through. + */ +function registryEntry(over: Record = {}) { + return { + id: 'trek-gotify', name: 'Gotify', author: 'Acme', description: 'Push', repo: 'acme/gotify', + type: 'integration', latest: '2.0.0', minTrekVersion: null, reviewedAt: null, + screenshotUrl: null, signed: true, authorPublicKey: 'NEWKEYbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', + ...over, + } +} + +function mockPanel(p: Record, entry: Record | null = registryEntry()) { + server.use( + http.get('*/api/admin/plugins', () => HttpResponse.json({ enabled: true, devLink: false, plugins: [p] })), + http.get('*/api/admin/plugins/registry', () => HttpResponse.json(entry ? [entry] : [])), + ) +} + +describe('AdminPluginsPanel — signature badges', () => { + it('FE-COMP-PLUGINS-SIG-001: a registry plugin with a pinned key reads as Signed', async () => { + mockPanel(plugin({ source_repo: 'acme/gotify', signed: true, keyFingerprint: 'AAAAAAAA…BBBBBBBB' })) + render() + expect(await screen.findByText('Signed')).toBeInTheDocument() + expect(screen.queryByText('Unsigned')).not.toBeInTheDocument() + }) + + it('FE-COMP-PLUGINS-SIG-002: a registry plugin with no key reads as Unsigned', async () => { + mockPanel(plugin({ source_repo: 'acme/gotify', signed: false, keyFingerprint: null })) + render() + expect(await screen.findByText('Unsigned')).toBeInTheDocument() + }) + + // The precedence rule. `signed` derives from the pinned key, sideloaded from source_repo + // — so they are NOT mutually exclusive in the data, and a sideloaded plugin genuinely has + // no key. Rendering "Unsigned" NEXT TO "Sideloaded" would double up on a plugin whose + // badge already says something strictly stronger, diluting the amber into wallpaper. + it('FE-COMP-PLUGINS-SIG-003: a sideloaded plugin shows Sideloaded and NO trust badge', async () => { + mockPanel(plugin({ source_repo: 'local:upload', signed: false })) + render() + expect(await screen.findByText('Sideloaded')).toBeInTheDocument() + expect(screen.queryByText('Unsigned')).not.toBeInTheDocument() + expect(screen.queryByText('Signed')).not.toBeInTheDocument() + }) + + it('FE-COMP-PLUGINS-SIG-004: a dev-linked plugin shows Dev-Link and NO trust badge', async () => { + mockPanel(plugin({ source_repo: 'local:link', signed: false })) + render() + expect(await screen.findByText('Dev-Link')).toBeInTheDocument() + expect(screen.queryByText('Unsigned')).not.toBeInTheDocument() + }) +}) + +describe('AdminPluginsPanel — a refused update', () => { + const blocked = (code: string) => + plugin({ + source_repo: 'acme/gotify', signed: true, keyFingerprint: 'OLDKEYaa…aaaaaaaa', + updateBlock: { code, detail: 'the signing key changed', version: '2.0.0' }, + }) + + it('FE-COMP-PLUGINS-SIG-005: the row keeps showing WHY, instead of the reason dying with a toast', async () => { + mockPanel(blocked('SIGNATURE_KEY_CHANGED')) + render() + expect(await screen.findByText(/update blocked/i)).toBeInTheDocument() + }) + + // The block describes the version that was REFUSED. Once the registry offers a newer one, + // it describes an artifact nobody is being offered anymore — so it reads as stale and the + // admin can simply re-attempt. + it('FE-COMP-PLUGINS-SIG-006: the block goes quiet once a NEWER version is on offer', async () => { + mockPanel(blocked('SIGNATURE_KEY_CHANGED'), registryEntry({ latest: '3.0.0' })) + render() + await screen.findByText('Gotify') + await waitFor(() => expect(screen.queryByText(/update blocked/i)).not.toBeInTheDocument()) + }) + + it('FE-COMP-PLUGINS-SIG-007: Review opens the re-trust dialog for a ROTATED key', async () => { + mockPanel(blocked('SIGNATURE_KEY_CHANGED')) + render() + fireEvent.click(await screen.findByRole('button', { name: /review/i })) + + // Both fingerprints, so the admin can compare them against what the author tells them. + expect(await screen.findByText(/key it was installed with/i)).toBeInTheDocument() + expect(screen.getByText(/key it is offering now/i)).toBeInTheDocument() + expect(screen.getByRole('button', { name: /trust the new key/i })).toBeInTheDocument() + }) + + // D2, at the UI. An invalid signature means the bytes are not what the author signed. + // There is no override — not a disabled button, not one behind a confirm. The ABSENCE of + // an escape hatch is the feature. (The server refuses it too; this is belt and braces.) + it('FE-COMP-PLUGINS-SIG-008: an INVALID signature offers NO re-trust affordance at all', async () => { + mockPanel(blocked('SIGNATURE_INVALID')) + render() + fireEvent.click(await screen.findByRole('button', { name: /review/i })) + + await screen.findByText(/do not match the author's signature/i) + expect(screen.queryByRole('button', { name: /trust the new key/i })).not.toBeInTheDocument() + // ...and it does not even show the key comparison, which would imply a choice exists. + expect(screen.queryByText(/key it is offering now/i)).not.toBeInTheDocument() + }) + + it('FE-COMP-PLUGINS-SIG-009: an unsigned-downgrade refusal offers no override either', async () => { + mockPanel(blocked('SIGNATURE_MISSING')) + render() + fireEvent.click(await screen.findByRole('button', { name: /review/i })) + + await screen.findByText(/ships no signature/i) + expect(screen.queryByRole('button', { name: /trust the new key/i })).not.toBeInTheDocument() + }) + + it('FE-COMP-PLUGINS-SIG-010: confirming a re-trust re-pins AND updates in ONE call', async () => { + let body: unknown = null + mockPanel(blocked('SIGNATURE_KEY_CHANGED')) + server.use( + http.post('*/api/admin/plugins/trek-gotify/retrust', async ({ request }) => { + body = await request.json() + return HttpResponse.json({ version: '2.0.0', activated: true, newPermissions: [], newEgress: [] }) + }), + ) + render() + fireEvent.click(await screen.findByRole('button', { name: /review/i })) + fireEvent.click(await screen.findByRole('button', { name: /trust the new key/i })) + + // The FULL key goes back, not the fingerprint: the server's equality check is exact, so + // it can refuse if the entry was re-keyed again since this dialog rendered. + await waitFor(() => + expect(body).toEqual({ version: '2.0.0', publicKey: 'NEWKEYbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb' }), + ) + // No follow-up /update: a re-pin that waited for a second call would leave the plugin + // pinned to a key no install had ever verified against if that call never came. + }) +}) + +describe('AdminPluginsPanel — update consent', () => { + it('FE-COMP-PLUGINS-SIG-011: says an unsigned update is untied to its author, and still activates in one click', async () => { + let activated = false + mockPanel(plugin({ source_repo: 'acme/gotify', signed: false }), registryEntry({ signed: false })) + server.use( + http.post('*/api/admin/plugins/trek-gotify/update', () => + HttpResponse.json({ version: '2.0.0', activated: false, newPermissions: ['db:read:trips'], newEgress: [] }), + ), + http.post('*/api/admin/plugins/trek-gotify/activate', () => { activated = true; return HttpResponse.json({ status: 'active' }) }), + ) + render() + await screen.findByText('Gotify') + fireEvent.click(await screen.findByRole('button', { name: /update to|2\.0\.0/i })) + + // Informs — it does not block. No checkbox, no second click. + expect(await screen.findByText(/nothing ties this version to its author/i)).toBeInTheDocument() + fireEvent.click(screen.getByRole('button', { name: /approve & turn on/i })) + await waitFor(() => expect(activated).toBe(true)) + }) + + // The warning used to be read ONLY off the registry entry, so an unreachable registry left + // it undefined and the pill silently vanished — at the exact moment the admin was widening + // what unsigned code may do. The installed row carries an authoritative `signed` from the + // server on every list call; degrade to that rather than to silence. + // + // Consent is reached here by turning a plugin back ON after an update widened its + // permissions (409 CONSENT_REQUIRED) — which is the path that still works with the registry + // down, precisely because it needs nothing from the registry. + it('FE-COMP-PLUGINS-SIG-015: the unsigned warning survives an unreachable registry', async () => { + server.use( + http.get('*/api/admin/plugins', () => + HttpResponse.json({ + enabled: true, devLink: false, + plugins: [plugin({ source_repo: 'acme/gotify', signed: false, enabled: 0, status: 'inactive', operatorEgress: false })], + })), + // The registry is down: `regById` stays empty, so the entry's `signed` is unknowable. + http.get('*/api/admin/plugins/registry', () => HttpResponse.json({ error: 'registry unreachable' }, { status: 500 })), + http.post('*/api/admin/plugins/trek-gotify/activate', () => + HttpResponse.json({ error: 'consent required', code: 'CONSENT_REQUIRED', newPermissions: ['db:read:trips'], newEgress: [] }, { status: 409 })), + ) + render() + fireEvent.click(await screen.findByRole('button', { name: /enable plugin/i })) + + // Falls back to the installed row's `signed: false` rather than going quiet. + expect(await screen.findByText(/nothing ties this version to its author/i)).toBeInTheDocument() + }) +}) + +/** + * A signature refusal must reach the dialog even when the plugin has NO installed row — + * which is every fresh install from Discover, and every dependency being downloaded. + * + * Routing the refusal off the installed list meant those two paths silently fell back to a + * generic toast: the admin met SIGNATURE_INVALID for the first time on the one path where the + * dialog explaining it never opened. A fresh install has no pinned key, so it can only ever + * be _INVALID / _INCOMPLETE — never a rotation — and both are non-overridable, so the dialog + * must explain and offer nothing. + */ +describe('AdminPluginsPanel — a refusal with no installed row', () => { + it('FE-COMP-PLUGINS-SIG-013: a fresh install refused for an INVALID signature opens the dialog, not a toast', async () => { + server.use( + http.get('*/api/admin/plugins', () => HttpResponse.json({ enabled: true, devLink: false, plugins: [] })), + http.get('*/api/admin/plugins/registry', () => HttpResponse.json([registryEntry()])), + http.post('*/api/admin/plugins/install', () => + HttpResponse.json({ error: 'author signature verification failed', code: 'SIGNATURE_INVALID' }, { status: 400 })), + ) + render() + fireEvent.click(await screen.findByRole('button', { name: /discover/i })) + fireEvent.click(await screen.findByRole('button', { name: /^install$/i })) + + // The dialog, named after the plugin — which it can only know from the REGISTRY entry, + // there being no installed row to read a name off. + expect(await screen.findByText(/gotify's signature could not be verified/i)).toBeInTheDocument() + await screen.findByText(/do not match the author's signature/i) + // Non-overridable, and no key comparison — showing one would imply a choice exists. + expect(screen.queryByRole('button', { name: /trust the new key/i })).not.toBeInTheDocument() + expect(screen.queryByText(/key it is offering now/i)).not.toBeInTheDocument() + }) + + it('FE-COMP-PLUGINS-SIG-014: a refusal while downloading a DEPENDENCY opens the dialog too', async () => { + const parent = plugin({ id: 'trek-parent', name: 'Parent', source_repo: 'acme/parent', enabled: 0, status: 'inactive', operatorEgress: false }) + server.use( + http.get('*/api/admin/plugins', () => HttpResponse.json({ enabled: true, devLink: false, plugins: [parent] })), + http.get('*/api/admin/plugins/registry', () => HttpResponse.json([registryEntry()])), + // Turning it on reveals the missing dependency… + http.post('*/api/admin/plugins/trek-parent/activate', () => + HttpResponse.json({ error: 'missing dependency', code: 'DEPENDENCY_MISSING', missing: [{ id: 'trek-gotify', version: '^1.0.0' }], versionMismatch: [] }, { status: 409 })), + // …and downloading it is refused on its signature. + http.post('*/api/admin/plugins/install', () => + HttpResponse.json({ error: 'author signature verification failed', code: 'SIGNATURE_INVALID' }, { status: 400 })), + ) + render() + fireEvent.click(await screen.findByRole('button', { name: /enable plugin/i })) + fireEvent.click(await screen.findByRole('button', { name: /download/i })) + + // Named after the DEPENDENCY, not the parent — it is the dependency's author whose + // signature did not verify, and saying "Parent" here would point the admin at the wrong + // plugin entirely. + expect(await screen.findByText(/gotify's signature could not be verified/i)).toBeInTheDocument() + expect(screen.queryByRole('button', { name: /trust the new key/i })).not.toBeInTheDocument() + }) +}) + +describe('AdminPluginsPanel — a block never outlives the registry relationship', () => { + // The server clears the block on sideload/dev-link. This is the belt: even if a stale + // block somehow reached the client, a plugin whose code the admin supplied by hand must + // never claim an update was blocked over an author signing key. + it('FE-COMP-PLUGINS-SIG-012: a sideloaded plugin never shows an update block', async () => { + mockPanel(plugin({ + source_repo: 'local:upload', signed: false, + updateBlock: { code: 'SIGNATURE_KEY_CHANGED', detail: 'the signing key changed', version: '2.0.0' }, + })) + render() + await screen.findByText('Sideloaded') + expect(screen.queryByText(/update blocked/i)).not.toBeInTheDocument() + }) +}) + +/** + * TREK-version compatibility. The SERVER owns the semver — a second implementation in the + * browser would eventually disagree with the install gate and offer a button that 400s — + * so the panel only renders the verdict the API hands it (`compatible`, `latestCompatible`). + */ +describe('AdminPluginsPanel — TREK-version compatibility', () => { + /** Discover cards for a plugin that is NOT installed — an installed one just reads "Installed". */ + async function openDiscover(entry: Record) { + mockPanel(plugin({ id: 'something-else' }), registryEntry(entry)) + render() + fireEvent.click(await screen.findByText('Discover')) + } + + it('blocks Install when no published version runs on this TREK, and says why', async () => { + await openDiscover({ trek: '>=4.0.0', hostVersion: '3.3.0', compatible: false, latestCompatible: null }) + const btn = await screen.findByRole('button', { name: /^incompatible$/i }) + expect(btn).toBeDisabled() + }) + + it('offers the newest version that DOES run here rather than a dead button', async () => { + await openDiscover({ latest: '2.0.0', trek: '>=3.4.0', hostVersion: '3.3.0', compatible: false, latestCompatible: '1.5.0' }) + const btn = await screen.findByRole('button', { name: /^install 1\.5\.0$/i }) + expect(btn).toBeEnabled() + }) + + it('installs normally when the latest version fits', async () => { + await openDiscover({ trek: '>=3.2.0 <4.0.0', hostVersion: '3.3.0', compatible: true, latestCompatible: '2.0.0' }) + expect(await screen.findByRole('button', { name: /^install$/i })).toBeEnabled() + }) + + it('an installed plugin the server has outgrown shows the blocker on its card', async () => { + // Same amber chip machinery as a disabled addon / missing dependency — the admin sees + // one "here is why this cannot turn on" surface, not a new concept per blocker. + mockPanel(plugin({ + dependencyStatus: 'hostIncompatible', trekRange: '>=3.2.0 <4.0.0', hostVersion: '4.0.0', enabled: 0, status: 'inactive', + })) + render() + expect(await screen.findByText(/needs trek >=3\.2\.0 <4\.0\.0/i)).toBeInTheDocument() + }) +}) diff --git a/client/src/components/Admin/AdminPluginsPanel.tsx b/client/src/components/Admin/AdminPluginsPanel.tsx index 00d8b4af9..d14b64654 100644 --- a/client/src/components/Admin/AdminPluginsPanel.tsx +++ b/client/src/components/Admin/AdminPluginsPanel.tsx @@ -1,11 +1,13 @@ -import { useEffect, useMemo, useRef, useState, type DragEvent } from 'react' +import { useEffect, useMemo, useRef, useState, type CSSProperties, type DragEvent } from 'react' +import { createPortal } from 'react-dom' import { Blocks, AlertTriangle, PackageOpen, RefreshCw, Trash2, Download, Bug, X, ShieldCheck, UploadCloud, - ArrowUpCircle, Github, ExternalLink, ChevronDown, Check, Lock, Search, Link2, + ArrowUpCircle, Github, ExternalLink, ChevronDown, Check, Lock, Search, Link2, KeyRound, ShieldAlert, SlidersHorizontal, ArrowUpDown, CircleDot, MoreHorizontal, RotateCw, ArrowRight, Database, Users, LayoutDashboard, - Radio, Luggage, Plane, Globe, Image, CalendarDays, Map, Bell, Cloud, Camera, Compass, - BookOpen, Wallet, Puzzle, MapPin, ListChecks, Pencil, Tag, FileText, + Radio, Luggage, Globe, Image, CalendarDays, Bell, + Wallet, Puzzle, MapPin, ListChecks, Pencil, Tag, FileText, } from 'lucide-react' +import PluginIcon from '../shared/PluginIcon' import { adminApi } from '../../api/client' import { usePluginStore } from '../../store/pluginStore' import { useTranslation } from '../../i18n' @@ -24,7 +26,7 @@ import ToggleSwitch from '../Settings/ToggleSwitch' interface PluginDep { id: string; version: string } interface VersionMismatch { id: string; wanted: string; installed: string } -type DependencyStatus = 'ok' | 'addonDisabled' | 'missingPlugin' +type DependencyStatus = 'ok' | 'addonDisabled' | 'missingPlugin' | 'hostIncompatible' interface PluginDependencies { requiredAddons: string[]; pluginDependencies: PluginDep[] } interface DependencyIssues { disabledAddons: string[]; missing: PluginDep[]; versionMismatch: VersionMismatch[] } @@ -49,6 +51,17 @@ interface PluginRow { dependencies?: PluginDependencies dependencyStatus?: DependencyStatus dependencyIssues?: DependencyIssues + /** The TREK versions the plugin says it supports; null if it never declared any. */ + trekRange?: string | null + /** The TREK this server is running — the server does the semver, the client just shows it. */ + hostVersion?: string + /** The author's signature was verified and their key pinned at install. False means the + * bytes matched the registry's sha256 and nothing more — one fewer guarantee. */ + signed?: boolean + /** Short form of the pinned key, for eyeballing against what the author reads out. */ + keyFingerprint?: string | null + /** Why an update was refused, if one was. `version` is the version that was refused. */ + updateBlock?: { code: string; detail: string | null; version: string | null } | null } interface RegistryItem { id: string @@ -58,13 +71,26 @@ interface RegistryItem { repo: string homepage?: string | null type: string + /** Lucide icon name from the registry entry; absent → Blocks. */ + icon?: string | null latest: string | null minTrekVersion: string | null + /** The latest version's declared TREK range; null on a legacy registry entry. */ + trek?: string | null + hostVersion?: string + /** Whether the LATEST version can be installed on this TREK. Computed server-side. */ + compatible?: boolean + /** Newest installable version — the latest, an older fallback, or null if none fits. */ + latestCompatible?: string | null reviewedAt: string | null downloadCount?: number | null screenshotUrl: string | null requiredAddons?: string[] pluginDependencies?: PluginDep[] + /** The latest version ships an author signature and the entry declares a key. */ + signed?: boolean + /** The full key — public, and carried in full because re-trust compares it exactly. */ + authorPublicKey?: string | null } interface RegistryDetail extends RegistryItem { size: number | null @@ -90,6 +116,49 @@ interface ActivateErr { } } +/** The server's error envelope. Reading `code` — not the message text — is what lets the + * UI tell a rotated key (overridable) from a signature that doesn't verify (never). */ +function errBody(e: unknown): { error?: string; code?: string } { + return (e as { response?: { data?: { error?: string; code?: string } } })?.response?.data ?? {} +} + +/** The ONE signature refusal an admin may override, because a rotation has a benign + * explanation. SIGNATURE_INVALID / _MISSING / _INCOMPLETE mean the bytes are not what the + * author signed — those get an explanation and no override button at all. */ +const RETRUSTABLE = 'SIGNATURE_KEY_CHANGED' +const SIGNATURE_CODES = [RETRUSTABLE, 'SIGNATURE_INVALID', 'SIGNATURE_MISSING', 'SIGNATURE_INCOMPLETE'] + +/** + * What the signature dialog needs to talk about a plugin — deliberately NOT a PluginRow. + * + * A refusal can land on a plugin that is not installed (a fresh install from Discover, or a + * dependency being downloaded), and those have no row. Keying the dialog off PluginRow meant + * the lookup missed and the refusal silently degraded to a toast — on the very path where an + * admin most often meets these codes for the first time. Name + pinned fingerprint is all the + * dialog ever reads, and both a row and a registry entry can supply that. + */ +type SigSubject = { id: string; name: string; keyFingerprint: string | null } + +/** + * Is a recorded update block still describing the version on offer? + * + * Once the registry offers something NEWER than the version that was refused, the block + * describes an artifact nobody is being offered anymore — so it reads as stale and the + * admin can simply re-attempt (the next install re-verifies and either succeeds or + * re-blocks with fresh values). When the registry is unreachable we can't prove staleness, + * so the block stands: silently dropping the last thing we knew would be the worse failure. + */ +function blockIsCurrent(p: PluginRow, latestVer?: string): boolean { + if (!p.updateBlock) return false + // A block describes a refused REGISTRY update. Once a plugin is sideloaded or dev-linked + // it has left the registry trust model — the running code is whatever the admin supplied, + // and a block about an author signing key says nothing about it. The server clears the + // block on both paths; this makes it impossible to render a stale one regardless. + if (!isRegistrySourced(p.source_repo)) return false + if (!latestVer || !p.updateBlock.version) return true + return latestVer === p.updateBlock.version +} + type T = (k: string, p?: Record) => string type TypeFilter = 'all' | 'widget' | 'page' | 'integration' | 'trip-page' type StatusFilter = 'all' | 'on' | 'off' | 'update' | 'err' @@ -105,11 +174,6 @@ const HEALTH: Record = { incompatible: 'bg-warning', } -// Manifest `icon` is a lucide name; map the common ones, fall back to Blocks. -const ICON_MAP: Record> = { - Luggage, Plane, Globe, Image, CalendarDays, Map, Bell, Cloud, Camera, Compass, BookOpen, Wallet, Puzzle, Blocks, -} - // Known permissions → human-readable i18n key; unknown ones render as raw code. const PERM_KEYS = [ 'db:own', 'db:read:trips', 'db:read:users', 'db:read:costs', 'db:read:packing', 'db:read:files', 'db:read:files:content', @@ -186,10 +250,21 @@ function deriveCaps(perms: string[], caps: { widget?: { slot?: string }; tripPag interface DepChip { icon: React.ComponentType<{ size?: number; className?: string }>; label: string; blocked: boolean } // A plugin's declared dependencies as chips — a required addon (amber when that -// addon is disabled) or a plugin dependency (amber when missing / version-mismatched). +// addon is disabled), a plugin dependency (amber when missing / version-mismatched), +// or the TREK version itself (amber when this server has outgrown the plugin's range, +// which is the one blocker the admin cannot fix by flipping something else on). function deriveDeps(p: PluginRow, t: T): DepChip[] { const out: DepChip[] = [] const issues = p.dependencyIssues + if (p.dependencyStatus === 'hostIncompatible') { + out.push({ + icon: AlertTriangle, + label: p.trekRange + ? t('admin.plugins.dep.trekIncompatible', { range: p.trekRange, host: p.hostVersion ?? '?' }) + : t('admin.plugins.dep.trekUnknown'), + blocked: true, + }) + } for (const a of p.dependencies?.requiredAddons ?? []) { out.push({ icon: Blocks, label: t('admin.plugins.cap.requiresAddon', { addon: a }), blocked: !!issues?.disabledAddons.includes(a) }) } @@ -200,9 +275,24 @@ function deriveDeps(p: PluginRow, t: T): DepChip[] { return out } -function PluginIcon({ name, size = 20, className }: { name: string | null; size?: number; className?: string }) { - const Icon = (name && Object.prototype.hasOwnProperty.call(ICON_MAP, name) && ICON_MAP[name]) || Blocks - return +/** + * What the Install button may do for a registry item. + * + * The server already decided compatibility — it owns the semver, and a second + * implementation here would eventually disagree with the install gate and offer a button + * that 400s. This only picks the wording. Note the middle case: when the newest release + * has outrun this TREK but an older one still fits, offer THAT version rather than a dead + * grey button. The plugin is perfectly usable, just not at its newest. + */ +function installOffer(item: RegistryItem, t: T): { blocked: boolean; version?: string; label: string; title?: string } { + if (item.compatible !== false) return { blocked: false, label: t('admin.plugins.install') } + const title = item.trek + ? t('admin.plugins.dep.trekIncompatible', { range: item.trek, host: item.hostVersion ?? '?' }) + : t('admin.plugins.dep.trekUnknown') + if (item.latestCompatible) { + return { blocked: false, version: item.latestCompatible, label: t('admin.plugins.installCompatible', { version: item.latestCompatible }), title } + } + return { blocked: true, label: t('admin.plugins.incompatible'), title } } function ReviewedBadge({ t, compact }: { t: T; compact?: boolean }) { @@ -224,6 +314,46 @@ function SideloadedBadge({ t }: { t: T }) { ) } +/** + * Whether a plugin came from the REGISTRY (as opposed to a manual upload or a dev-link). + * + * This is the precedence rule for the trust badges, and it is load-bearing: `signed` + * derives from the pinned author key while sideloaded/dev-linked derive from source_repo, + * so the states are NOT mutually exclusive in the data. A sideloaded plugin genuinely has + * no pinned key, and a naive render would put "Unsigned" *and* "Sideloaded" side by side. + * The source badge wins — it already says something strictly stronger, and doubling up + * dilutes the amber into wallpaper, which is exactly what makes a warning worthless. + */ +function isRegistrySourced(sourceRepo: string | null | undefined): boolean { + return !!sourceRepo && sourceRepo !== 'local:upload' && sourceRepo !== 'local:link' +} + +/** + * Signed / Unsigned, for registry plugins only (see isRegistrySourced). + * + * Signed is a quiet neutral tick, NOT a green celebration; unsigned is an amber note, NOT + * a red alarm. Roughly two thirds of the live registry is unsigned, so an alarming + * treatment would fire on most of the catalog and teach admins to ignore it — and the + * honest delta is small: sha256 proves the bytes are what the REGISTRY vouches for, a + * signature proves they came from the AUTHOR. Unsigned is one fewer guarantee, not "unsafe". + */ +function TrustBadge({ signed, t }: { signed: boolean; t: T }) { + if (signed) { + return ( + + {t('admin.plugins.signed')} + + ) + } + return ( + + {t('admin.plugins.unsigned')} + + ) +} + /** Marks a dev-linked plugin: loaded from a local build dir + hot-reloaded (dev only). */ function DevLinkBadge({ t }: { t: T }) { return ( @@ -255,6 +385,13 @@ export default function AdminPluginsPanel() { const [view, setView] = useState<'installed' | 'discover'>('installed') const [registry, setRegistry] = useState(null) const [latest, setLatest] = useState>({}) + // The registry entry per id — the re-trust dialog needs the NEW author key from it (in + // full: the server's equality check is exact), and the Discover/consent copy needs `signed`. + const [regById, setRegById] = useState>({}) + // Open when a signature check refused an install/update. Carries the code, so the dialog + // knows whether an override may even be offered. + const [signatureBlock, setSignatureBlock] = useState<{ subject: SigSubject; code: string; detail: string | null } | null>(null) + const [retrusting, setRetrusting] = useState(false) const [detailFor, setDetailFor] = useState(null) const [errorsFor, setErrorsFor] = useState<{ id: string; rows: Array<{ ts: string; level: string; message: string }> } | null>(null) const [egressFor, setEgressFor] = useState<{ id: string; supported: boolean; hosts: string[] } | null>(null) @@ -288,6 +425,16 @@ export default function AdminPluginsPanel() { const uploadInputRef = useRef(null) const dragDepth = useRef(0) + // Index the registry once per fetch: the version map the update badges read, plus the + // whole entry (author key + signed flag) the trust badges and re-trust dialog need. + const indexRegistry = (items: RegistryItem[]) => { + const vers: Record = {} + const byId: Record = {} + items.forEach((i) => { byId[i.id] = i; if (i.latest) vers[i.id] = i.latest }) + setLatest(vers) + setRegById(byId) + } + const refresh = () => { // Keep the app-wide active-plugin store in sync so widget/hero/tab consumers // (e.g. the dashboard) reflect an activate/deactivate without a full reload (F5). @@ -298,13 +445,7 @@ export default function AdminPluginsPanel() { setDevLink(!!d.devLink) setPlugins(d.plugins || []) if ((d.plugins || []).length) { - adminApi.pluginBrowse() - .then((items: RegistryItem[]) => { - const map: Record = {} - items.forEach((i) => { if (i.latest) map[i.id] = i.latest }) - setLatest(map) - }) - .catch(() => {}) + adminApi.pluginBrowse().then(indexRegistry).catch(() => {}) } }) .catch(() => setError(true)) @@ -312,16 +453,43 @@ export default function AdminPluginsPanel() { } useEffect(refresh, []) + // A signature refusal is not an ordinary "action failed": it is the one class of error + // where WHICH failure it was decides what the admin may do about it. Route it to the + // dialog off the CODE, never off the message text. Returns true when handled. + // + // The subject is resolved from wherever it can be — the installed row, else the registry + // entry (a plugin being INSTALLED has no row yet), else the bare id. A signature code + // ALWAYS opens the dialog: falling back to a toast is what used to hide an invalid + // signature on a fresh install behind the same treatment as a network blip. + const routeSignatureError = (id: string, code?: string, detail?: string): boolean => { + if (!code || !SIGNATURE_CODES.includes(code)) return false + const row = plugins.find(p => p.id === id) + const subject: SigSubject = row + ? { id, name: row.name, keyFingerprint: row.keyFingerprint ?? null } + // Not installed: no pinned key exists, so SIGNATURE_KEY_CHANGED cannot arise and the + // dialog shows the no-override explanation — which is exactly right. + : { id, name: regById[id]?.name ?? id, keyFingerprint: null } + setSignatureBlock({ subject, code, detail: detail ?? null }) + return true + } + const act = async (id: string, fn: () => Promise, ok: string) => { setBusy(id); setMenu(null) try { await fn(); toast.success(ok) } - catch (e) { toast.error((e as { response?: { data?: { error?: string } } })?.response?.data?.error || t('admin.plugins.actionError')) } + catch (e) { + const { error, code } = errBody(e) + if (!routeSignatureError(id, code, error)) toast.error(error || t('admin.plugins.actionError')) + } finally { setBusy(null); refresh() } } const openDiscover = () => { setView('discover') - if (!registry) adminApi.pluginBrowse().then(setRegistry).catch(() => setRegistry([])) + if (!registry) { + adminApi.pluginBrowse() + .then((items: RegistryItem[]) => { setRegistry(items); indexRegistry(items) }) + .catch(() => setRegistry([])) + } } // The rescan/reload button rediscovers locally-installed plugins AND force-pulls // the remote registry (bypassing the 30-min server cache + GitHub's CDN), so a @@ -330,9 +498,7 @@ export default function AdminPluginsPanel() { await adminApi.pluginRescan() const items: RegistryItem[] = await adminApi.pluginBrowse(true) setRegistry(items) - const map: Record = {} - items.forEach((i) => { if (i.latest) map[i.id] = i.latest }) - setLatest(map) + indexRegistry(items) }, t('admin.plugins.rescanned')) // Sideload a plugin archive (installs INACTIVE — the admin still consents on activation). @@ -393,7 +559,7 @@ export default function AdminPluginsPanel() { } const updateAvailable = (p: PluginRow) => !!(p.version && latest[p.id] && isNewer(latest[p.id], p.version)) - const install = (id: string) => act(id, () => adminApi.pluginInstall(id), t('admin.plugins.installed')) + const install = (id: string, version?: string) => act(id, () => adminApi.pluginInstall(id, version ? { version } : undefined), t('admin.plugins.installed')) const restart = (id: string) => act(id, async () => { await adminApi.pluginDeactivate(id); await adminApi.pluginActivate(id) }, t('admin.plugins.restarted')) // Dev-link: register a plugin from a local built directory (dev only). Reuses the // same busy/toast/refresh loop as uploadPlugin; the server gates it. @@ -470,7 +636,13 @@ export default function AdminPluginsPanel() { if (r?.requiredAddons?.length) toast.error(t('admin.plugins.dep.addonDisabledToast', { addons: r.requiredAddons.join(', ') })) return attemptActivate(parent) }) - .catch((e: ActivateErr) => onActivateError(parent, e)) + // The DEPENDENCY is what's being downloaded, so a signature refusal here is about the + // dependency's author, not the parent's — route it under depId before falling through + // to the activation-error handling, which knows nothing about signature codes. + .catch((e: ActivateErr) => { + const { error, code } = errBody(e) + if (!routeSignatureError(depId, code, error)) onActivateError(parent, e) + }) .finally(() => { setBusy(null); refresh() }) } @@ -481,10 +653,33 @@ export default function AdminPluginsPanel() { if (r.activated || (r.newPermissions.length === 0 && r.newEgress.length === 0)) toast.success(t('admin.plugins.updated')) else setConsentQueue(qq => [...qq, { plugin: p, version: r.version, newPermissions: r.newPermissions, newEgress: r.newEgress }]) }) - .catch(e => toast.error((e as { response?: { data?: { error?: string } } })?.response?.data?.error || t('admin.plugins.actionError'))) + .catch(e => { + const { error, code } = errBody(e) + if (!routeSignatureError(p.id, code, error)) toast.error(error || t('admin.plugins.actionError')) + }) .finally(() => { setBusy(null); refresh() }) } + // Confirm a key rotation: re-pin the new key AND update, in one server call. There is no + // follow-up /update — a re-pin that waited for a second call would leave the plugin + // pinned to a key no install had ever been verified against if that call never came. + const confirmRetrust = (id: string, version: string, publicKey: string) => { + setRetrusting(true) + adminApi.pluginRetrust(id, version, publicKey) + .then((r: { version: string; activated: boolean; newPermissions: string[]; newEgress: string[] }) => { + setSignatureBlock(null) + // A re-trusted update widening permissions still needs consent — re-trusting a + // signing key says nothing about what the new code is allowed to do. Re-trust only + // ever fires for an INSTALLED plugin, so the row is there to consent against. + const p = plugins.find(x => x.id === id) + if (p && !r.activated && (r.newPermissions.length > 0 || r.newEgress.length > 0)) { + setConsentQueue(qq => [...qq, { plugin: p, version: r.version, newPermissions: r.newPermissions, newEgress: r.newEgress }]) + } else toast.success(t('admin.plugins.retrusted')) + }) + .catch(e => toast.error(errBody(e).error || t('admin.plugins.actionError'))) + .finally(() => { setRetrusting(false); refresh() }) + } + // eslint-disable-next-line react-hooks/exhaustive-deps const updatable = useMemo(() => plugins.filter(updateAvailable), [plugins, latest]) @@ -691,8 +886,13 @@ export default function AdminPluginsPanel() { ) : shownInstalled.map(p => ( toggle(p)} onUpdate={() => runUpdate(p)} onRestart={() => restart(p.id)} + onReviewBlock={() => setSignatureBlock({ + subject: { id: p.id, name: p.name, keyFingerprint: p.keyFingerprint ?? null }, + code: p.updateBlock!.code, detail: p.updateBlock!.detail, + })} onErrors={() => openErrors(p.id)} onEgress={() => openEgress(p.id)} onUninstall={() => { setMenu(null); setConfirmUninstall(p) }} /> ))} @@ -791,9 +991,26 @@ export default function AdminPluginsPanel() { message={t('admin.plugins.uninstallBody')} /> + {signatureBlock && ( + confirmRetrust(signatureBlock.subject.id, version, publicKey)} + onClose={() => setSignatureBlock(null)} + /> + )} + {consentQueue[0] && ( { const c = consentQueue[0]; setConsentQueue(qq => qq.slice(1)) // consent:true — the ONLY path that may widen a plugin's granted rights. @@ -886,14 +1103,33 @@ function EmptyState({ t, onDiscover }: { t: T; onDiscover: () => void }) { ) } -function InstalledRow({ p, t, busy, menu, setMenu, hasUpdate, latestVer, onToggle, onUpdate, onRestart, onErrors, onEgress, onUninstall }: { +function InstalledRow({ p, t, busy, menu, setMenu, hasUpdate, latestVer, blocked, onToggle, onUpdate, onRestart, onReviewBlock, onErrors, onEgress, onUninstall }: { p: PluginRow; t: T; busy: string | null; menu: string | null; setMenu: (v: string | null) => void - hasUpdate: boolean; latestVer?: string - onToggle: () => void; onUpdate: () => void; onRestart: () => void; onErrors: () => void; onEgress: () => void; onUninstall: () => void + hasUpdate: boolean; latestVer?: string; blocked: boolean + onToggle: () => void; onUpdate: () => void; onRestart: () => void; onReviewBlock: () => void + onErrors: () => void; onEgress: () => void; onUninstall: () => void }) { const caps = deriveCaps(parseJson(p.permissions, []), parseJson<{ widget?: { slot?: string } }>(p.capabilities, {}), t) const deps = deriveDeps(p, t) const menuOpen = menu === `row:${p.id}` + const menuBtnRef = useRef(null) + + // The menu is portaled to and positioned `fixed` against the ⋯ button, + // because the row's ancestor (PageSidebar) is `overflow-hidden` and would clip + // an in-flow `absolute` menu — losing Delete on the lower rows of a long list. + // Re-anchor while the page moves under it. + const [, reanchor] = useState(0) + useEffect(() => { + if (!menuOpen) return + const onMove = () => reanchor(n => n + 1) + window.addEventListener('scroll', onMove, true) + window.addEventListener('resize', onMove) + return () => { + window.removeEventListener('scroll', onMove, true) + window.removeEventListener('resize', onMove) + } + }, [menuOpen]) + return (
@@ -911,8 +1147,24 @@ function InstalledRow({ p, t, busy, menu, setMenu, hasUpdate, latestVer, onToggl {p.reviewed_at && } {p.source_repo === 'local:upload' && } {p.source_repo === 'local:link' && } + {/* Registry plugins only — a sideloaded/dev-linked plugin already says something + strictly stronger, and stacking "Unsigned" on top of it just dilutes the amber. */} + {isRegistrySourced(p.source_repo) && }
{p.description &&

{p.description}

} + {/* A refused update leaves a WORKING plugin pinned at its old version — so this is + its own row state, not an error state, and it persists until it is resolved + rather than dying with the toast that first reported it. */} + {blocked && p.updateBlock && ( +
+ + {t('admin.plugins.updateBlocked', { reason: p.updateBlock.detail ?? p.updateBlock.code })} + +
+ )} {p.status === 'error' && p.last_error ? (
{p.last_error} @@ -970,12 +1222,13 @@ function InstalledRow({ p, t, busy, menu, setMenu, hasUpdate, latestVer, onToggl
- - {menuOpen && ( -
+ {menuOpen && createPortal( +
{p.enabled === 1 && ( } label={t('admin.plugins.restart')} onClick={onRestart} /> )} @@ -995,7 +1248,8 @@ function InstalledRow({ p, t, busy, menu, setMenu, hasUpdate, latestVer, onToggl )}
} label={t('common.delete')} danger onClick={onUninstall} /> -
+
, + document.body, )}
@@ -1003,6 +1257,23 @@ function InstalledRow({ p, t, busy, menu, setMenu, hasUpdate, latestVer, onToggl ) } +/** Tallest the ⋯ menu gets (6 items + divider + padding). Drives the flip. */ +const ROW_MENU_MAX_H = 260 + +/** Pin a portaled menu to the right edge of its trigger, flipping up when the bottom is tight. */ +function anchorMenu(trigger: HTMLElement | null): CSSProperties { + const r = trigger?.getBoundingClientRect() + if (!r) return { position: 'fixed', top: 0, right: 0, zIndex: 100 } + const spaceBelow = window.innerHeight - r.bottom + const openUp = spaceBelow < ROW_MENU_MAX_H && r.top > spaceBelow + return { + position: 'fixed', + right: Math.max(8, window.innerWidth - r.right), + ...(openUp ? { bottom: window.innerHeight - r.top + 4 } : { top: r.bottom + 4 }), + zIndex: 100, + } +} + function MenuItem({ icon, label, onClick, danger }: { icon: React.ReactNode; label: string; onClick: () => void; danger?: boolean }) { return (
@@ -1106,7 +1382,7 @@ function PermLabel({ perm, t }: { perm: string; t: T }) { function PluginDetailModal({ item, installed, busy, onInstall, onClose, t, locale }: { item: RegistryItem; installed: boolean; busy: string | null - onInstall: (id: string) => void; onClose: () => void; t: T; locale: string + onInstall: (id: string, version?: string) => void; onClose: () => void; t: T; locale: string }) { const [detail, setDetail] = useState(null) const [failed, setFailed] = useState(false) @@ -1124,6 +1400,9 @@ function PluginDetailModal({ item, installed, busy, onInstall, onClose, t, local const repoUrl = `https://github.com/${item.repo}` const homepage = item.homepage && /^https?:\/\//i.test(item.homepage) && item.homepage !== repoUrl ? item.homepage : null const sizeKb = detail?.size ? Math.max(1, Math.round(detail.size / 1024)) : null + // The detail fetch carries the same compat verdict as the browse list; prefer it once + // it lands (it is keyed to the same entry) and fall back to the grid item until then. + const offer = installOffer(detail ?? item, t) return (
@@ -1145,15 +1424,24 @@ function PluginDetailModal({ item, installed, busy, onInstall, onClose, t, local

{item.author}{item.latest ? ` · v${item.latest}` : ''}

-

{item.description}

{failed &&

{t('admin.plugins.detailError')}

} + {/* The reason the button is blocked (or offering an older version) — a tooltip + alone would leave a touch user with a dead button and no explanation. */} + {offer.title && !installed && ( +

+ {offer.title} +

+ )} {manifest && (
@@ -1220,7 +1508,11 @@ function PluginDetailModal({ item, installed, busy, onInstall, onClose, t, local
{item.latest && } {sizeKb && } - {item.minTrekVersion && } + {/* The range, not just its lower bound: "TREK 3.2.0+" reads as "and anything + newer", which is exactly the claim a `<4.0.0` upper bound denies. */} + {(item.trek || item.minTrekVersion) && ( + + )} {item.reviewedAt && } {typeof item.downloadCount === 'number' && item.downloadCount > 0 && ( @@ -1254,8 +1546,101 @@ function Meta({ k, v }: { k: string; v: string }) { return
{k}
{v}
} -function UpdateConsentDialog({ data, t, onApprove, onLater }: { +/** + * A signature check refused an install/update. + * + * The override lives here, and it is scoped to exactly one code. A rotated key has a + * benign explanation — the author rotated it, or lost it and made a new one. A signature + * that does NOT verify does not: it means the bytes are not what the author signed, which + * is corruption or an attack, and there is no story where the right answer is "let the + * admin wave it through". So SIGNATURE_INVALID / _MISSING / _INCOMPLETE get a clear + * explanation and no override button AT ALL — not a disabled one, not one behind a + * confirm. The absence of an escape hatch is the feature. + * + * (The server enforces this too — it re-derives the condition and refuses anything but a + * changed key. This dialog is the convenience, not the control.) + */ +function SignatureBlockDialog({ data, entry, busy, t, onRetrust, onClose }: { + data: { subject: SigSubject; code: string; detail: string | null } + entry: RegistryItem | undefined + busy: boolean; t: T + onRetrust: (version: string, publicKey: string) => void + onClose: () => void +}) { + const canRetrust = data.code === RETRUSTABLE + const newKey = entry?.authorPublicKey ?? null + const version = entry?.latest ?? null + // Only offer the override when we actually hold the new key + version to send: the + // request carries both, and the server compares the key exactly. + const offerRetrust = canRetrust && !!newKey && !!version + + const bodyKey = data.code === RETRUSTABLE ? 'admin.plugins.sig.keyChangedBody' + : data.code === 'SIGNATURE_MISSING' ? 'admin.plugins.sig.missingBody' + : data.code === 'SIGNATURE_INCOMPLETE' ? 'admin.plugins.sig.incompleteBody' + : 'admin.plugins.sig.invalidBody' + + return ( +
+
e.stopPropagation()}> +
+
+
+

{t('admin.plugins.sig.title', { name: data.subject.name })}

+

{t(bodyKey as never)}

+
+
+
+ {/* Fingerprints, not full keys: these exist to be COMPARED by a human — read the + new one back to the author over the phone. The full key travels in the request. */} + {canRetrust && ( +
+ + +

{t('admin.plugins.sig.confirmOutOfBand')}

+
+ )} + {!canRetrust && data.detail && ( +

{data.detail}

+ )} +
+
+ + {offerRetrust && ( + + )} +
+
+
+ ) +} + +function KeyRow({ label, value, highlight }: { label: string; value: string; highlight?: boolean }) { + return ( +
+ {label} + {value} +
+ ) +} + +/** Client-side twin of the server's fingerprint: head…tail of the base64 payload. Display + * only — every equality check that matters happens server-side against the full key. */ +function fingerprint(key: string | null): string | null { + if (!key) return null + const payload = key.trim().split(/\r?\n/).map(l => l.trim()).filter(l => l && !l.startsWith('untrusted comment')).pop() + if (!payload) return null + return payload.length <= 20 ? payload : `${payload.slice(0, 8)}…${payload.slice(-8)}` +} + +function UpdateConsentDialog({ data, unsigned, t, onApprove, onLater }: { data: { plugin: PluginRow; version: string; newPermissions: string[]; newEgress: string[] } + unsigned: boolean t: T; onApprove: () => void; onLater: () => void }) { return ( @@ -1269,6 +1654,15 @@ function UpdateConsentDialog({ data, t, onApprove, onLater }: {
+ {/* The admin is about to widen what this code may do — so say, right here, that + nothing ties this code to its author. One line, no checkbox, no extra click: + this informs, it does not block. */} + {unsigned && ( +

+ + {t('admin.plugins.sig.consentUnsigned')} +

+ )} {data.newPermissions.length > 0 && (

{t('admin.plugins.updateNewPermissions')}

@@ -1358,6 +1752,7 @@ function SecurityInfo({ t }: { t: T }) { ['admin.plugins.security.limitsTitle', 'admin.plugins.security.limitsBody'], ['admin.plugins.security.worstTitle', 'admin.plugins.security.worstBody'], ['admin.plugins.security.reviewedTitle', 'admin.plugins.security.reviewedBody'], + ['admin.plugins.security.signedTitle', 'admin.plugins.security.signedBody'], ['admin.plugins.security.trustTitle', 'admin.plugins.security.trustBody'], ] return ( diff --git a/client/src/components/Admin/GitHubPanel.tsx b/client/src/components/Admin/GitHubPanel.tsx index 4ea99b0de..26774989e 100644 --- a/client/src/components/Admin/GitHubPanel.tsx +++ b/client/src/components/Admin/GitHubPanel.tsx @@ -1,146 +1,187 @@ -import { useState, useEffect } from 'react' -import { Tag, Calendar, ExternalLink, ChevronDown, ChevronUp, Loader2, Heart, Coffee, Bug, Lightbulb, BookOpen } from 'lucide-react' -import { getLocaleForLanguage, useTranslation } from '../../i18n' -import apiClient from '../../api/client' +import { + BookOpen, + Bug, + Calendar, + ChevronDown, + ChevronUp, + Coffee, + ExternalLink, + Heart, + Lightbulb, + Loader2, + Tag, +} from 'lucide-react'; +import { useEffect, useState } from 'react'; +import apiClient from '../../api/client'; +import { getLocaleForLanguage, useTranslation } from '../../i18n'; -const REPO = 'mauriceboe/TREK' -const PER_PAGE = 10 +const REPO = 'liketrek/TREK'; +const PER_PAGE = 10; interface GithubRelease { - id: number - prerelease: boolean - tag_name: string - name: string | null - body: string | null - published_at: string | null - created_at: string - author: { login: string } | null - [key: string]: unknown + id: number; + prerelease: boolean; + tag_name: string; + name: string | null; + body: string | null; + published_at: string | null; + created_at: string; + author: { login: string } | null; + [key: string]: unknown; } export default function GitHubPanel({ isPrerelease = false }: { isPrerelease?: boolean }) { - const { t, language } = useTranslation() - const [releases, setReleases] = useState([]) - const [loading, setLoading] = useState(true) - const [error, setError] = useState(null) - const [expanded, setExpanded] = useState>({}) - const [page, setPage] = useState(1) - const [hasMore, setHasMore] = useState(true) - const [loadingMore, setLoadingMore] = useState(false) + const { t, language } = useTranslation(); + const [releases, setReleases] = useState([]); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + const [expanded, setExpanded] = useState>({}); + const [page, setPage] = useState(1); + const [hasMore, setHasMore] = useState(true); + const [loadingMore, setLoadingMore] = useState(false); const fetchReleases = async (pageNum = 1, append = false) => { try { - const res = await apiClient.get(`/admin/github-releases`, { params: { per_page: PER_PAGE, page: pageNum } }) - const data = Array.isArray(res.data) ? res.data : [] - setReleases(prev => append ? [...prev, ...data] : data) - setHasMore(data.length === PER_PAGE) + const res = await apiClient.get(`/admin/github-releases`, { params: { per_page: PER_PAGE, page: pageNum } }); + const data = Array.isArray(res.data) ? res.data : []; + setReleases((prev) => (append ? [...prev, ...data] : data)); + setHasMore(data.length === PER_PAGE); } catch (err: unknown) { - setError(err instanceof Error ? err.message : 'Unknown error') + setError(err instanceof Error ? err.message : 'Unknown error'); } - } + }; useEffect(() => { - setLoading(true) - fetchReleases(1).finally(() => setLoading(false)) - }, []) + setLoading(true); + fetchReleases(1).finally(() => setLoading(false)); + }, []); const handleLoadMore = async () => { - const next = page + 1 - setLoadingMore(true) - await fetchReleases(next, true) - setPage(next) - setLoadingMore(false) - } + const next = page + 1; + setLoadingMore(true); + await fetchReleases(next, true); + setPage(next); + setLoadingMore(false); + }; const toggleExpand = (id) => { - setExpanded(prev => ({ ...prev, [id]: !prev[id] })) - } + setExpanded((prev) => ({ ...prev, [id]: !prev[id] })); + }; const formatDate = (dateStr) => { - const d = new Date(dateStr) - return d.toLocaleDateString(getLocaleForLanguage(language), { day: 'numeric', month: 'short', year: 'numeric' }) - } + const d = new Date(dateStr); + return d.toLocaleDateString(getLocaleForLanguage(language), { day: 'numeric', month: 'short', year: 'numeric' }); + }; // Simple markdown-to-html for release notes (handles headers, bold, lists, links) const renderBody = (body) => { - if (!body) return null - const lines = body.split('\n') - const elements = [] - let listItems = [] + if (!body) return null; + const lines = body.split('\n'); + const elements = []; + let listItems = []; const flushList = () => { if (listItems.length > 0) { elements.push( -
    +
      {listItems.map((item, i) => (
    • - +
    • ))}
    - ) - listItems = [] + ); + listItems = []; } - } + }; - const escapeHtml = (str) => str.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"') + const escapeHtml = (str) => + str.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); const inlineFormat = (text) => { return escapeHtml(text) .replace(/\*\*(.+?)\*\*/g, '$1') - .replace(/`(.+?)`/g, '$1') + .replace( + /`(.+?)`/g, + '$1' + ) .replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_, label, url) => { - const safeUrl = url.startsWith('http://') || url.startsWith('https://') ? url : '#' - return `${label}` - }) - } + const safeUrl = url.startsWith('http://') || url.startsWith('https://') ? url : '#'; + return `${label}`; + }); + }; for (const line of lines) { - const trimmed = line.trim() - if (!trimmed) { flushList(); continue } + const trimmed = line.trim(); + if (!trimmed) { + flushList(); + continue; + } if (trimmed.startsWith('### ')) { - flushList() + flushList(); elements.push( -

    +

    {trimmed.slice(4)}

    - ) + ); } else if (trimmed.startsWith('## ')) { - flushList() + flushList(); elements.push( -

    +

    {trimmed.slice(3)}

    - ) + ); } else if (/^[-*] /.test(trimmed)) { - listItems.push(trimmed.slice(2)) + listItems.push(trimmed.slice(2)); } else { - flushList() + flushList(); elements.push( -

    - ) + ); } } - flushList() - return elements - } + flushList(); + return elements; + }; return (

    {/* Support cards */} -
    +
    { e.currentTarget.style.borderColor = '#ff5e5b'; e.currentTarget.style.boxShadow = '0 0 0 1px #ff5e5b22' }} - onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--border-primary)'; e.currentTarget.style.boxShadow = 'none' }} + className="flex items-center gap-4 overflow-hidden rounded-xl border border-edge bg-surface-card px-5 py-4 no-underline transition-[border-color,box-shadow] duration-200 ease-[cubic-bezier(0.23,1,0.32,1)]" + onMouseEnter={(e) => { + e.currentTarget.style.borderColor = '#ff5e5b'; + e.currentTarget.style.boxShadow = '0 0 0 1px #ff5e5b22'; + }} + onMouseLeave={(e) => { + e.currentTarget.style.borderColor = 'var(--border-primary)'; + e.currentTarget.style.boxShadow = 'none'; + }} > -
    +
    @@ -153,11 +194,28 @@ export default function GitHubPanel({ isPrerelease = false }: { isPrerelease?: b href="https://buymeacoffee.com/mauriceboe" target="_blank" rel="noopener noreferrer" - className="rounded-xl border overflow-hidden flex items-center gap-4 px-5 py-4 transition-[border-color,box-shadow] duration-200 ease-[cubic-bezier(0.23,1,0.32,1)] bg-surface-card border-edge no-underline" - onMouseEnter={e => { e.currentTarget.style.borderColor = '#ffdd00'; e.currentTarget.style.boxShadow = '0 0 0 1px #ffdd0022' }} - onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--border-primary)'; e.currentTarget.style.boxShadow = 'none' }} + className="flex items-center gap-4 overflow-hidden rounded-xl border border-edge bg-surface-card px-5 py-4 no-underline transition-[border-color,box-shadow] duration-200 ease-[cubic-bezier(0.23,1,0.32,1)]" + onMouseEnter={(e) => { + e.currentTarget.style.borderColor = '#ffdd00'; + e.currentTarget.style.boxShadow = '0 0 0 1px #ffdd0022'; + }} + onMouseLeave={(e) => { + e.currentTarget.style.borderColor = 'var(--border-primary)'; + e.currentTarget.style.boxShadow = 'none'; + }} > -
    +
    @@ -170,12 +228,31 @@ export default function GitHubPanel({ isPrerelease = false }: { isPrerelease?: b href="https://discord.gg/NhZBDSd4qW" target="_blank" rel="noopener noreferrer" - className="rounded-xl border overflow-hidden flex items-center gap-4 px-5 py-4 transition-[border-color,box-shadow] duration-200 ease-[cubic-bezier(0.23,1,0.32,1)] bg-surface-card border-edge no-underline" - onMouseEnter={e => { e.currentTarget.style.borderColor = '#5865F2'; e.currentTarget.style.boxShadow = '0 0 0 1px #5865F222' }} - onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--border-primary)'; e.currentTarget.style.boxShadow = 'none' }} + className="flex items-center gap-4 overflow-hidden rounded-xl border border-edge bg-surface-card px-5 py-4 no-underline transition-[border-color,box-shadow] duration-200 ease-[cubic-bezier(0.23,1,0.32,1)]" + onMouseEnter={(e) => { + e.currentTarget.style.borderColor = '#5865F2'; + e.currentTarget.style.boxShadow = '0 0 0 1px #5865F222'; + }} + onMouseLeave={(e) => { + e.currentTarget.style.borderColor = 'var(--border-primary)'; + e.currentTarget.style.boxShadow = 'none'; + }} > -
    - +
    + + +
    -
    +
    { e.currentTarget.style.borderColor = '#ef4444'; e.currentTarget.style.boxShadow = '0 0 0 1px #ef444422' }} - onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--border-primary)'; e.currentTarget.style.boxShadow = 'none' }} + className="flex items-center gap-4 overflow-hidden rounded-xl border border-edge bg-surface-card px-5 py-4 no-underline transition-[border-color,box-shadow] duration-200 ease-[cubic-bezier(0.23,1,0.32,1)]" + onMouseEnter={(e) => { + e.currentTarget.style.borderColor = '#ef4444'; + e.currentTarget.style.boxShadow = '0 0 0 1px #ef444422'; + }} + onMouseLeave={(e) => { + e.currentTarget.style.borderColor = 'var(--border-primary)'; + e.currentTarget.style.boxShadow = 'none'; + }} > -
    +
    @@ -204,14 +298,31 @@ export default function GitHubPanel({ isPrerelease = false }: { isPrerelease?: b { e.currentTarget.style.borderColor = '#f59e0b'; e.currentTarget.style.boxShadow = '0 0 0 1px #f59e0b22' }} - onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--border-primary)'; e.currentTarget.style.boxShadow = 'none' }} + className="flex items-center gap-4 overflow-hidden rounded-xl border border-edge bg-surface-card px-5 py-4 no-underline transition-[border-color,box-shadow] duration-200 ease-[cubic-bezier(0.23,1,0.32,1)]" + onMouseEnter={(e) => { + e.currentTarget.style.borderColor = '#f59e0b'; + e.currentTarget.style.boxShadow = '0 0 0 1px #f59e0b22'; + }} + onMouseLeave={(e) => { + e.currentTarget.style.borderColor = 'var(--border-primary)'; + e.currentTarget.style.boxShadow = 'none'; + }} > -
    +
    @@ -221,14 +332,31 @@ export default function GitHubPanel({ isPrerelease = false }: { isPrerelease?: b { e.currentTarget.style.borderColor = '#6366f1'; e.currentTarget.style.boxShadow = '0 0 0 1px #6366f122' }} - onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--border-primary)'; e.currentTarget.style.boxShadow = 'none' }} + className="flex items-center gap-4 overflow-hidden rounded-xl border border-edge bg-surface-card px-5 py-4 no-underline transition-[border-color,box-shadow] duration-200 ease-[cubic-bezier(0.23,1,0.32,1)]" + onMouseEnter={(e) => { + e.currentTarget.style.borderColor = '#6366f1'; + e.currentTarget.style.boxShadow = '0 0 0 1px #6366f122'; + }} + onMouseLeave={(e) => { + e.currentTarget.style.borderColor = 'var(--border-primary)'; + e.currentTarget.style.boxShadow = 'none'; + }} > -
    +
    @@ -241,137 +369,134 @@ export default function GitHubPanel({ isPrerelease = false }: { isPrerelease?: b {/* Loading / Error / Releases */} {loading ? ( -
    -
    - +
    +
    +
    ) : error ? ( -
    +

    {t('admin.github.error')}

    -

    {error}

    +

    {error}

    ) : ( -
    -
    -
    -

    {t('admin.github.title')}

    -

    {t('admin.github.subtitle').replace('{repo}', REPO)}

    +
    - {/* Timeline */} -
    -
    - {/* Timeline line */} -
    + {/* Timeline */} +
    +
    + {/* Timeline line */} +
    -
    - {(isPrerelease ? releases : releases.filter(r => !r.prerelease)).map((release, idx) => { - const isLatest = idx === 0 - const isExpanded = expanded[release.id] +
    + {(isPrerelease ? releases : releases.filter((r) => !r.prerelease)).map((release, idx) => { + const isLatest = idx === 0; + const isExpanded = expanded[release.id]; - return ( -
    - {/* Timeline dot */} -
    - -
    - - {/* Release content */} -
    -
    - - {release.tag_name} - - {isLatest && ( - - {t('admin.github.latest')} - - )} - {release.prerelease && ( - - {t('admin.github.prerelease')} - - )} + return ( +
    + {/* Timeline dot */} +
    +
    - {release.name && release.name !== release.tag_name && ( -

    - {release.name} -

    - )} - -
    - - - {formatDate(release.published_at || release.created_at)} - - {release.author && ( - - {t('admin.github.by')} {release.author.login} - - )} -
    - - {/* Expandable body */} - {release.body && ( -
    - - - {isExpanded && ( -
    - {renderBody(release.body)} -
    + {/* Release content */} +
    +
    + {release.tag_name} + {isLatest && ( + + {t('admin.github.latest')} + + )} + {release.prerelease && ( + + {t('admin.github.prerelease')} + )}
    - )} -
    -
    - ) - })} -
    -
    - {/* Load more */} - {hasMore && ( -
    - + {release.name && release.name !== release.tag_name && ( +

    {release.name}

    + )} + +
    + + + {formatDate(release.published_at || release.created_at)} + + {release.author && ( + + {t('admin.github.by')} {release.author.login} + + )} +
    + + {/* Expandable body */} + {release.body && ( +
    + + + {isExpanded && ( +
    {renderBody(release.body)}
    + )} +
    + )} +
    +
    + ); + })} +
    - )} + + {/* Load more */} + {hasMore && ( +
    + +
    + )} +
    -
    )}
    - ) + ); } diff --git a/client/src/components/BackgroundTasks/BackgroundTasksWidget.test.tsx b/client/src/components/BackgroundTasks/BackgroundTasksWidget.test.tsx new file mode 100644 index 000000000..3883a5f5e --- /dev/null +++ b/client/src/components/BackgroundTasks/BackgroundTasksWidget.test.tsx @@ -0,0 +1,45 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { screen } from '@testing-library/react' +import { render } from '../../../tests/helpers/render' +import { useBackgroundTasksStore, type BackgroundImportTask } from '../../store/backgroundTasksStore' +import BackgroundTasksWidget from './BackgroundTasksWidget' + +vi.mock('../../api/websocket', () => ({ addListener: vi.fn(), removeListener: vi.fn() })) +vi.mock('../../api/client', () => ({ + // Keep the rehydrate/poll backstops pending so the seeded state is what renders. + reservationsApi: { importJobStatus: vi.fn(() => new Promise(() => {})) }, +})) + +const task = (overrides: Partial = {}): BackgroundImportTask => ({ + id: 'j1', + tripId: 't1', + label: 'voucher.pdf', + status: 'done', + done: 0, + total: 1, + items: [], + warnings: [], + ...overrides, +}) + +beforeEach(() => { + vi.clearAllMocks() + useBackgroundTasksStore.setState({ tasks: [] }) +}) + +describe('BackgroundTasksWidget', () => { + it('shows the warnings when a finished job produced no items', () => { + const warning = 'voucher.pdf: AI parsing failed — LLM request failed (400): response_format unsupported' + useBackgroundTasksStore.setState({ tasks: [task({ warnings: [warning] })] }) + render() + expect(screen.getByText('No reservations could be extracted from the uploaded files.')).toBeInTheDocument() + expect(screen.getByText(warning)).toBeInTheDocument() + }) + + it('shows only the empty-preview note when there are no warnings', () => { + useBackgroundTasksStore.setState({ tasks: [task()] }) + render() + expect(screen.getByText('No reservations could be extracted from the uploaded files.')).toBeInTheDocument() + expect(screen.queryByText(/AI parsing failed/)).not.toBeInTheDocument() + }) +}) diff --git a/client/src/components/BackgroundTasks/BackgroundTasksWidget.tsx b/client/src/components/BackgroundTasks/BackgroundTasksWidget.tsx index b53a3e57a..977833e4e 100644 --- a/client/src/components/BackgroundTasks/BackgroundTasksWidget.tsx +++ b/client/src/components/BackgroundTasks/BackgroundTasksWidget.tsx @@ -136,7 +136,14 @@ export default function BackgroundTasksWidget() { {t('common.import')} ) : ( -
    {t('reservations.import.previewEmpty')}
    +
    + {t('reservations.import.previewEmpty')} + {(task.warnings?.length ?? 0) > 0 && ( +
    + {task.warnings!.join('\n')} +
    + )} +
    ) )} diff --git a/client/src/components/Budget/CostsPanel.helpers.test.ts b/client/src/components/Budget/CostsPanel.helpers.test.ts new file mode 100644 index 000000000..80ac00812 --- /dev/null +++ b/client/src/components/Budget/CostsPanel.helpers.test.ts @@ -0,0 +1,78 @@ +import { describe, it, expect } from 'vitest' +import { splitCents, payerSum, payersBalanced, rebalancePayers } from './CostsPanel.helpers' + +describe('splitCents', () => { + it('splits evenly when it divides cleanly', () => { + expect(splitCents(90, 3)).toEqual([30, 30, 30]) + }) + + it('distributes the remainder cents so the parts sum back exactly', () => { + const parts = splitCents(100.01, 3) + expect(parts).toEqual([33.34, 33.34, 33.33]) + expect(parts.reduce((a, b) => a + b, 0)).toBeCloseTo(100.01, 2) + }) + + it('returns an empty list for a non-positive count', () => { + expect(splitCents(50, 0)).toEqual([]) + }) + + it('floors a negative amount at zero rather than inventing debt', () => { + expect(splitCents(-10, 2)).toEqual([0, 0]) + }) +}) + +describe('payerSum', () => { + it('sums only the selected payers', () => { + const amounts = { 1: '45', 2: '45', 3: '99' } + expect(payerSum(amounts, new Set([1, 2]))).toBeCloseTo(90, 2) + }) + + it('treats blank and unparseable amounts as zero', () => { + expect(payerSum({ 1: '', 2: 'abc' }, new Set([1, 2]))).toBe(0) + }) +}) + +describe('payersBalanced', () => { + it('is true when the payer amounts add up to the total', () => { + expect(payersBalanced({ 1: '45', 2: '45' }, new Set([1, 2]), 90)).toBe(true) + }) + + it('is false when they do not', () => { + expect(payersBalanced({ 1: '45', 2: '40' }, new Set([1, 2]), 90)).toBe(false) + }) + + it('compares to the cent, tolerating float dust', () => { + expect(payersBalanced({ 1: '33.34', 2: '33.34', 3: '33.33' }, new Set([1, 2, 3]), 100.01)).toBe(true) + }) +}) + +describe('rebalancePayers', () => { + it('spreads the total across payers when none are pinned', () => { + const next = rebalancePayers({}, new Set(), new Set([1, 2]), 90) + expect(next).toEqual({ 1: '45.00', 2: '45.00' }) + }) + + it('leaves pinned payers alone and lets the rest absorb the remainder', () => { + // Alice pinned at 70 of a 100 bill → Bob must absorb 30. + const next = rebalancePayers({ 1: '70' }, new Set([1]), new Set([1, 2]), 100) + expect(next[1]).toBe('70') + expect(next[2]).toBe('30.00') + }) + + it('returns the amounts untouched when every payer is pinned', () => { + const amounts = { 1: '70', 2: '20' } + const next = rebalancePayers(amounts, new Set([1, 2]), new Set([1, 2]), 100) + expect(next).toEqual(amounts) + }) + + it('blanks a free payer whose share works out to zero', () => { + // Alice pinned at the full total → Bob is a payer with nothing left to pay. + const next = rebalancePayers({ 1: '100' }, new Set([1]), new Set([1, 2]), 100) + expect(next[2]).toBe('') + }) + + it('keeps the result balanced after rebalancing', () => { + const next = rebalancePayers({ 1: '33.33' }, new Set([1]), new Set([1, 2, 3]), 100) + expect(payersBalanced(next, new Set([1, 2, 3]), 100)).toBe(true) + }) +}) diff --git a/client/src/components/Budget/CostsPanel.helpers.ts b/client/src/components/Budget/CostsPanel.helpers.ts new file mode 100644 index 000000000..ae297b9f8 --- /dev/null +++ b/client/src/components/Budget/CostsPanel.helpers.ts @@ -0,0 +1,53 @@ +/** + * Pure payer math for the Costs expense modal. + * + * An expense's payers must always sum to its total. The server re-derives + * budget_items.total_price from the payer sum (budgetService.createItem), so an + * unbalanced payer list would silently rewrite the expense total — and in custom + * split mode the member debits, balanced against the old total, would stop + * cancelling the payer credits. rebalancePayers keeps the payers the user hasn't + * touched absorbing the remainder as they type; payersBalanced gates the save. + * + * Amounts are the raw input strings, parsed on use (same as customAmounts). + */ + +/** Spread `amount` across `n` payers in whole cents so the parts sum back exactly. */ +export function splitCents(amount: number, n: number): number[] { + if (n <= 0) return [] + const cents = Math.max(0, Math.round(amount * 100)) + const base = Math.floor(cents / n) + const rem = cents - base * n + return Array.from({ length: n }, (_, i) => (base + (i < rem ? 1 : 0)) / 100) +} + +/** Sum the amounts of the selected payers. */ +export function payerSum(amounts: Record, ids: Set): number { + return [...ids].reduce((a, id) => a + (parseFloat(amounts[id]) || 0), 0) +} + +/** True when the payer amounts add up to the expense total, to the cent. */ +export function payersBalanced(amounts: Record, ids: Set, total: number): boolean { + return Math.round(payerSum(amounts, ids) * 100) === Math.round(total * 100) +} + +/** + * Recompute the payers the user has not explicitly edited (everyone not in + * `pinned`) so the whole list sums to `total`. Pinned amounts are left as typed. + */ +export function rebalancePayers( + amounts: Record, + pinned: Set, + ids: Set, + total: number, +): Record { + const all = [...ids] + const free = all.filter(id => !pinned.has(id)) + if (free.length === 0) return amounts + const pinnedSum = all + .filter(id => pinned.has(id)) + .reduce((a, id) => a + (parseFloat(amounts[id]) || 0), 0) + const shares = splitCents(total - pinnedSum, free.length) + const next = { ...amounts } + free.forEach((id, i) => { next[id] = shares[i] ? shares[i].toFixed(2) : '' }) + return next +} diff --git a/client/src/components/Budget/CostsPanel.test.tsx b/client/src/components/Budget/CostsPanel.test.tsx index 634b0384f..9ebec4544 100644 --- a/client/src/components/Budget/CostsPanel.test.tsx +++ b/client/src/components/Budget/CostsPanel.test.tsx @@ -222,6 +222,166 @@ describe('CostsPanel — settlements in the ledger', () => { expect(posted!.payers).toEqual([]) }) + it('keeps "no one paid yet" when reopening a payer-less expense (#1533)', async () => { + seedStore(useAuthStore, { user: buildUser({ id: 1, username: 'alice' }), isAuthenticated: true }) + let put: Record | null = null + const item = { + ...buildBudgetItem({ trip_id: 1, category: 'food', name: 'Hotel' }), + id: 5, + total_price: 120, + payers: [], + members: [{ user_id: 1, username: 'alice', paid: 0 }, { user_id: 2, username: 'bob', paid: 0 }], + } + server.use( + http.get('/api/trips/1/budget', () => HttpResponse.json({ items: [item] })), + http.get('/api/trips/1/budget/settlement', () => HttpResponse.json({ balances: [], flows: [], settlements: [] })), + http.put('/api/trips/1/budget/5', async ({ request }) => { + put = await request.json() as Record + return HttpResponse.json({ item }) + }), + ) + const { default: userEvent } = await import('@testing-library/user-event') + const user = userEvent.setup() + render() + + await screen.findByText('Hotel') + await user.click(screen.getByTitle('Edit')) + + // Nobody paid this expense — reopening it must not silently reselect "You". + expect(await screen.findByRole('button', { name: 'No one paid yet' })).toBeInTheDocument() + + // …and saving an untouched edit must not assign the current user as payer. + await user.click(screen.getByRole('button', { name: 'Save' })) + await waitFor(() => expect(put).toBeTruthy()) + expect(put!.payers).toEqual([]) + }) + + it('still defaults a brand-new expense to "You" as the payer', async () => { + seedStore(useAuthStore, { user: buildUser({ id: 1, username: 'alice' }), isAuthenticated: true }) + server.use( + http.get('/api/trips/1/budget', () => HttpResponse.json({ items: [] })), + http.get('/api/trips/1/budget/settlement', () => HttpResponse.json({ balances: [], flows: [], settlements: [] })), + ) + const { default: userEvent } = await import('@testing-library/user-event') + const user = userEvent.setup() + render() + + await user.click(await screen.findByRole('button', { name: 'Add expense' })) + expect(await screen.findByRole('button', { name: 'You' })).toBeInTheDocument() + }) + + // ── Multi-payer (#1426 regression) ───────────────────────────────────────── + // 3.2.0 collapsed payers[] to a single payer, so a bill fronted by two people + // credited all of it to one and skewed settle-up. The ledger always supported N + // payers; only the form could no longer send them. + + it('records an expense paid by two people with their own amounts', async () => { + seedStore(useAuthStore, { user: buildUser({ id: 1, username: 'alice' }), isAuthenticated: true }) + let posted: Record | null = null + server.use( + http.get('/api/trips/1/budget', () => HttpResponse.json({ items: [] })), + http.get('/api/trips/1/budget/settlement', () => HttpResponse.json({ balances: [], flows: [], settlements: [] })), + http.post('/api/trips/1/budget', async ({ request }) => { + posted = await request.json() as Record + return HttpResponse.json({ item: { ...buildBudgetItem({ trip_id: 1, name: 'Dinner' }), id: 11 } }) + }), + ) + const { default: userEvent } = await import('@testing-library/user-event') + const user = userEvent.setup() + render() + + await user.click(await screen.findByRole('button', { name: 'Add expense' })) + await user.type(await screen.findByPlaceholderText('e.g. Dinner, souvenirs, gas…'), 'Dinner') + await user.type(screen.getAllByPlaceholderText('0.00')[0], '90') + + await user.click(screen.getByRole('button', { name: 'Multiple people paid' })) + + // Alice (me) is seeded as the sole payer; including Bob rebalances to 45/45. + await user.click(screen.getAllByTestId('payer-toggle')[1]) + expect(screen.getAllByTestId('payer-amount').map(i => (i as HTMLInputElement).value)) + .toEqual(['45.00', '45.00']) + + const addBtns = screen.getAllByRole('button', { name: 'Add expense' }) + await user.click(addBtns[addBtns.length - 1]) + + await waitFor(() => expect(posted).toBeTruthy()) + expect(posted!.total_price).toBe(90) + expect(posted!.payers).toEqual(expect.arrayContaining([ + { user_id: 1, amount: 45 }, + { user_id: 2, amount: 45 }, + ])) + expect(posted!.payers).toHaveLength(2) + }) + + it('blocks saving when the payer amounts do not add up to the total', async () => { + seedStore(useAuthStore, { user: buildUser({ id: 1, username: 'alice' }), isAuthenticated: true }) + let posted: Record | null = null + server.use( + http.get('/api/trips/1/budget', () => HttpResponse.json({ items: [] })), + http.get('/api/trips/1/budget/settlement', () => HttpResponse.json({ balances: [], flows: [], settlements: [] })), + http.post('/api/trips/1/budget', async ({ request }) => { + posted = await request.json() as Record + return HttpResponse.json({ item: buildBudgetItem({ trip_id: 1, name: 'Dinner' }) }) + }), + ) + const { default: userEvent } = await import('@testing-library/user-event') + const user = userEvent.setup() + render() + + await user.click(await screen.findByRole('button', { name: 'Add expense' })) + await user.type(await screen.findByPlaceholderText('e.g. Dinner, souvenirs, gas…'), 'Dinner') + await user.type(screen.getAllByPlaceholderText('0.00')[0], '90') + await user.click(screen.getByRole('button', { name: 'Multiple people paid' })) + await user.click(screen.getAllByTestId('payer-toggle')[1]) + + // Pin both payers at 20 of a 90 bill, so nobody is left to absorb the rest. + const amounts = () => screen.getAllByTestId('payer-amount') as HTMLInputElement[] + await user.clear(amounts()[0]) + await user.type(amounts()[0], '20') + await user.clear(amounts()[1]) + await user.type(amounts()[1], '20') + + // An unbalanced payer list would make the server re-derive total_price as 40. + expect(screen.getByText(/must add up to/i)).toBeInTheDocument() + const addBtns = screen.getAllByRole('button', { name: 'Add expense' }) + expect(addBtns[addBtns.length - 1]).toBeDisabled() + expect(posted).toBeNull() + }) + + it('reopens a two-payer expense with both payers intact', async () => { + seedStore(useAuthStore, { user: buildUser({ id: 1, username: 'alice' }), isAuthenticated: true }) + let put: Record | null = null + const item = { + ...buildBudgetItem({ trip_id: 1, category: 'food', name: 'Dinner' }), + id: 7, + total_price: 90, + payers: [{ user_id: 1, amount: 45, username: 'alice' }, { user_id: 2, amount: 45, username: 'bob' }], + members: [{ user_id: 1, username: 'alice', paid: 0 }, { user_id: 2, username: 'bob', paid: 0 }], + } + server.use( + http.get('/api/trips/1/budget', () => HttpResponse.json({ items: [item] })), + http.get('/api/trips/1/budget/settlement', () => HttpResponse.json({ balances: [], flows: [], settlements: [] })), + http.put('/api/trips/1/budget/7', async ({ request }) => { + put = await request.json() as Record + return HttpResponse.json({ item }) + }), + ) + const { default: userEvent } = await import('@testing-library/user-event') + const user = userEvent.setup() + render() + + await screen.findByText('Dinner') + await user.click(screen.getByTitle('Edit')) + + // Loading used to be payers.find(...), which silently dropped the second payer. + const amounts = await screen.findAllByTestId('payer-amount') + expect(amounts.map(i => (i as HTMLInputElement).value)).toEqual(['45', '45']) + + await user.click(screen.getByRole('button', { name: 'Save' })) + await waitFor(() => expect(put).toBeTruthy()) + expect(put!.payers).toHaveLength(2) + }) + it('exports the expenses as a CSV download (#1500)', async () => { // Display in the trip's own currency so FX conversion is an identity. seedStore(useSettingsStore, { settings: { ...useSettingsStore.getState().settings, default_currency: 'EUR' } }) @@ -305,4 +465,102 @@ describe('CostsPanel — settlements in the ledger', () => { ])) expect(posted!.note).toContain('TICKETJSON:') }) + + // ── Display currency ─────────────────────────────────────────────────────── + + it('shows amounts in the trip currency when the user has no display currency set', async () => { + // No personal preference → the trip's own currency wins, instead of a hardcoded one. + seedStore(useSettingsStore, { settings: { ...useSettingsStore.getState().settings, default_currency: '' } }) + seedStore(useTripStore, { trip: buildTrip({ id: 1, currency: 'JPY' }) }) + const item = { ...buildBudgetItem({ trip_id: 1, category: 'food', name: 'Sushi' }), total_price: 3000, currency: 'JPY', payers: [], members: [{ user_id: 1, username: 'alice', paid: 0 }] } + server.use( + http.get('/api/trips/1/budget', () => HttpResponse.json({ items: [item] })), + http.get('/api/trips/1/budget/settlement', () => HttpResponse.json({ balances: [], flows: [], settlements: [] })), + ) + render() + + await screen.findByText('Sushi') + const card = screen.getByText('Total trip spend').closest('div[style*="border-radius: 22"]') + // Yen, unconverted and with JPY's zero decimals — not a euro/dollar default. + expect(card).toHaveTextContent('¥3,000') + }) + + // ── Payment currency ─────────────────────────────────────────────────────── + // A transfer settling a shared bill can be made in any currency, so it carries its + // own rather than being assumed to be in the display one. + + it('records a payment in the display currency by default', async () => { + seedStore(useSettingsStore, { settings: { ...useSettingsStore.getState().settings, default_currency: 'EUR' } }) + let posted: Record | null = null + server.use( + http.get('/api/trips/1/budget', () => HttpResponse.json({ items: [] })), + http.get('/api/trips/1/budget/settlement', () => HttpResponse.json({ balances: [], flows: [], settlements: [] })), + http.post('/api/trips/1/budget/settlements', async ({ request }) => { + posted = await request.json() as Record + return HttpResponse.json({ settlement: { id: 1, ...posted } }) + }), + ) + const { default: userEvent } = await import('@testing-library/user-event') + const user = userEvent.setup() + render() + + await user.click(await screen.findByRole('button', { name: 'Add payment' })) + await user.type(await screen.findByPlaceholderText('0.00'), '25') + const addButtons = screen.getAllByRole('button', { name: 'Add payment' }) + await user.click(addButtons[addButtons.length - 1]) + + await waitFor(() => expect(posted).toMatchObject({ amount: 25, currency: 'EUR' })) + }) + + it('records a payment made in another currency', async () => { + seedStore(useSettingsStore, { settings: { ...useSettingsStore.getState().settings, default_currency: 'EUR' } }) + let posted: Record | null = null + server.use( + http.get('/api/trips/1/budget', () => HttpResponse.json({ items: [] })), + http.get('/api/trips/1/budget/settlement', () => HttpResponse.json({ balances: [], flows: [], settlements: [] })), + http.post('/api/trips/1/budget/settlements', async ({ request }) => { + posted = await request.json() as Record + return HttpResponse.json({ settlement: { id: 1, ...posted } }) + }), + ) + const { default: userEvent } = await import('@testing-library/user-event') + const user = userEvent.setup() + render() + + await user.click(await screen.findByRole('button', { name: 'Add payment' })) + await user.type(await screen.findByPlaceholderText('0.00'), '25') + // Bob paid me back in dollars — the server freezes the USD rate on write. + await user.click(screen.getByText(/^EUR/)) + await user.click(await screen.findByText(/^USD/)) + const addButtons = screen.getAllByRole('button', { name: 'Add payment' }) + await user.click(addButtons[addButtons.length - 1]) + + await waitFor(() => expect(posted).toMatchObject({ amount: 25, currency: 'USD' })) + }) + + it('reopens a foreign-currency payment with its own currency', async () => { + seedStore(useSettingsStore, { settings: { ...useSettingsStore.getState().settings, default_currency: 'EUR' } }) + server.use( + http.get('/api/trips/1/budget', () => HttpResponse.json({ items: [] })), + http.get('/api/trips/1/budget/settlement', () => + HttpResponse.json({ + balances: [], + flows: [], + settlements: [ + { id: 7, trip_id: 1, from_user_id: 2, to_user_id: 1, amount: 30, currency: 'USD', exchange_rate: 1.1, created_at: '2025-06-16 10:00:00', from_username: 'bob', to_username: 'alice' }, + ], + }) + ), + ) + const { default: userEvent } = await import('@testing-library/user-event') + const user = userEvent.setup() + render() + + await screen.findByText('Payment') + await user.click(screen.getByTitle('Edit')) + + // The stored USD amount comes back as-is, not silently reread as euros. + expect((await screen.findByPlaceholderText('0.00') as HTMLInputElement).value).toBe('30') + expect(screen.getByText(/^USD/)).toBeInTheDocument() + }) }) diff --git a/client/src/components/Budget/CostsPanel.tsx b/client/src/components/Budget/CostsPanel.tsx index 08caee73a..715b24a12 100644 --- a/client/src/components/Budget/CostsPanel.tsx +++ b/client/src/components/Budget/CostsPanel.tsx @@ -15,6 +15,7 @@ import Modal from '../shared/Modal' import CustomSelect from '../shared/CustomSelect' import { CustomDatePicker } from '../shared/CustomDateTimePicker' import { SYMBOLS, currenciesWith, SPLIT_COLORS } from './BudgetPanel.constants' +import { payersBalanced, rebalancePayers } from './CostsPanel.helpers' import { COST_CATEGORY_LIST, catMeta } from './costsCategories' import type { BudgetItem } from '../../types' import type { TripMember } from './BudgetPanelMemberChips' @@ -93,6 +94,9 @@ interface Settlement { from_user_id: number to_user_id: number amount: number + // The currency the transfer was entered in. Legacy rows predate it (null) and are + // read as the display currency, which is what the server assumes for them too. + currency?: string | null created_at?: string from_username?: string to_username?: string @@ -774,18 +778,23 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps // A settle-up payment as a ledger row — visually distinct from an expense, with // inline edit + undo (reuses deleteSettlement) so it isn't buried in a modal. function SettlementRow({ s }: { s: Settlement }) { + // Legacy transfers carry no currency and were entered in the display base. + const cur = (s.currency || base).toUpperCase() return (
    -
    {t('costs.payment')}
    +
    + {t('costs.payment')} + {cur !== base && · {fmt(s.amount, cur)} → {fmt(convert(s.amount, cur))}} +
    {personName(s.from_user_id)} → {personName(s.to_user_id)}
    -
    {fmt(s.amount)}
    +
    {fmt(convert(s.amount, cur))}
    {canEdit && (
    @@ -901,9 +910,12 @@ function FlowPills({ ids, lead, Avatar, name }: { ids: number[]; lead: string; A ) } -// Add or edit a settle-up payment (from / to / amount). Reachable inline from the -// ledger row and from a manual "Add payment" button, so recording "I sent money to -// X" works the same whether or not there's an outstanding expense behind it. +// Add or edit a settle-up payment (from / to / amount / currency). Reachable inline +// from the ledger row and from a manual "Add payment" button, so recording "I sent +// money to X" works the same whether or not there's an outstanding expense behind it. +// A transfer can be made in any currency — paying a rouble debt in euros is normal — +// so it carries its own, defaulting to the display currency. The server freezes its +// FX rate on write, the same way an expense's is frozen. function SettlementModal({ tripId, people, me, editing, currency, onClose, onSaved }: { tripId: number; people: TripMember[]; me: number; editing: Settlement | null; currency: string; onClose: () => void; onSaved: () => void }) { @@ -913,6 +925,7 @@ function SettlementModal({ tripId, people, me, editing, currency, onClose, onSav const [fromId, setFromId] = useState(String(editing?.from_user_id ?? me)) const [toId, setToId] = useState(String(editing?.to_user_id ?? otherDefault)) const [amount, setAmount] = useState(editing ? String(editing.amount) : '') + const [cur, setCur] = useState((editing?.currency || currency).toUpperCase()) const [saving, setSaving] = useState(false) const amt = parseFloat(amount) || 0 @@ -922,7 +935,7 @@ function SettlementModal({ tripId, people, me, editing, currency, onClose, onSav const save = async () => { if (!valid) return setSaving(true) - const data = { from_user_id: Number(fromId), to_user_id: Number(toId), amount: amt, currency } + const data = { from_user_id: Number(fromId), to_user_id: Number(toId), amount: amt, currency: cur } try { if (editing) await budgetApi.updateSettlement(tripId, editing.id, data) else await budgetApi.createSettlement(tripId, data) @@ -930,7 +943,6 @@ function SettlementModal({ tripId, people, me, editing, currency, onClose, onSav } catch { toast.error(t('common.unknownError')) } finally { setSaving(false) } } - const inputCls = 'w-full bg-surface-input border border-edge text-content' const labelCls = 'block text-[11px] font-semibold uppercase tracking-[0.08em] text-content-faint mb-[6px]' return ( @@ -950,10 +962,22 @@ function SettlementModal({ tripId, people, me, editing, currency, onClose, onSav setToId(String(v))} options={opts} style={{ width: '100%' }} />
    -
    - - setAmount(e.target.value.replace(',', '.'))} className={inputCls} style={{ borderRadius: 10, padding: '11px 13px', fontSize: 'calc(14px * var(--fs-scale-body, 1))', outline: 'none', fontWeight: 600 }} /> +
    +
    + +
    + {SYMBOLS[cur] || (cur + ' ')} + setAmount(e.target.value.replace(',', '.'))} + className="text-content" style={{ flex: 1, border: 0, background: 'none', outline: 'none', fontSize: 'calc(14px * var(--fs-scale-body, 1))', fontWeight: 600, paddingLeft: 6, width: '100%' }} /> +
    +
    +
    + + setCur(String(v))} searchable + options={currenciesWith(cur).map(c => ({ value: c, label: SYMBOLS[c] ? `${c} ${SYMBOLS[c]}` : c }))} + style={{ width: '100%' }} /> +
    @@ -989,11 +1013,29 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo const [participants, setParticipants] = useState>(() => editing ? new Set((editing.members || []).map(m => m.user_id)) : new Set(people.map(p => p.id))) - // Payer state: 0 represents "Nobody (planning entry)" + // Payer state. An expense can be fronted by several people, each with their own + // amount (budget_item_payers) — a shared card, or "I got this round, you get the + // next". The single-payer dropdown stays the default path; multiPayer swaps in a + // per-person amount editor. 0 represents "Nobody (planning entry)"; on an + // existing expense a missing payer is a deliberate choice, so only a brand-new + // one defaults to me. + const initialPayers = (editing?.payers || []).filter(p => p.amount > 0) + const [payerId, setPayerId] = useState(() => { - const existingPayer = (editing?.payers || []).find(p => p.amount > 0) - return existingPayer ? existingPayer.user_id : me + const existingPayer = initialPayers[0] + if (existingPayer) return existingPayer.user_id + return editing ? 0 : me }) + const [multiPayer, setMultiPayer] = useState(() => initialPayers.length > 1) + const [payerIds, setPayerIds] = useState>(() => new Set(initialPayers.map(p => p.user_id))) + const [payerAmounts, setPayerAmounts] = useState>(() => { + const m: Record = {} + for (const p of initialPayers) m[p.user_id] = String(p.amount) + return m + }) + // Payers the user typed an amount for: rebalance leaves these alone and makes + // the others absorb the remainder. + const [pinnedPayers, setPinnedPayers] = useState>(() => new Set(initialPayers.map(p => p.user_id))) const [splitMode, setSplitMode] = useState<'equally' | 'custom' | 'ticket'>(() => { if (editing?.note && editing.note.startsWith('TICKETJSON:')) { @@ -1064,7 +1106,8 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo }, [totalNum, participants, customAmounts, editing]) const ticketValid = ticketItems.length > 0 && ticketItems.every(item => item.name.trim().length > 0 && (parseFloat(item.price) || 0) > 0 && item.participants.size > 0) - const valid = name.trim().length > 0 && ( + const payersOk = !multiPayer || (payerIds.size > 0 && payersBalanced(payerAmounts, payerIds, totalNum)) + const valid = name.trim().length > 0 && payersOk && ( isTicketMode ? ticketValid : totalNum > 0 && (participants.size === 0 || splitMode === 'equally' || customBalanced) @@ -1074,6 +1117,52 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo setTotal(v.replace(',', '.')) } + // Keep the payer amounts summing to the total as it changes — including in ticket + // mode, where the total is derived from the ticket items rather than typed. + useEffect(() => { + if (!multiPayer) return + setPayerAmounts(prev => rebalancePayers(prev, pinnedPayers, payerIds, totalNum)) + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [totalNum]) + + const enableMultiPayer = () => { + const seed = payerIds.size > 0 ? new Set(payerIds) : new Set([payerId > 0 ? payerId : me]) + const pinned = new Set() + setPayerIds(seed) + setPinnedPayers(pinned) + setPayerAmounts(prev => rebalancePayers(prev, pinned, seed, totalNum)) + setMultiPayer(true) + } + + const disableMultiPayer = () => { + // Collapsing back keeps the first payer; their amount becomes the whole total. + const [first] = [...payerIds] + setPayerId(first ?? me) + setMultiPayer(false) + } + + const togglePayer = (id: number) => { + const nextIds = new Set(payerIds) + const nextPinned = new Set(pinnedPayers) + if (nextIds.has(id)) { + nextIds.delete(id) + nextPinned.delete(id) + } else { + nextIds.add(id) + } + setPayerIds(nextIds) + setPinnedPayers(nextPinned) + setPayerAmounts(prev => rebalancePayers(prev, nextPinned, nextIds, totalNum)) + } + + const onPayerAmountChange = (id: number, v: string) => { + const val = v.replace(',', '.') + const nextPinned = new Set(pinnedPayers) + nextPinned.add(id) + setPinnedPayers(nextPinned) + setPayerAmounts(prev => rebalancePayers({ ...prev, [id]: val }, nextPinned, payerIds, totalNum)) + } + const handleCustomAmountChange = (id: number, val: string) => { val = val.replace(',', '.') if (/^\d*\.?\d{0,2}$/.test(val) || val === '') { @@ -1138,7 +1227,11 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo const save = async () => { if (!valid) return setSaving(true) - const payerList = (payerId > 0 && participants.size > 0) ? [{ user_id: payerId, amount: totalNum }] : [] + const payerList = multiPayer + ? [...payerIds] + .map(id => ({ user_id: id, amount: parseFloat(payerAmounts[id]) || 0 })) + .filter(p => p.amount > 0) + : (payerId > 0 && participants.size > 0) ? [{ user_id: payerId, amount: totalNum }] : [] const memberList = [...participants].map(id => ({ user_id: id, amount: splitMode === 'custom' @@ -1243,13 +1336,66 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
    - - setPayerId(Number(v))} - options={[ - { value: '0', label: t('costs.noOnePaid') || 'Nobody (planning entry)' }, - ...people.map(p => ({ value: String(p.id), label: p.id === me ? t('costs.you') : p.username })) - ]} - style={{ width: '100%' }} /> +
    + + +
    + {!multiPayer ? ( + setPayerId(Number(v))} + options={[ + { value: '0', label: t('costs.noOnePaid') || 'Nobody (planning entry)' }, + ...people.map(p => ({ value: String(p.id), label: p.id === me ? t('costs.you') : p.username })) + ]} + style={{ width: '100%' }} /> + ) : ( + <> +
    + {people.map((p, idx) => { + const on = payerIds.has(p.id) + return ( +
    + + {on ? ( +
    + {sym(currency)} + onPayerAmountChange(p.id, v)} + className="text-content" + style={{ width: '100%', border: 0, background: 'none', outline: 'none', fontSize: 'calc(14px * var(--fs-scale-body, 1))', fontWeight: 600, padding: '8px 0', textAlign: 'right' }} /> +
    + ) : ( + + )} +
    + ) + })} +
    + {!payersOk && ( +
    + {t('costs.payersUnbalanced', { amount: formatMoney(totalNum, currency, locale) })} +
    + )} + + )}
    @@ -1279,16 +1425,16 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
    {ticketItems.map((item, itemIdx) => (
    -
    +
    handleUpdateItemName(item.id, e.target.value)} className="bg-surface-input border border-edge text-content" - style={{ flex: 2, padding: '6px 10px', borderRadius: 8, fontSize: 13, border: '1px solid var(--border-color)', outline: 'none' }} + style={{ minWidth: 0, padding: '6px 10px', borderRadius: 8, fontSize: 13, border: '1px solid var(--border-color)', outline: 'none' }} /> -
    +
    {sym(currency)} 0 - ? [pts[0].lat as number, pts[0].lng as number] - : [48.8566, 2.3522] const tileUrl = dark ? 'https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png' : 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png' @@ -35,8 +32,8 @@ export default function CollectionMap({ places, selectedPlaceId, onOpenPlace, on hoverDisabled onMarkerClick={onOpenPlace} onMapClick={onDeselect ? () => onDeselect() : undefined} - center={center} - zoom={pts.length > 0 ? 6 : 3} + // No center/zoom: the map frames itself on the collection's places at mount, and + // falls back to the world view for a collection with none. tileUrl={tileUrl} fitKey={pts.length} /> diff --git a/client/src/components/Journey/JourneyMapGL.tsx b/client/src/components/Journey/JourneyMapGL.tsx index 3eb4f1cc7..c57d7c327 100644 --- a/client/src/components/Journey/JourneyMapGL.tsx +++ b/client/src/components/Journey/JourneyMapGL.tsx @@ -362,6 +362,9 @@ const JourneyMapGL = forwardRef(function JourneyMapGL antialias: mapboxQuality, } if (!isMapLibre) mapOptions.projection = mapboxQuality ? 'globe' : 'mercator' + // MapLibre 5's around-center mouse rotate ping-pongs near mid-screen (#1545) + // — see MapViewGL. Keep the plain dx-based rotate everywhere. + if (isMapLibre) mapOptions.aroundCenter = false const map = new gl.Map(mapOptions as any) mapRef.current = map diff --git a/client/src/components/Layout/BottomNav.test.tsx b/client/src/components/Layout/BottomNav.test.tsx index 717cf8fca..a4d751f45 100644 --- a/client/src/components/Layout/BottomNav.test.tsx +++ b/client/src/components/Layout/BottomNav.test.tsx @@ -21,6 +21,7 @@ import userEvent from '@testing-library/user-event'; import { useAuthStore } from '../../store/authStore'; import { useSettingsStore } from '../../store/settingsStore'; import { useAddonStore } from '../../store/addonStore'; +import { usePluginStore } from '../../store/pluginStore'; import { resetAllStores, seedStore } from '../../../tests/helpers/store'; import { buildUser, buildSettings } from '../../../tests/helpers/factories'; import BottomNav from './BottomNav'; @@ -113,4 +114,21 @@ describe('BottomNav', () => { await user.click(screen.getByRole('button', { name: 'Add expense' })); expect(mockNavigate).toHaveBeenCalledWith('/trips/42?create=expense'); }); + + it('FE-COMP-BOTTOMNAV-011: page plugin renders the icon its manifest declares', () => { + seedStore(usePluginStore, { + plugins: [{ id: 'trip-doctor', name: 'Trip Doctor', type: 'page', icon: 'Stethoscope' }], + }); + const { container } = render(); + expect(screen.getByText('Trip Doctor')).toBeInTheDocument(); + expect(container.querySelector('.lucide-stethoscope')).not.toBeNull(); + }); + + it('FE-COMP-BOTTOMNAV-012: page plugin with an unknown icon falls back to Blocks', () => { + seedStore(usePluginStore, { + plugins: [{ id: 'bogus', name: 'Bogus', type: 'page', icon: 'NotAnIcon' }], + }); + const { container } = render(); + expect(container.querySelector('.lucide-blocks')).not.toBeNull(); + }); }); diff --git a/client/src/components/Layout/BottomNav.tsx b/client/src/components/Layout/BottomNav.tsx index 232c09bb8..3d318571f 100644 --- a/client/src/components/Layout/BottomNav.tsx +++ b/client/src/components/Layout/BottomNav.tsx @@ -3,8 +3,9 @@ import { useAddonStore } from '../../store/addonStore' import { usePluginStore } from '../../store/pluginStore' import { useSettingsStore } from '../../store/settingsStore' import { useTranslation } from '../../i18n' -import { LayoutGrid, CalendarDays, Globe, Compass, Bookmark, Plus, Blocks } from 'lucide-react' +import { LayoutGrid, CalendarDays, Globe, Compass, Bookmark, Plus } from 'lucide-react' import type { LucideIcon } from 'lucide-react' +import { resolvePluginIcon } from '../shared/PluginIcon' const ADDON_NAV: Record = { vacay: { icon: CalendarDays, labelKey: 'admin.addons.catalog.vacay.name' }, @@ -65,7 +66,7 @@ export default function BottomNav() { const nav = ADDON_NAV[addon.id] return nav ? [{ to: `/${addon.id}`, label: t(nav.labelKey), icon: nav.icon }] : [] }), - ...pagePlugins.map(p => ({ to: `/plugins/${p.id}`, label: p.name, icon: Blocks })), + ...pagePlugins.map(p => ({ to: `/plugins/${p.id}`, label: p.name, icon: resolvePluginIcon(p.icon) })), ] // Split the items so the raised "+" sits dead centre. const splitAt = Math.ceil(items.length / 2) diff --git a/client/src/components/Layout/DemoBanner.test.tsx b/client/src/components/Layout/DemoBanner.test.tsx index a876b8d24..2e73868c5 100644 --- a/client/src/components/Layout/DemoBanner.test.tsx +++ b/client/src/components/Layout/DemoBanner.test.tsx @@ -1,6 +1,6 @@ -import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest'; -import userEvent from '@testing-library/user-event'; import { act, fireEvent } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { render, screen } from '../../../tests/helpers/render'; import DemoBanner from './DemoBanner'; @@ -94,7 +94,7 @@ describe('DemoBanner', () => { it('self-host link points to GitHub', () => { render(); const link = screen.getByText('self-host it').closest('a')!; - expect(link).toHaveAttribute('href', 'https://github.com/mauriceboe/TREK'); + expect(link).toHaveAttribute('href', 'https://github.com/liketrek/TREK'); expect(link).toHaveAttribute('target', '_blank'); }); diff --git a/client/src/components/Layout/DemoBanner.tsx b/client/src/components/Layout/DemoBanner.tsx index 6afd79aa0..a43feb7d0 100644 --- a/client/src/components/Layout/DemoBanner.tsx +++ b/client/src/components/Layout/DemoBanner.tsx @@ -1,24 +1,40 @@ -import React, { useState, useEffect } from 'react' -import { Info, Github, Shield, Key, Users, Database, Upload, Clock, Puzzle, CalendarDays, Globe, ArrowRightLeft, Map, Briefcase, ListChecks, Wallet, FileText, Plane } from 'lucide-react' -import { useTranslation } from '../../i18n' +import { + ArrowRightLeft, + CalendarDays, + Clock, + Database, + FileText, + Github, + Globe, + Key, + ListChecks, + Map, + Puzzle, + Shield, + Upload, + Users, + Wallet, +} from 'lucide-react'; +import React, { useEffect, useState } from 'react'; +import { useTranslation } from '../../i18n'; interface DemoTexts { - titleBefore: string - titleAfter: string - title: string - description: string - resetIn: string - minutes: string - uploadNote: string - fullVersionTitle: string - features: string[] - addonsTitle: string - addons: [string, string][] - whatIs: string - whatIsDesc: string - selfHost: string - selfHostLink: string - close: string + titleBefore: string; + titleAfter: string; + title: string; + description: string; + resetIn: string; + minutes: string; + uploadNote: string; + fullVersionTitle: string; + features: string[]; + addonsTitle: string; + addons: [string, string][]; + whatIs: string; + whatIsDesc: string; + selfHost: string; + selfHostLink: string; + close: string; } const texts: Record = { @@ -26,7 +42,8 @@ const texts: Record = { titleBefore: 'Willkommen bei ', titleAfter: '', title: 'Willkommen zur TREK Demo', - description: 'Du kannst Reisen ansehen, bearbeiten und eigene erstellen. Alle Aenderungen werden jede Stunde automatisch zurueckgesetzt.', + description: + 'Du kannst Reisen ansehen, bearbeiten und eigene erstellen. Alle Aenderungen werden jede Stunde automatisch zurueckgesetzt.', resetIn: 'Naechster Reset in', minutes: 'Minuten', uploadNote: 'Datei-Uploads (Fotos, Dokumente, Cover) sind in der Demo deaktiviert.', @@ -49,7 +66,8 @@ const texts: Record = { ['Widgets', 'Waehrungsrechner & Zeitzonen'], ], whatIs: 'Was ist TREK?', - whatIsDesc: 'Ein selbst-gehosteter Reiseplaner mit Echtzeit-Kollaboration, interaktiver Karte, OIDC Login und Dark Mode.', + whatIsDesc: + 'Ein selbst-gehosteter Reiseplaner mit Echtzeit-Kollaboration, interaktiver Karte, OIDC Login und Dark Mode.', selfHost: 'Open Source — ', selfHostLink: 'selbst hosten', close: 'Verstanden', @@ -81,7 +99,8 @@ const texts: Record = { ['Widgets', 'Currency converter & timezones'], ], whatIs: 'What is TREK?', - whatIsDesc: 'A self-hosted travel planner with real-time collaboration, interactive maps, OIDC login and dark mode.', + whatIsDesc: + 'A self-hosted travel planner with real-time collaboration, interactive maps, OIDC login and dark mode.', selfHost: 'Open source — ', selfHostLink: 'self-host it', close: 'Got it', @@ -113,7 +132,8 @@ const texts: Record = { ['Widgets', 'Conversor de divisas y zonas horarias'], ], whatIs: '¿Qué es TREK?', - whatIsDesc: 'Un planificador de viajes autohospedado con colaboración en tiempo real, mapas interactivos, inicio de sesión OIDC y modo oscuro.', + whatIsDesc: + 'Un planificador de viajes autohospedado con colaboración en tiempo real, mapas interactivos, inicio de sesión OIDC y modo oscuro.', selfHost: 'Código abierto — ', selfHostLink: 'alójalo tú mismo', close: 'Entendido', @@ -218,7 +238,8 @@ const texts: Record = { titleBefore: 'Selamat datang di ', titleAfter: '', title: 'Selamat datang di Demo TREK', - description: 'Anda dapat melihat, mengedit, dan membuat perjalanan. Semua perubahan akan diatur ulang secara otomatis setiap jam.', + description: + 'Anda dapat melihat, mengedit, dan membuat perjalanan. Semua perubahan akan diatur ulang secara otomatis setiap jam.', resetIn: 'Atur ulang berikutnya dalam', minutes: 'menit', uploadNote: 'Unggah file (foto, dokumen, sampul) dinonaktifkan dalam mode demo.', @@ -241,159 +262,309 @@ const texts: Record = { ['Widget', 'Konverter mata uang & zona waktu'], ], whatIs: 'Apa itu TREK?', - whatIsDesc: 'Perencana perjalanan yang di-host sendiri dengan kolaborasi real-time, peta interaktif, login OIDC, dan mode gelap.', + whatIsDesc: + 'Perencana perjalanan yang di-host sendiri dengan kolaborasi real-time, peta interaktif, login OIDC, dan mode gelap.', selfHost: 'Buka sumber — ', selfHostLink: 'host mandiri', close: 'Mengerti', }, -} +}; -const featureIcons = [Upload, Key, Users, Database, Puzzle, Shield] -const addonIcons = [CalendarDays, Globe, ListChecks, Wallet, FileText, ArrowRightLeft] +const featureIcons = [Upload, Key, Users, Database, Puzzle, Shield]; +const addonIcons = [CalendarDays, Globe, ListChecks, Wallet, FileText, ArrowRightLeft]; export default function DemoBanner(): React.ReactElement | null { - const [dismissed, setDismissed] = useState(false) - const [minutesLeft, setMinutesLeft] = useState(59 - new Date().getMinutes()) - const { language } = useTranslation() - const t = texts[language] || texts.en + const [dismissed, setDismissed] = useState(false); + const [minutesLeft, setMinutesLeft] = useState(59 - new Date().getMinutes()); + const { language } = useTranslation(); + const t = texts[language] || texts.en; useEffect(() => { - const interval = setInterval(() => setMinutesLeft(59 - new Date().getMinutes()), 10000) - return () => clearInterval(interval) - }, []) + const interval = setInterval(() => setMinutesLeft(59 - new Date().getMinutes()), 10000); + return () => clearInterval(interval); + }, []); - if (dismissed) return null + if (dismissed) return null; return ( -
    setDismissed(true)}> -
    ) => e.stopPropagation()}> - + fontFamily: 'var(--font-system)', + }} + onClick={() => setDismissed(true)} + > +
    ) => e.stopPropagation()} + > {/* Header */}
    -

    - {t.titleBefore}TREK{t.titleAfter} +

    + {t.titleBefore} + TREK + {t.titleAfter}

    -

    +

    {t.description}

    {/* Timer + Upload note */}
    -
    +
    {t.resetIn} {minutesLeft} {t.minutes}
    -
    +
    - {t.uploadNote} + + {t.uploadNote} +
    {/* What is TREK */} -
    +
    - + {t.whatIs}
    -

    {t.whatIsDesc}

    +

    + {t.whatIsDesc} +

    {/* Addons */} -

    +

    {t.addonsTitle}

    {t.addons.map(([name, desc], i) => { - const Icon = addonIcons[i] + const Icon = addonIcons[i]; return ( -
    +
    - {name} + + {name} +
    -

    {desc}

    +

    + {desc} +

    - ) + ); })}
    {/* Full version features */} -

    +

    {t.fullVersionTitle}

    {t.features.map((text, i) => { - const Icon = featureIcons[i] + const Icon = featureIcons[i]; return ( -
    +
    {text}
    - ) + ); })}
    {/* Footer */} -
    -
    +
    +
    {t.selfHost} - + {t.selfHostLink}
    -
    - ) + ); } diff --git a/client/src/components/Layout/Navbar.test.tsx b/client/src/components/Layout/Navbar.test.tsx index b0f8df240..4c098eb28 100644 --- a/client/src/components/Layout/Navbar.test.tsx +++ b/client/src/components/Layout/Navbar.test.tsx @@ -6,6 +6,7 @@ import { server } from '../../../tests/helpers/msw/server'; import { useAuthStore } from '../../store/authStore'; import { useSettingsStore } from '../../store/settingsStore'; import { useAddonStore } from '../../store/addonStore'; +import { usePluginStore } from '../../store/pluginStore'; import { resetAllStores, seedStore } from '../../../tests/helpers/store'; import { buildUser, buildSettings } from '../../../tests/helpers/factories'; import Navbar from './Navbar'; @@ -304,4 +305,21 @@ describe('Navbar', () => { await user.click(screen.getByText('adminuser')); expect(screen.getByText('Administrator')).toBeInTheDocument(); }); + + it('FE-COMP-NAVBAR-034: page plugin renders the icon its manifest declares', () => { + seedStore(usePluginStore, { + plugins: [{ id: 'trip-doctor', name: 'Trip Doctor', type: 'page', icon: 'Stethoscope' }], + }); + const { container } = render(); + expect(screen.getByRole('link', { name: /trip doctor/i })).toBeInTheDocument(); + expect(container.querySelector('.lucide-stethoscope')).not.toBeNull(); + }); + + it('FE-COMP-NAVBAR-035: page plugin with an unknown icon falls back to Blocks', () => { + seedStore(usePluginStore, { + plugins: [{ id: 'bogus', name: 'Bogus', type: 'page', icon: 'NotAnIcon' }], + }); + const { container } = render(); + expect(container.querySelector('.lucide-blocks')).not.toBeNull(); + }); }); diff --git a/client/src/components/Layout/Navbar.tsx b/client/src/components/Layout/Navbar.tsx index d7db52733..cb7cd684c 100644 --- a/client/src/components/Layout/Navbar.tsx +++ b/client/src/components/Layout/Navbar.tsx @@ -6,9 +6,10 @@ import { useSettingsStore } from '../../store/settingsStore' import { useAddonStore } from '../../store/addonStore' import { usePluginStore } from '../../store/pluginStore' import { useTranslation } from '../../i18n' -import { Plane, LogOut, Settings, ChevronDown, Shield, ArrowLeft, Users, Moon, Sun, Monitor, CalendarDays, Briefcase, Globe, Compass, BookOpen, Bookmark, Blocks } from 'lucide-react' +import { Plane, LogOut, Settings, ChevronDown, Shield, ArrowLeft, Users, Moon, Sun, Monitor, CalendarDays, Briefcase, Globe, Compass, BookOpen, Bookmark } from 'lucide-react' import type { LucideIcon } from 'lucide-react' import InAppNotificationBell from './InAppNotificationBell.tsx' +import { resolvePluginIcon } from '../shared/PluginIcon' const ADDON_ICONS: Record = { CalendarDays, Briefcase, Globe, Compass, Bookmark } @@ -150,7 +151,7 @@ export default function Navbar({ tripTitle, tripId, onBack, showBack, onShare }: > {[{ id: '__trips', path: '/dashboard', label: t('nav.myTrips'), Icon: Briefcase }, ...globalAddons.map(a => ({ id: a.id, path: `/${a.id}`, label: getAddonName(a), Icon: ADDON_ICONS[a.icon] || CalendarDays })), - ...pagePlugins.map(p => ({ id: `plugin:${p.id}`, path: `/plugins/${p.id}`, label: p.name, Icon: Blocks })) + ...pagePlugins.map(p => ({ id: `plugin:${p.id}`, path: `/plugins/${p.id}`, label: p.name, Icon: resolvePluginIcon(p.icon) })) ].map(tab => { const isActive = location.pathname === tab.path return ( diff --git a/client/src/components/Map/MapView.test.tsx b/client/src/components/Map/MapView.test.tsx index b1cd71ea5..a9e3396b9 100644 --- a/client/src/components/Map/MapView.test.tsx +++ b/client/src/components/Map/MapView.test.tsx @@ -4,7 +4,7 @@ import { render, screen } from '../../../tests/helpers/render' import { fireEvent, waitFor } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { resetAllStores } from '../../../tests/helpers/store' -import { buildPlace } from '../../../tests/helpers/factories' +import { buildPlace, buildReservation } from '../../../tests/helpers/factories' import * as photoService from '../../services/photoService' const mapMock = vi.hoisted(() => ({ @@ -15,10 +15,14 @@ const mapMock = vi.hoisted(() => ({ on: vi.fn(), off: vi.fn(), panBy: vi.fn(), + latLngToContainerPoint: vi.fn(() => ({ x: 0, y: 0, distanceTo: () => 1000 })), })) vi.mock('react-leaflet', () => ({ - MapContainer: ({ children }: any) =>
    {children}
    , + // center/zoom are surfaced so tests can assert the camera the map is built with. + MapContainer: ({ children, center, zoom }: any) => ( +
    {children}
    + ), TileLayer: () =>
    , Marker: ({ children, eventHandlers, position }: any) => (
    ({ Polyline: ({ positions }: any) =>
    , CircleMarker: () =>
    , Circle: () =>
    , + Tooltip: ({ children }: any) => <>{children}, useMap: () => mapMock, useMapEvents: () => ({}), })) @@ -291,15 +296,85 @@ describe('MapView', () => { buildMapPlace({ id: 1, lat: 48.0, lng: 2.0 }), buildMapPlace({ id: 2, lat: 48.1, lng: 2.1 }), ] - // Day selected, route not computed yet → first fit is the two destinations. + // The map opens already framed on its places, so nothing fits on mount. const { rerender } = render() const lastBounds = () => { const c = L.latLngBounds.mock.calls; return c[c.length - 1][0] } + + // Day selected, route not computed yet → first fit is the two destinations. + L.latLngBounds.mockClear() + rerender() expect(lastBounds()).toHaveLength(2) // The day's route arrives → one-shot re-fit including the 3 route points. L.latLngBounds.mockClear() - rerender() + rerender() expect(L.latLngBounds).toHaveBeenCalled() expect(lastBounds()).toHaveLength(5) // 2 destinations + 3 route points }) + + describe('opening camera', () => { + const camera = () => { + const el = screen.getByTestId('map-container') + return { + center: JSON.parse(el.getAttribute('data-center')!) as [number, number], + zoom: Number(el.getAttribute('data-zoom')), + } + } + + it('FE-COMP-MAPVIEW-021: builds the map framed on the places', () => { + render() + + const { center, zoom } = camera() + expect(center[0]).toBeCloseTo(34.85, 1) + expect(center[1]).toBeCloseTo(135.63, 1) + expect(zoom).toBeGreaterThan(7) + expect(zoom).toBeLessThan(13) + }) + + it('FE-COMP-MAPVIEW-022: does not fit on mount when it opened already framed', async () => { + const L = ((await import('leaflet')).default) as unknown as { latLngBounds: ReturnType } + L.latLngBounds.mockClear() + + render() + + expect(L.latLngBounds).not.toHaveBeenCalled() + }) + + it('FE-COMP-MAPVIEW-023: falls back to the world view when no place has coordinates', () => { + render() + + const { center, zoom } = camera() + expect(center).toEqual([0, 0]) + expect(zoom).toBe(2) + }) + }) + + it('FE-COMP-MAPVIEW-023: a routable reservation not in visibleConnectionIds draws no route', () => { + const reservation = buildReservation({ + id: 43, + type: 'flight', + endpoints: [ + { role: 'from', sequence: 0, name: 'A', code: 'AAA', lat: 1, lng: 2, timezone: null, local_time: null, local_date: null }, + { role: 'to', sequence: 1, name: 'B', code: 'BBB', lat: 3, lng: 4, timezone: null, local_time: null, local_date: null }, + ], + } as any) + render() + expect(screen.queryByTestId('polyline')).not.toBeInTheDocument() + }) + + it('FE-COMP-MAPVIEW-024: a routable reservation in visibleConnectionIds draws its route', () => { + const reservation = buildReservation({ + id: 42, + type: 'flight', + endpoints: [ + { role: 'from', sequence: 0, name: 'A', code: 'AAA', lat: 1, lng: 2, timezone: null, local_time: null, local_date: null }, + { role: 'to', sequence: 1, name: 'B', code: 'BBB', lat: 3, lng: 4, timezone: null, local_time: null, local_date: null }, + ], + } as any) + render() + expect(screen.getAllByTestId('polyline').length).toBeGreaterThan(0) + }) }) diff --git a/client/src/components/Map/MapView.tsx b/client/src/components/Map/MapView.tsx index bf9e13c37..94db37c93 100644 --- a/client/src/components/Map/MapView.tsx +++ b/client/src/components/Map/MapView.tsx @@ -11,8 +11,11 @@ import { getCategoryIcon, CATEGORY_ICON_MAP } from '../shared/categoryIcons' import ReservationOverlay from './ReservationOverlay' import { PluginMapMarkers } from './MapPluginMarkers' import { useTransportRoutes } from '../../hooks/useTransportRoutes' +import { visibleRouteReservations } from '../../utils/reservationRoutes' import type { Reservation } from '../../types' import { POI_CATEGORY_BY_KEY, type Poi } from './poiCategories' +import { DEFAULT_MAP_CENTER, DEFAULT_MAP_ZOOM } from '../../constants/mapDefaults' +import { computeMapViewport, TILE_SIZE_RASTER, type ViewportPadding } from '../../utils/mapViewport' function categoryIconSvg(iconName: string | null | undefined, size: number): string { const IconComponent = (iconName && CATEGORY_ICON_MAP[iconName]) || CATEGORY_ICON_MAP['MapPin'] @@ -241,12 +244,15 @@ interface BoundsControllerProps { routeCoords: [number, number][] fitKey: number paddingOpts: L.FitBoundsOptions + /** The map was built already framed on these places, so the opening fit has nothing to do. */ + framedOnMount?: boolean } -function BoundsController({ places, routeCoords, fitKey, paddingOpts, hasDayDetail }: BoundsControllerProps) { +function BoundsController({ places, routeCoords, fitKey, paddingOpts, hasDayDetail, framedOnMount = false }: BoundsControllerProps) { const map = useMap() const prevFitKey = useRef(-1) const awaitingRoute = useRef(false) + const fitRan = useRef(false) const fitTo = useCallback((coords: [number, number][]) => { if (coords.length === 0) return @@ -268,6 +274,14 @@ function BoundsController({ places, routeCoords, fitKey, paddingOpts, hasDayDeta prevFitKey.current = fitKey awaitingRoute.current = false if (places.length === 0) return + // The map opened framed on these very places — re-fitting would only re-do that, and its + // maxZoom would overrule the gentler zoom a single place opens at. Later fits (picking a + // day) still run. + if (!fitRan.current && framedOnMount) { + fitRan.current = true + return + } + fitRan.current = true fitTo(places.map(p => [p.lat, p.lng] as [number, number])) awaitingRoute.current = true }, [fitKey]) // eslint-disable-line react-hooks/exhaustive-deps @@ -435,8 +449,8 @@ export const MapView = memo(function MapView({ onMarkerClick, onMapClick, onMapContextMenu = null, - center = [48.8566, 2.3522], - zoom = 10, + center = DEFAULT_MAP_CENTER, + zoom = DEFAULT_MAP_ZOOM, tileUrl = 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png', fitKey = 0, dayOrderMap = {}, @@ -465,25 +479,43 @@ export const MapView = memo(function MapView({ {poi.name} )), [pois, onPoiClick]) - const visibleReservations = useMemo(() => { - const set = new Set(visibleConnectionIds || []) - // Transit journeys ride the route toggle — they are part of the computed - // day route, so hiding the route hides them too (#1065). - return reservations.filter((r: Reservation) => (r.type === 'transit' && showTransitRoutes) || set.has(r.id)) - }, [reservations, visibleConnectionIds, showTransitRoutes]) + const visibleReservations = useMemo(() => ( + visibleRouteReservations(reservations, { visibleConnectionIds, showTransitRoutes }) + ), [reservations, visibleConnectionIds, showTransitRoutes]) // Real road geometry for car/bus/taxi/bicycle bookings (straight line until it loads/if it fails). const transportRoutes = useTransportRoutes(visibleReservations) // Dynamic padding: account for sidebars + bottom inspector + day detail panel - const paddingOpts = useMemo((): L.FitBoundsOptions => { + // The chrome overlaying the map (side panels, day detail). Kept as a plain box so both the + // Leaflet fit options and the opening-camera maths can read the same numbers. + const paddingBox = useMemo((): ViewportPadding => { const isMobile = typeof window !== 'undefined' && window.innerWidth < 768 - if (isMobile) return { padding: [40, 20] } - const top = 60 - const bottom = hasInspector ? 320 : hasDayDetail ? 280 : 60 - const left = leftWidth + 40 - const right = rightWidth + 40 - return { paddingTopLeft: [left, top], paddingBottomRight: [right, bottom] } + if (isMobile) return { top: 20, right: 40, bottom: 20, left: 40 } + return { + top: 60, + right: rightWidth + 40, + bottom: hasInspector ? 320 : hasDayDetail ? 280 : 60, + left: leftWidth + 40, + } }, [leftWidth, rightWidth, hasInspector, hasDayDetail]) + const paddingOpts = useMemo((): L.FitBoundsOptions => ({ + paddingTopLeft: [paddingBox.left, paddingBox.top], + paddingBottomRight: [paddingBox.right, paddingBox.bottom], + }), [paddingBox]) + + // Open framed on the places rather than on the caller's default, so a trip in Japan shows + // Japan straight away instead of the world view followed by a flight across the planet. + // The initializer runs once, at mount — exactly when this should be decided; afterwards the + // camera belongs to the user. `framed` is false when no place has coordinates (a new trip), + // and then the caller's center/zoom stands. + const [initialView] = useState(() => { + const framed = computeMapViewport(dayPlaces.length > 0 ? dayPlaces : places, { + tileSize: TILE_SIZE_RASTER, + padding: paddingBox, + }) + return { center: framed?.center ?? center, zoom: framed?.zoom ?? zoom, framed: framed !== null } + }) + // Hover state for the single tooltip overlay (replaces per-marker ) const [hoveredPlace, setHoveredPlace] = useState(null) const [tooltipPos, setTooltipPos] = useState<{ x: number; y: number } | null>(null) @@ -656,8 +688,8 @@ export const MapView = memo(function MapView({
    @@ -672,7 +704,7 @@ export const MapView = memo(function MapView({ /> - 0 ? dayPlaces : places} routeCoords={dayPlaces.length > 0 ? routeCoords : []} fitKey={fitKey} paddingOpts={paddingOpts} hasDayDetail={hasDayDetail} /> + 0 ? dayPlaces : places} routeCoords={dayPlaces.length > 0 ? routeCoords : []} fitKey={fitKey} paddingOpts={paddingOpts} hasDayDetail={hasDayDetail} framedOnMount={initialView.framed} /> diff --git a/client/src/components/Map/MapViewGL.test.tsx b/client/src/components/Map/MapViewGL.test.tsx index 7b4c7635e..a4a30831b 100644 --- a/client/src/components/Map/MapViewGL.test.tsx +++ b/client/src/components/Map/MapViewGL.test.tsx @@ -5,6 +5,8 @@ import { act } from '@testing-library/react' import { resetAllStores } from '../../../tests/helpers/store' import { buildPlace } from '../../../tests/helpers/factories' import { useSettingsStore } from '../../store/settingsStore' +import maplibregl from 'maplibre-gl' +import { DEFAULT_MAP_ZOOM } from '../../constants/mapDefaults' // Stable fake map so fitBounds call counts survive re-renders. The canvas // container is a single element so listeners registered by the component are @@ -37,6 +39,23 @@ const glMap = vi.hoisted(() => ({ easeTo: vi.fn(), })) +const glBounds = vi.hoisted(() => { + const state = { + instances: [] as Array<{ extend: ReturnType }>, + } + return { + get instances() { return state.instances }, + clear: () => { state.instances = [] }, + create: () => { + const bounds = { + extend: vi.fn(() => bounds), + } + state.instances.push(bounds) + return bounds + }, + } +}) + vi.mock('mapbox-gl', () => ({ default: { accessToken: '', @@ -52,7 +71,7 @@ vi.mock('mapbox-gl', () => ({ } }), LngLatBounds: vi.fn(function () { - return { extend: vi.fn().mockReturnThis() } + return glBounds.create() }), NavigationControl: vi.fn(), Popup: vi.fn(function () { @@ -81,7 +100,7 @@ vi.mock('maplibre-gl', () => ({ } }), LngLatBounds: vi.fn(function () { - return { extend: vi.fn().mockReturnThis() } + return glBounds.create() }), NavigationControl: vi.fn(), Popup: vi.fn(function () { @@ -148,6 +167,7 @@ beforeEach(() => { glMap.on.mockImplementation(() => glMap) glMap.off.mockImplementation(() => glMap) glMap.once.mockImplementation(() => glMap) + glMap.loaded.mockReturnValue(true) glMap.getSource.mockReturnValue(null) glMap.getLayer.mockReturnValue(null) glMap.queryRenderedFeatures.mockReturnValue([]) @@ -165,6 +185,7 @@ beforeEach(() => { afterEach(() => { vi.clearAllMocks() + glBounds.clear() resetAllStores() }) @@ -244,6 +265,39 @@ describe('MapViewGL', () => { expect(mapboxgl.Map).not.toHaveBeenCalled() }) + it('FE-COMP-MAPVIEWGL-014: MapLibre maps disable the around-center mouse rotate (#1545)', async () => { + const mapboxgl = (await import('mapbox-gl')).default + const maplibregl = (await import('maplibre-gl')).default + useSettingsStore.setState({ + settings: { + ...useSettingsStore.getState().settings, + map_provider: 'maplibre-gl', + mapbox_access_token: '', + maplibre_style: 'https://tiles.openfreemap.org/styles/liberty', + }, + } as any) + const places = [buildMapPlace({ id: 1, lat: 48.8584, lng: 2.2945 })] + + render() + await act(async () => {}) + // MapLibre 5's around-center rotate reverses direction at a drifting + // mid-screen line, so the map must opt out of it. + expect((maplibregl.Map as any).mock.calls[0][0]).toMatchObject({ aroundCenter: false }) + + vi.clearAllMocks() + useSettingsStore.setState({ + settings: { + ...useSettingsStore.getState().settings, + map_provider: 'mapbox-gl', + mapbox_access_token: 'pk.test_token', + }, + } as any) + render() + await act(async () => {}) + // mapbox-gl has no such option — it must not receive the stray key. + expect((mapboxgl.Map as any).mock.calls[0][0]).not.toHaveProperty('aroundCenter') + }) + it('FE-COMP-MAPVIEWGL-005: adds the clustered place source + layers so markers group on zoom-out (#1385)', async () => { glMap.on.mockImplementation((event: string, handlerOrLayer: unknown) => { if (event === 'load' && typeof handlerOrLayer === 'function') (handlerOrLayer as () => void)() @@ -439,4 +493,187 @@ describe('MapViewGL', () => { act(() => { el.dispatchEvent(new MouseEvent('mouseenter', { clientX: 10, clientY: 10 })) }) expect(queryByTestId('tooltip')).toBeTruthy() }) + + // The map opens already framed on its places, so these exercise the fits that happen + // afterwards — picking a day bumps fitKey. + it('FE-COMP-MAPVIEWGL-014: fits bounds immediately even when MapLibre loaded() is false', async () => { + glMap.loaded.mockReturnValue(false) + const places = [ + buildMapPlace({ id: 1, lat: 35.38, lng: 136.94 }), + buildMapPlace({ id: 2, lat: 35.42, lng: 136.76 }), + ] + + const { rerender } = render( + , + ) + await act(async () => {}) + + rerender() + await act(async () => {}) + + expect(glMap.fitBounds).toHaveBeenCalled() + }) + + it('FE-COMP-MAPVIEWGL-015: fits MapLibre bounds to route geometry when it arrives after a day fit', async () => { + const dayPlaces = [ + buildMapPlace({ id: 1, lat: 35.38, lng: 136.94 }), + buildMapPlace({ id: 2, lat: 35.42, lng: 136.76 }), + ] + // The day's route is drawn as straight lines in the same batch as the fit, then + // upgraded to the real road geometry — which detours well outside the markers. + const straightLines: [number, number][][] = [[[35.38, 136.94], [35.42, 136.76]]] + const roadGeometry: [number, number][][] = [[[35.38, 136.94], [35.72, 137.51], [35.42, 136.76]]] + + const { rerender } = render( + , + ) + await act(async () => {}) + + // Pick a day: fits the markers, with only the straight-line route to go on so far. + rerender( + , + ) + await act(async () => {}) + const afterDayFit = glMap.fitBounds.mock.calls.length + expect(afterDayFit).toBeGreaterThan(0) + + // The real geometry lands a moment later and the fit widens to take it in. + rerender( + , + ) + await act(async () => {}) + + expect(glMap.fitBounds.mock.calls.length).toBeGreaterThan(afterDayFit) + const latestBounds = glBounds.instances[glBounds.instances.length - 1] + expect(latestBounds.extend).toHaveBeenCalledWith([137.51, 35.72]) + }) + + describe('opening camera', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const mapOptions = () => (maplibregl.Map as any).mock.calls.at(-1)[0] + + it('FE-COMP-MAPVIEWGL-017: builds the map framed on the places, in [lng, lat] order', async () => { + const places = [ + buildMapPlace({ id: 1, lat: 35.01, lng: 135.76 }), // Kyoto + buildMapPlace({ id: 2, lat: 34.69, lng: 135.5 }), // Osaka + ] + + render() + await act(async () => {}) + + const { center, zoom } = mapOptions() + // GL takes [lng, lat] — the swap is the easiest thing to get backwards here. + expect(center[0]).toBeCloseTo(135.63, 1) + expect(center[1]).toBeCloseTo(34.85, 1) + // Framed on two cities ~30km apart: regional, not the world and not street level. + expect(zoom).toBeGreaterThan(6) + expect(zoom).toBeLessThan(12) + }) + + it('FE-COMP-MAPVIEWGL-020: does not jump to the default centre on mount, undoing the framing', async () => { + const places = [buildMapPlace({ id: 1, lat: 35.01, lng: 135.76 })] + + render() + await act(async () => {}) + + // The centre prop is the world-view default nobody passed. Jumping to it on mount would + // throw away the camera the map was just built with and land on Null Island at zoom 2. + expect(glMap.jumpTo).not.toHaveBeenCalled() + }) + + it('FE-COMP-MAPVIEWGL-018: does not fit on mount when it opened already framed', async () => { + const places = [buildMapPlace({ id: 1, lat: 35.01, lng: 135.76 })] + + const { rerender } = render() + await act(async () => {}) + + // Fitting would only re-do the framing, and its maxZoom would overrule the gentler + // zoom a lone place opens at. + expect(glMap.fitBounds).not.toHaveBeenCalled() + + // Picking a day still fits, as always. + rerender() + await act(async () => {}) + expect(glMap.fitBounds).toHaveBeenCalled() + }) + + it('FE-COMP-MAPVIEWGL-019: falls back to the world view when no place has coordinates', async () => { + render( + , + ) + await act(async () => {}) + + const { center, zoom } = mapOptions() + expect(center).toEqual([0, 0]) + expect(zoom).toBe(DEFAULT_MAP_ZOOM) + }) + }) + + it('FE-COMP-MAPVIEWGL-016: leaves the camera alone when a route appears long after the fit', async () => { + const dayPlaces = [ + buildMapPlace({ id: 1, lat: 35.38, lng: 136.94 }), + buildMapPlace({ id: 2, lat: 35.42, lng: 136.76 }), + ] + + const { rerender } = render( + , + ) + await act(async () => {}) + + // Pick a day with the route toggle off: no route is pending for this fit. + rerender( + , + ) + await act(async () => {}) + const afterDayFit = glMap.fitBounds.mock.calls.length + expect(afterDayFit).toBeGreaterThan(0) + + // Much later the user pans away and turns the route on. That is not the geometry this + // fit was waiting for, so the camera must stay put. + rerender( + , + ) + await act(async () => {}) + + expect(glMap.fitBounds.mock.calls.length).toBe(afterDayFit) + }) }) diff --git a/client/src/components/Map/MapViewGL.tsx b/client/src/components/Map/MapViewGL.tsx index cc79f6e78..aa81048d3 100644 --- a/client/src/components/Map/MapViewGL.tsx +++ b/client/src/components/Map/MapViewGL.tsx @@ -12,12 +12,15 @@ import { isStandardFamily, supportsCustom3d, wantsTerrain, addCustom3dBuildings, import { attachLocationMarker, type LocationMarkerHandle } from './locationMarkerMapbox' import { ReservationMapboxOverlay } from './reservationsMapbox' import { useTransportRoutes } from '../../hooks/useTransportRoutes' +import { visibleRouteReservations } from '../../utils/reservationRoutes' import { MAPBOX_DEFAULT_STYLE, styleForActiveProvider, basemapLanguage, type GlMapProvider } from './glProviders' import LocationButton from './LocationButton' import { useGeolocation } from '../../hooks/useGeolocation' import type { Place, Reservation } from '../../types' import { POI_CATEGORY_BY_KEY, type Poi } from './poiCategories' import { buildPoiPopupHtml } from './placePopup' +import { DEFAULT_MAP_CENTER, DEFAULT_MAP_ZOOM } from '../../constants/mapDefaults' +import { computeMapViewport, TILE_SIZE_GL } from '../../utils/mapViewport' function categoryIconSvg(iconName: string | null | undefined, size: number): string { const IconComponent = (iconName && CATEGORY_ICON_MAP[iconName]) || CATEGORY_ICON_MAP['MapPin'] @@ -43,6 +46,10 @@ function hasValidCoords(place: Place): place is PlaceWithCoords { return place.lat != null && place.lng != null && Number.isFinite(place.lat) && Number.isFinite(place.lng) } +function isValidCoordinate(coord: [number, number] | null | undefined): coord is [number, number] { + return !!coord && Number.isFinite(coord[0]) && Number.isFinite(coord[1]) +} + function buildPlaceClusterData(places: Place[]) { return { type: 'FeatureCollection' as const, @@ -191,8 +198,8 @@ export function MapViewGL({ onMarkerClick, onMapClick, onMapContextMenu = null, - center = [48.8566, 2.3522], - zoom = 10, + center = DEFAULT_MAP_CENTER, + zoom = DEFAULT_MAP_ZOOM, fitKey = 0, dayOrderMap = {}, leftWidth = 0, @@ -258,8 +265,8 @@ export function MapViewGL({ onReservationClickRef.current = onReservationClick // eslint-disable-next-line @typescript-eslint/no-explicit-any const poiMarkersRef = useRef([]) - // Single reusable hover popup (name/category/address card) shared by planned - // places and POI markers — mirrors the Leaflet map's hover tooltip. + // Single reusable hover popup for POI markers. Planned places use the + // cursor-following React tooltip below so they match the Leaflet map. // eslint-disable-next-line @typescript-eslint/no-explicit-any const popupRef = useRef(null) const onPoiClickRef = useRef(onPoiClick) @@ -275,22 +282,46 @@ export function MapViewGL({ onClickRefs.current.context = onMapContextMenu const hoverDisabledRef = useRef(hoverDisabled) hoverDisabledRef.current = hoverDisabled + const routeCoords = useMemo<[number, number][]>(() => (route || []).flat().filter(isValidCoordinate), [route]) + const routeFitKey = useMemo( + () => routeCoords.map(([lat, lng]) => `${lat.toFixed(6)},${lng.toFixed(6)}`).join('|'), + [routeCoords], + ) + // Set when the map was built already framed on its places, so the fit below knows there is + // nothing left to do on mount. + const framedOnMountRef = useRef(false) // Build/rebuild the map on provider/style/token/3d change useEffect(() => { if (!containerRef.current || (!isMapLibre && !mapboxToken)) return if (!isMapLibre) mapboxgl.accessToken = mapboxToken + // Open framed on the places rather than on the caller's default: a trip in Japan should + // show Japan straight away, not the world view followed by a flight across the planet. + // Reading them here is what makes this "on load" — the map is built once, and the trip's + // places are already loaded by then (TripPlannerPage holds a splash until they are). + const framed = computeMapViewport(dayPlaces.length > 0 ? dayPlaces : places, { + tileSize: TILE_SIZE_GL, + padding: paddingOpts, + }) + framedOnMountRef.current = framed !== null + const initial = framed ?? { center, zoom } + const mapOptions: Record = { container: containerRef.current, style: glStyle, - center: [center[1], center[0]], - zoom, + center: [initial.center[1], initial.center[0]], + zoom: initial.zoom, pitch: enableMapbox3d ? 45 : 0, attributionControl: true, antialias: mapboxQuality, } if (!isMapLibre) mapOptions.projection = mapboxQuality ? 'globe' : 'mercator' + // MapLibre 5's mouse-rotate inverts its sign at a mid-screen line it gets by + // re-projecting the map center — a line that drifts with the bearing, so a + // right-button drag near mid-screen ping-pongs instead of rotating (#1545). + // aroundCenter: false restores the plain dx-based rotate mapbox-gl uses. + if (isMapLibre) mapOptions.aroundCenter = false const map = new gl.Map(mapOptions as any) mapRef.current = map @@ -898,12 +929,9 @@ export function MapViewGL({ // `visibleConnectionIds` is driven by the per-reservation toggle in // DayPlanSidebar — nothing is rendered until the user enables a // booking's route, matching the Leaflet MapView's behaviour. - const visibleReservations = useMemo(() => { - const set = new Set(visibleConnectionIds || []) - // Transit journeys ride the route toggle — they are part of the computed - // day route, so hiding the route hides them too (#1065). - return reservations.filter(r => (r.type === 'transit' && showTransitRoutes) || set.has(r.id)) - }, [reservations, visibleConnectionIds, showTransitRoutes]) + const visibleReservations = useMemo(() => ( + visibleRouteReservations(reservations, { visibleConnectionIds, showTransitRoutes }) + ), [reservations, visibleConnectionIds, showTransitRoutes]) // Real road geometry for car/bus/taxi/bicycle bookings (straight line until it loads/if it fails). const transportRoutes = useTransportRoutes(visibleReservations) @@ -935,17 +963,46 @@ export function MapViewGL({ return { top, right: rightWidth + 40, bottom, left: leftWidth + 40 } }, [leftWidth, rightWidth, hasInspector, hasDayDetail]) - const prevFitKey = useRef(-1) + const prevFitKey = useRef(-1) + const pendingRouteFitRef = useRef<{ fitKey: number | null; routeKey: string } | null>(null) + const fitRanRef = useRef(false) useEffect(() => { - if (fitKey === prevFitKey.current) return - prevFitKey.current = fitKey + const fitKeyChanged = fitKey !== prevFitKey.current + const routeArrivedForPendingFit = + !fitKeyChanged + && pendingRouteFitRef.current?.fitKey === fitKey + && !!routeFitKey + && routeFitKey !== pendingRouteFitRef.current.routeKey + if (!fitKeyChanged && !routeArrivedForPendingFit) return const map = mapRef.current if (!map) return + + // The map was built framed on these very places, so fitting now would only re-do that — + // and its maxZoom would overrule the gentler zoom a single place opens at. Adopt the + // current fitKey and stand down; every later fit (picking a day) still runs. + if (!fitRanRef.current && framedOnMountRef.current) { + fitRanRef.current = true + prevFitKey.current = fitKey + pendingRouteFitRef.current = null + return + } + fitRanRef.current = true + if (fitKeyChanged) { + prevFitKey.current = fitKey + // Only wait for better geometry when a route is already on screen: the day's + // route lands as straight lines in the same batch as the fit, then upgrades to + // the real road geometry a moment later. With no route drawn, none is coming for + // this fit — arming the slot anyway would let a route toggled on much later + // (after the user has panned somewhere else) yank the camera back. + pendingRouteFitRef.current = routeFitKey ? { fitKey, routeKey: routeFitKey } : null + } const target = dayPlaces.length > 0 ? dayPlaces : places - const valid = target.filter(p => p.lat && p.lng) - if (valid.length === 0) return + const markerPoints = target.filter(hasValidCoords).map(p => [p.lat, p.lng] as [number, number]) + const fitPoints = routeCoords.length > 0 ? [...routeCoords, ...markerPoints] : markerPoints + if (fitPoints.length === 0) return const bounds = new gl.LngLatBounds() - valid.forEach(p => bounds.extend([p.lng, p.lat])) + fitPoints.forEach(([lat, lng]) => bounds.extend([lng, lat])) + let fitted = false const run = () => { try { map.fitBounds(bounds, { @@ -954,11 +1011,13 @@ export function MapViewGL({ pitch: enableMapbox3d ? 45 : 0, duration: 400, }) + fitted = true } catch { /* noop */ } } - if (map.loaded()) run() - else map.once('load', run) - }, [fitKey]) // eslint-disable-line react-hooks/exhaustive-deps + run() + if (!fitted && typeof map.once === 'function') map.once('load', run) + if (routeArrivedForPendingFit) pendingRouteFitRef.current = null + }, [fitKey, routeFitKey]) // eslint-disable-line react-hooks/exhaustive-deps // flyTo selected place useEffect(() => { @@ -981,9 +1040,16 @@ export function MapViewGL({ }, [selectedPlaceId, enableMapbox3d]) // eslint-disable-line react-hooks/exhaustive-deps // External center/zoom prop changes — jump without animation + const jumpedToRef = useRef<[number, number] | null>(null) useEffect(() => { const map = mapRef.current if (!map) return + // Not on mount: the map was just built with its own camera, framed on the places, and + // jumping to the prop centre here would throw that away and land on the world view. + // This effect is for *changes* to the prop, which only arrive later. + const previous = jumpedToRef.current + jumpedToRef.current = [center[0], center[1]] + if (!previous || (previous[0] === center[0] && previous[1] === center[1])) return try { map.jumpTo({ center: [center[1], center[0]], zoom }) } catch { /* noop */ } }, [center[0], center[1]]) // eslint-disable-line react-hooks/exhaustive-deps diff --git a/client/src/components/Map/ReservationOverlay.tsx b/client/src/components/Map/ReservationOverlay.tsx index d1cdb2128..b856482df 100644 --- a/client/src/components/Map/ReservationOverlay.tsx +++ b/client/src/components/Map/ReservationOverlay.tsx @@ -371,6 +371,11 @@ export default function ReservationOverlay({ reservations, showConnections, show const visibleItems = useMemo(() => { return items.filter(item => { + // A transit journey draws its real rail/bus alignment, not a straight from->to + // line, so the endpoint-proximity declutter (which exists to hide tiny no-op + // straight connectors) must not suppress it. Otherwise a zoomed-out day — e.g. one + // with no other places to tighten the map onto — hides the whole route (#1570). + if (item.transitSegs.length > 0) return true const fromPx = map.latLngToContainerPoint([item.from.lat, item.from.lng]) const toPx = map.latLngToContainerPoint([item.to.lat, item.to.lng]) const minPx = item.type === 'flight' ? 50 : item.type === 'cruise' ? 150 : item.type === 'car' ? 80 : 200 diff --git a/client/src/components/Map/reservationsMapbox.test.ts b/client/src/components/Map/reservationsMapbox.test.ts index 423767a16..7a352649f 100644 --- a/client/src/components/Map/reservationsMapbox.test.ts +++ b/client/src/components/Map/reservationsMapbox.test.ts @@ -42,6 +42,22 @@ function carBooking(): Reservation { } as unknown as Reservation } +// A transit journey whose from/to stations project close together (under the 200px +// declutter threshold) but which carries real per-leg MOTIS geometry. The encoded +// polyline decodes to [[48,2],[48.02,2.01],[48.05,2]] at precision 6. +function transitBooking(withGeometry: boolean): Reservation { + return { + id: 2, type: 'transit', status: 'confirmed', + endpoints: [ + { role: 'from', sequence: 0, name: 'Stop A', code: null, lat: 48.0, lng: 2.0, timezone: null, local_time: null, local_date: null }, + { role: 'to', sequence: 1, name: 'Stop B', code: null, lat: 48.05, lng: 2.0, timezone: null, local_time: null, local_date: null }, + ], + metadata: withGeometry + ? { transit: { legs: [{ geometry: '__upzA_gayB_af@_pR_ry@~oR', mode: 'BUS', line_color: '#7c3aed' }] } } + : { transit: { legs: [{ mode: 'BUS' }] } }, + } as unknown as Reservation +} + const opts = { showConnections: true, showStats: false, showEndpointLabels: false } function lastFeatureCoords(map: ReturnType) { @@ -76,3 +92,23 @@ describe('ReservationMapboxOverlay road routes (#1425)', () => { expect(data.features).toHaveLength(0) }) }) + +describe('ReservationMapboxOverlay transit routes (#1570)', () => { + it('draws a transit journey with real geometry even when its stations project close together', () => { + const map = fakeMap() + const overlay = new ReservationMapboxOverlay(map as never, opts, FakeMarker as never) + overlay.update([transitBooking(true)], opts) + // Stations are ~50px apart — under the 200px declutter — yet the real per-leg + // path (GeoJSON [lng, lat]) is drawn because it carries stored geometry. + expect(lastFeatureCoords(map)).toEqual([[2, 48], [2.01, 48.02], [2, 48.05]]) + }) + + it('still declutters a geometry-less transit whose stations project close together', () => { + const map = fakeMap() + const overlay = new ReservationMapboxOverlay(map as never, opts, FakeMarker as never) + overlay.update([transitBooking(false)], opts) + const calls = map._source.setData.mock.calls + const data = calls[calls.length - 1]?.[0] as { features: unknown[] } + expect(data.features).toHaveLength(0) + }) +}) diff --git a/client/src/components/Map/reservationsMapbox.ts b/client/src/components/Map/reservationsMapbox.ts index 5e87f79cd..a698d21dd 100644 --- a/client/src/components/Map/reservationsMapbox.ts +++ b/client/src/components/Map/reservationsMapbox.ts @@ -283,6 +283,10 @@ export class ReservationMapboxOverlay { // overlay, so tiny no-op transport lines don't clutter the map. const visibleItems = show ? this.items.filter(item => { try { + // A transit journey draws its real alignment, not a straight from->to line, so + // don't let the endpoint-proximity declutter hide it when the map is zoomed out + // (#1570). Mirrors the Leaflet overlay. + if (item.type === 'transit' && getTransitMapSegments(item.res).length > 0) return true const fromPx = map.project([item.from.lng, item.from.lat]) const toPx = map.project([item.to.lng, item.to.lat]) const dx = fromPx.x - toPx.x, dy = fromPx.y - toPx.y diff --git a/client/src/components/PDF/TripPDF.test.ts b/client/src/components/PDF/TripPDF.test.ts index 68c3805bc..3867d9850 100644 --- a/client/src/components/PDF/TripPDF.test.ts +++ b/client/src/components/PDF/TripPDF.test.ts @@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { http, HttpResponse } from 'msw' import { downloadTripPDF } from './TripPDF' import { server } from '../../../tests/helpers/msw/server' +import { clearExchangeRateCache } from '../../hooks/useExchangeRates' // ── Helpers ─────────────────────────────────────────────────────────────────── @@ -50,7 +51,11 @@ beforeEach(() => { http.get('/api/pdf-sections/:tripId', () => HttpResponse.json({ sections: [] }) ), + // Mixed-currency exports fetch FX rates; keep the suite hermetic. + http.get('https://api.frankfurter.dev/v2/rates', () => HttpResponse.json([])), ) + // The FX cache is module-level and would leak rates between tests in this file. + clearExchangeRateCache() }) afterEach(() => { @@ -170,6 +175,18 @@ describe('downloadTripPDF', () => { expect(srcdoc).toContain('Colosseum') }) + it('FE-COMP-TRIPPDF-005c: the gap under the day header lives in the repeated thead cell (#1531)', async () => { + await downloadTripPDF(richArgs) + const iframe = getIframe() + const srcdoc = iframe!.srcdoc + // The thead is repeated on every overflow page, so the spacing below the header bar + // must be declared on its cell... + expect(srcdoc).toContain('.day-header > tr > td { padding-bottom: 12px; }') + // ...and not as a block-start padding on .day-body, which the print engine only paints + // on the first fragment of the (fragmented) body cell. + expect(srcdoc).toContain('.day-body { padding: 0 28px 6px; }') + }) + it('FE-COMP-TRIPPDF-006: escHtml prevents XSS in trip title', async () => { const args = { ...minimalArgs, @@ -274,13 +291,104 @@ describe('downloadTripPDF', () => { expect(iframe!.srcdoc).toContain('CONF999') }) - it('FE-COMP-TRIPPDF-016: renders place description and price chip', async () => { + it('FE-COMP-TRIPPDF-016: renders place description and a currency-formatted price chip', async () => { await downloadTripPDF(richArgs) const iframe = getIframe() expect(iframe!.srcdoc).toContain('Ancient amphitheater') - // Price chip: 15 EUR - expect(iframe!.srcdoc).toContain('15') - expect(iframe!.srcdoc).toContain('EUR') + // richArgs trip has no explicit currency, place has no currency override — + // formatMoney falls back to EUR, formatted via Intl (symbol, not literal "EUR" text). + expect(iframe!.srcdoc).toContain('15,00') + expect(iframe!.srcdoc).toContain('€') + }) + + it('FE-COMP-TRIPPDF-016b: formats price chip and totals in the trip currency, not EUR', async () => { + const usdArgs = { + ...richArgs, + trip: { ...richArgs.trip, currency: 'USD' }, + } + await downloadTripPDF(usdArgs) + const iframe = getIframe() + // Place price chip: place has no currency override, falls back to trip.currency (USD). + expect(iframe!.srcdoc).toContain('$15.00') + // No literal "EUR" text should leak into a USD trip's export. + expect(iframe!.srcdoc).not.toContain('EUR') + // Price chip icon must stay currency-neutral — not the euro-shaped glyph. + expect(iframe!.srcdoc).not.toContain('M14 5c-3.87 0-7 3.13-7 7s3.13 7 7 7c2.17 0 4.1-.99 5.4-2.55') + }) + + it('FE-COMP-TRIPPDF-016c: a place with its own currency overrides the trip currency for its price chip', async () => { + const mixedArgs = { + ...richArgs, + trip: { ...richArgs.trip, currency: 'EUR' }, + assignments: { + '10': [{ + ...assignmentForDay, + place: { ...placeWithDetails, currency: 'JPY', price: '1500' }, + }], + } as any, + } + await downloadTripPDF(mixedArgs) + const iframe = getIframe() + // JPY is a zero-decimal currency (currencyDecimals) and uses its own symbol, not EUR. + // Note: Intl renders JPY with the fullwidth yen sign (U+FFE5 "¥"), not U+00A5 "¥". + expect(iframe!.srcdoc).toContain('¥1,500') + }) + + it('FE-COMP-TRIPPDF-016d: converts foreign-currency prices into the trip currency for day and cover totals (#1561)', async () => { + server.use(http.get('https://api.frankfurter.dev/v2/rates', ({ request }) => { + expect(new URL(request.url).searchParams.get('base')).toBe('NOK') + return HttpResponse.json([{ quote: 'USD', rate: 0.1 }]) // 1 NOK = 0.1 USD + })) + const mixedArgs = { + ...richArgs, + trip: { ...richArgs.trip, currency: 'NOK' }, + assignments: { + '10': [ + { ...assignmentForDay, place: { ...placeWithDetails, currency: 'USD', price: '273' } }, + { ...assignmentForDay, id: 201, place: { ...placeWithDetails, id: 101, name: 'Museum', currency: null, price: '2500' } }, + ], + } as any, + } + await downloadTripPDF(mixedArgs) + const srcdoc = getIframe()!.srcdoc.replace(/[\u00A0\u202F]/g, ' ') + // 2500 NOK + 273 USD / 0.1 = 5230 NOK, marked approximate, in day header AND cover stat. + expect(srcdoc).toContain('≈ 5 230,00 kr') + expect((srcdoc.match(/≈ 5 230,00 kr/g) || []).length).toBeGreaterThanOrEqual(2) + }) + + it('FE-COMP-TRIPPDF-016e: falls back to per-currency breakdowns when the FX fetch fails (#1561)', async () => { + server.use(http.get('https://api.frankfurter.dev/v2/rates', () => HttpResponse.error())) + const mixedArgs = { + ...richArgs, + trip: { ...richArgs.trip, currency: 'NOK' }, + assignments: { + '10': [ + { ...assignmentForDay, place: { ...placeWithDetails, currency: 'USD', price: '2730.27' } }, + { ...assignmentForDay, id: 201, place: { ...placeWithDetails, id: 101, name: 'Museum', currency: null, price: '2500' } }, + ], + } as any, + } + // Export still resolves — a dead FX endpoint must never break the PDF. + await expect(downloadTripPDF(mixedArgs)).resolves.not.toThrow() + const srcdoc = getIframe()!.srcdoc.replace(/[\u00A0\u202F]/g, ' ') + // Honest breakdown, base currency first; the USD amount is never NOK-labeled. + expect(srcdoc).toContain('2 500,00 kr + $2,730.27') + expect(srcdoc).not.toContain('≈') + expect(srcdoc).not.toMatch(/5 ?230/) + }) + + it('FE-COMP-TRIPPDF-016f: an all-same-currency trip makes no FX request', async () => { + let fxCalled = false + server.use(http.get('https://api.frankfurter.dev/v2/rates', () => { + fxCalled = true + return HttpResponse.json([]) + })) + await downloadTripPDF({ ...richArgs, trip: { ...richArgs.trip, currency: 'EUR' } }) + expect(fxCalled).toBe(false) + // Totals render exactly as before for the single-currency case. + const srcdoc = getIframe()!.srcdoc.replace(/[\u00A0\u202F]/g, ' ') + expect(srcdoc).toContain('15,00 €') + expect(srcdoc).not.toContain('≈') }) it('FE-COMP-TRIPPDF-017: renders trip description on cover', async () => { diff --git a/client/src/components/PDF/TripPDF.tsx b/client/src/components/PDF/TripPDF.tsx index 40ba37cb7..98745bd8e 100644 --- a/client/src/components/PDF/TripPDF.tsx +++ b/client/src/components/PDF/TripPDF.tsx @@ -5,7 +5,8 @@ import { FileText, Info, Clock, MapPin, Navigation, Train, Plane, Bus, Car, Ship import { accommodationsApi, mapsApi, pluginsApi } from '../../api/client' import type { Trip, Day, Place, Category, AssignmentsMap, DayNote } from '../../types' import { isDayInAccommodationRange, getDayOrder } from '../../utils/dayOrder' -import { splitReservationDateTime } from '../../utils/formatters' +import { formatMoney, formatMoneySum, splitReservationDateTime, type MoneyEntry } from '../../utils/formatters' +import { fetchExchangeRates } from '../../hooks/useExchangeRates' import { getFlightLegs, getTrainLegs } from '../../utils/flightLegs' function renderLucideIcon(icon:LucideIcon, props = {}) { @@ -40,7 +41,7 @@ const svgPin = `` const svgClock2= `` const svgCheck = `` -const svgEuro = `` +const svgMoney = `` function escHtml(str) { if (!str) return '' @@ -92,9 +93,15 @@ function longDateRange(days, locale) { return `${f.toLocaleDateString(locale, { day: 'numeric', month: 'long', timeZone: 'UTC' })} – ${l.toLocaleDateString(locale, { day: 'numeric', month: 'long', year: 'numeric', timeZone: 'UTC' })}` } -function dayCost(assignments, dayId, locale) { - const total = (assignments[String(dayId)] || []).reduce((s, a) => s + (parseFloat(a.place?.price) || 0), 0) - return total > 0 ? `${total.toLocaleString(locale)} EUR` : null +// Day totals render in the trip's currency; foreign-currency place prices are +// converted via the pre-fetched rates, or listed per-currency when rates are +// unavailable (#1561). +function dayCost(assignments, dayId, locale, tripCurrency, rates) { + const entries: MoneyEntry[] = (assignments[String(dayId)] || []).map(a => ({ + amount: parseFloat(a.place?.price) || 0, + currency: a.place?.currency || tripCurrency, + })) + return formatMoneySum(entries, tripCurrency, locale || 'en', rates) } // Pre-fetch place photos for all assigned places. @@ -160,8 +167,18 @@ export async function downloadTripPDF({ trip, days, places, assignments, categor const totalAssigned = new Set( Object.values(assignments || {}).flatMap(a => a.map(x => x.place?.id)).filter(Boolean) ).size - const totalCost = Object.values(assignments || {}) - .flatMap(a => a).reduce((s, a) => s + (Number(a.place?.price) || 0), 0) + // The PDF is a trip-scoped, shareable document, so totals stay in the trip's + // own currency. Rates are resolved ONCE before any HTML is built so the cover + // stat and every day header agree; all-same-currency trips skip the FX fetch + // entirely (offline export keeps working), and a failed fetch degrades to + // per-currency breakdowns instead of mislabeled sums (#1561). + const tripCur = (trip?.currency || 'EUR').toUpperCase() + const allCostEntries: MoneyEntry[] = Object.values(assignments || {}) + .flatMap(a => a) + .map(a => ({ amount: Number(a.place?.price) || 0, currency: a.place?.currency || tripCur })) + const needsFx = allCostEntries.some(e => e.amount > 0 && e.currency.toUpperCase() !== tripCur) + const fxRates = needsFx ? await fetchExchangeRates(tripCur) : null + const totalCostLabel = formatMoneySum(allCostEntries, tripCur, loc || 'en', fxRates) // Span helpers for multi-day transport (mirrors DayPlanSidebar logic) const pdfGetDayOrder = (d: Day) => d.day_number @@ -204,7 +221,7 @@ export async function downloadTripPDF({ trip, days, places, assignments, categor const daysHtml = sorted.map((day, di) => { const assigned = assignments[String(day.id)] || [] const notes = (dayNotes || []).filter(n => n.day_id === day.id) - const cost = dayCost(assignments, day.id, loc) + const cost = dayCost(assignments, day.id, loc, tripCur, fxRates) // Reservations for this day (hotel rendered via accommodations block; car middle-phase rendered in sidebar header only) const dayReservations = pdfGetTransportForDay(day.id) @@ -320,7 +337,7 @@ export async function downloadTripPDF({ trip, days, places, assignments, categor const chips = [ place.place_time ? `${svgClock}${escHtml(place.place_time)}` : '', - place.price && parseFloat(place.price) > 0 ? `${svgEuro}${Number(place.price).toLocaleString(loc)} EUR` : '', + place.price && parseFloat(place.price) > 0 ? `${svgMoney}${formatMoney(Number(place.price), place.currency || trip.currency, loc)}` : '', ].filter(Boolean).join('') return ` @@ -495,7 +512,11 @@ export async function downloadTripPDF({ trip, days, places, assignments, categor .day-title { font-size: 13px; font-weight: 600; color: #fff; flex: 1; } .day-date { font-size: 9px; color: rgba(255,255,255,0.45); } .day-cost { font-size: 9px; font-weight: 600; color: rgba(255,255,255,0.65); } - .day-body { padding: 12px 28px 6px; } + /* The gap under the header bar must sit inside the repeated cell: a block-start + padding on .day-body is only painted on the box's first fragment, so overflow pages + would render their first card flush against the bar (#1531). */ + .day-header > tr > td { padding-bottom: 12px; } + .day-body { padding: 0 28px 6px; } /* accommodation info */ .day-accommodations-overview { font-size: 12px; } @@ -620,8 +641,8 @@ export async function downloadTripPDF({ trip, days, places, assignments, categor
    ${totalAssigned}
    ${escHtml(tr('pdf.planned'))}
    - ${totalCost > 0 ? `
    -
    ${totalCost.toLocaleString(loc)}
    + ${totalCostLabel ? `
    +
    ${totalCostLabel}
    ${escHtml(tr('pdf.costLabel'))}
    ` : ''}
    diff --git a/client/src/components/Packing/ApplyTemplateButton.tsx b/client/src/components/Packing/ApplyTemplateButton.tsx index cd2ea129e..7fa920f98 100644 --- a/client/src/components/Packing/ApplyTemplateButton.tsx +++ b/client/src/components/Packing/ApplyTemplateButton.tsx @@ -13,13 +13,14 @@ interface Template { interface ApplyTemplateButtonProps { tripId: number + visibility: 'common' | 'personal' style: React.CSSProperties className?: string } // Dropdown-Button um ein Packing-Template auf den aktuellen Trip anzuwenden. // Rendert nichts wenn keine Templates existieren. -export default function ApplyTemplateButton({ tripId, style, className }: ApplyTemplateButtonProps): React.ReactElement | null { +export default function ApplyTemplateButton({ tripId, visibility, style, className }: ApplyTemplateButtonProps): React.ReactElement | null { const [templates, setTemplates] = useState([]) const [open, setOpen] = useState(false) const [applying, setApplying] = useState(false) @@ -43,7 +44,7 @@ export default function ApplyTemplateButton({ tripId, style, className }: ApplyT const handleApply = async (templateId: number) => { setApplying(true) try { - const data = await packingApi.applyTemplate(tripId, templateId) + const data = await packingApi.applyTemplate(tripId, templateId, visibility) useTripStore.setState(s => ({ packingItems: [...s.packingItems, ...(data.items || [])] })) toast.success(t('packing.templateApplied', { count: data.count })) setOpen(false) diff --git a/client/src/components/Packing/PackingListPanel.test.tsx b/client/src/components/Packing/PackingListPanel.test.tsx index 881a2ca85..bd15afb4f 100644 --- a/client/src/components/Packing/PackingListPanel.test.tsx +++ b/client/src/components/Packing/PackingListPanel.test.tsx @@ -1159,6 +1159,48 @@ describe('PackingListPanel', () => { await waitFor(() => expect(applyCalled).toBe(true)); }); + // #1565: the template used to always land in the shared pool, whichever tab was open. + it('FE-COMP-PACKING-061a: applying a template from "My List" sends the personal view', async () => { + const user = userEvent.setup(); + let applyBody: Record | null = null; + server.use( + http.get('/api/trips/:id/packing/templates', () => + HttpResponse.json({ templates: [{ id: 5, name: 'Beach Trip', item_count: 12 }] }) + ), + http.post('/api/trips/1/packing/apply-template/5', async ({ request }) => { + applyBody = (await request.json()) as Record; + return HttpResponse.json({ items: [], count: 12 }); + }) + ); + render(); + + await user.click(await screen.findByText('My list')); + await user.click(await screen.findByText('Apply template')); + await user.click(await screen.findByText('Beach Trip')); + + await waitFor(() => expect(applyBody).toEqual({ visibility: 'personal' })); + }); + + it('FE-COMP-PACKING-061b: applying a template from the shared tab sends the common view', async () => { + const user = userEvent.setup(); + let applyBody: Record | null = null; + server.use( + http.get('/api/trips/:id/packing/templates', () => + HttpResponse.json({ templates: [{ id: 5, name: 'Beach Trip', item_count: 12 }] }) + ), + http.post('/api/trips/1/packing/apply-template/5', async ({ request }) => { + applyBody = (await request.json()) as Record; + return HttpResponse.json({ items: [], count: 12 }); + }) + ); + render(); + + await user.click(await screen.findByText('Apply template')); + await user.click(await screen.findByText('Beach Trip')); + + await waitFor(() => expect(applyBody).toEqual({ visibility: 'common' })); + }); + it('FE-COMP-PACKING-062: handleBulkImport calls import API and closes modal', async () => { const user = userEvent.setup(); let importBody: Record | null = null; diff --git a/client/src/components/Packing/PackingListPanelItemRow.tsx b/client/src/components/Packing/PackingListPanelItemRow.tsx index 0e4e7926f..debeb1d42 100644 --- a/client/src/components/Packing/PackingListPanelItemRow.tsx +++ b/client/src/components/Packing/PackingListPanelItemRow.tsx @@ -1,9 +1,10 @@ -import { useState } from 'react' +import { useRef, useState, type ReactNode } from 'react' import { useTripStore } from '../../store/tripStore' import { useToast } from '../shared/Toast' import { useTranslation } from '../../i18n' import { CheckSquare, Square, Trash2, Plus, Pencil, Package, GripVertical, UserRound, Users, HandHelping, + MoreHorizontal, } from 'lucide-react' import type { PackingItem, PackingBag } from '../../types' import { katColor } from './packingListPanel.helpers' @@ -41,15 +42,18 @@ interface ArtikelZeileProps { } } -export function ArtikelZeile({ item, tripId, categories, onCategoryChange, onDelete, bagTrackingEnabled, bags = [], onCreateBag, canEdit = true, tripMembers = [], currentUserId, onSetSharing, onClone, onJoin, onLeave, drag }: ArtikelZeileProps) { +export function ArtikelZeile({ item, tripId, categories, onCategoryChange: _onCategoryChange, onDelete, bagTrackingEnabled, bags = [], onCreateBag, canEdit = true, tripMembers = [], currentUserId, onSetSharing, onClone, onJoin, onLeave, drag }: ArtikelZeileProps) { const isPlaceholder = item.name === PACKING_PLACEHOLDER_NAME const [editing, setEditing] = useState(false) const [editName, setEditName] = useState(isPlaceholder ? '' : item.name) const [hovered, setHovered] = useState(false) const [showCatPicker, setShowCatPicker] = useState(false) const [showBagPicker, setShowBagPicker] = useState(false) + const [showItemMenu, setShowItemMenu] = useState(false) + const [showMenuCategories, setShowMenuCategories] = useState(false) const [bagInlineCreate, setBagInlineCreate] = useState(false) const [bagInlineName, setBagInlineName] = useState('') + const itemMenuBtnRef = useRef(null) const { togglePackingItem, updatePackingItem, deletePackingItem } = useTripStore() const toast = useToast() const { t } = useTranslation() @@ -80,16 +84,19 @@ export function ArtikelZeile({ item, tripId, categories, onCategoryChange, onDel const handleCatChange = async (cat: string) => { setShowCatPicker(false) + setShowMenuCategories(false) + setShowItemMenu(false) if (cat === item.category) return try { await updatePackingItem(tripId, item.id, { category: cat }) } catch { toast.error(t('common.error')) } } const canDrag = canEdit && !isPlaceholder && !!drag + const selectedBag = bags.find(b => b.id === item.bag_id) return (
    setHovered(true)} onMouseLeave={() => { setHovered(false); setShowCatPicker(false); setShowBagPicker(false) }} onDragOver={canDrag ? (e => { e.preventDefault(); e.dataTransfer.dropEffect = 'move'; drag!.onOver(item.id) }) : undefined} @@ -162,30 +169,31 @@ export function ArtikelZeile({ item, tripId, categories, onCategoryChange, onDel {/* Sharing badges (#858 three-tier) */} {!isPlaceholder && sharedToMe && ( - {t('packing.takenCareOf', { name: item.owner_username || '' })} )} {!isPlaceholder && sharedByMe && ( - r.username).join(', ')} + r.username).join(', ')} style={{ display: 'inline-flex', alignItems: 'center', gap: 3, flexShrink: 0, fontSize: 'calc(10px * var(--fs-scale-caption, 1))', fontWeight: 600, color: 'var(--text-muted)', background: 'var(--bg-tertiary)', padding: '1px 7px', borderRadius: 99 }}> {t('packing.sharedWithCount', { count: recipients.length })} )} {!isPlaceholder && broughtBy && ( - {broughtBy}{contributors.length > 0 ? ` +${contributors.length}` : ''} )} - {/* Quantity */} - {canEdit && updatePackingItem(tripId, item.id, { quantity: qty })} />} +
    + {/* Quantity */} + {canEdit && updatePackingItem(tripId, item.id, { quantity: qty })} />} - {/* Weight + Bag (when enabled) */} - {bagTrackingEnabled && ( -
    + {/* Weight + Bag (when enabled) */} + {bagTrackingEnabled && ( + <>
    canEdit && setShowBagPicker(p => !p)} style={{ width: 22, height: 22, borderRadius: '50%', cursor: canEdit ? 'pointer' : 'default', padding: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', - border: item.bag_id ? `2.5px solid ${bags.find(b => b.id === item.bag_id)?.color || 'var(--border-primary)'}` : '2px dashed var(--border-primary)', - background: item.bag_id ? `${bags.find(b => b.id === item.bag_id)?.color || 'var(--border-primary)'}30` : 'transparent', + border: item.bag_id ? `2.5px solid ${selectedBag?.color || 'var(--border-primary)'}` : '2px dashed var(--border-primary)', + background: item.bag_id ? `${selectedBag?.color || 'var(--border-primary)'}30` : 'transparent', }} > {!item.bag_id && } @@ -275,11 +283,12 @@ export function ArtikelZeile({ item, tripId, categories, onCategoryChange, onDel
    )}
    -
    - )} + + )} +
    {canEdit && ( -
    +
    )} + + {canEdit && ( +
    + + {showItemMenu && (() => { + const rect = itemMenuBtnRef.current?.getBoundingClientRect() + return ( + <> +
    { setShowItemMenu(false); setShowMenuCategories(false) }} /> +
    +
    + {t('packing.quantity')} + updatePackingItem(tripId, item.id, { quantity: qty })} /> +
    + + {bagTrackingEnabled && ( + <> +
    +
    + {t('packing.totalWeight')} +
    + { + const v = raw === '' ? null : parseInt(raw) + try { await updatePackingItem(tripId, item.id, { weight_grams: v }) } catch { toast.error(t('packing.toast.saveError')) } + }} + placeholder="—" + style={{ width: 42, border: 'none', fontSize: 'calc(12px * var(--fs-scale-body, 1))', textAlign: 'right', fontFamily: 'inherit', outline: 'none', color: 'var(--text-secondary)', background: 'transparent', padding: 0 }} + /> + g +
    +
    +
    + } label={selectedBag?.name || t('packing.noBag')} onClick={async () => { + if (item.bag_id) { + try { await updatePackingItem(tripId, item.id, { bag_id: null }) } catch { toast.error(t('packing.toast.saveError')) } + } + }} /> + {bags.map(b => ( + } label={b.name} active={item.bag_id === b.id} onClick={async () => { + setShowItemMenu(false) + try { await updatePackingItem(tripId, item.id, { bag_id: b.id }) } catch { toast.error(t('packing.toast.saveError')) } + }} /> + ))} +
    + + )} + +
    + } label={t('packing.changeCategory')} onClick={() => setShowMenuCategories(v => !v)} /> + {showMenuCategories && ( +
    + {categories.map(cat => ( + } label={cat} active={cat === (item.category || t('packing.defaultCategory'))} onClick={() => handleCatChange(cat)} /> + ))} +
    + )} + + {canShare && onClone && onJoin && onLeave && ( +
    + {t('packing.share')} + +
    + )} + +
    + } label={t('common.rename')} onClick={() => { setEditing(true); setShowItemMenu(false) }} /> + } label={t('common.delete')} danger onClick={() => { setShowItemMenu(false); handleDelete() }} /> +
    + + ) + })()} +
    + )}
    ) } + +interface OverflowMenuItemProps { + icon: ReactNode + label: string + onClick: () => void + active?: boolean + danger?: boolean +} + +function OverflowMenuItem({ icon, label, onClick, active = false, danger = false }: OverflowMenuItemProps) { + return ( + + ) +} diff --git a/client/src/components/Packing/usePackingListPanel.ts b/client/src/components/Packing/usePackingListPanel.ts index b4e04c24e..f4f388954 100644 --- a/client/src/components/Packing/usePackingListPanel.ts +++ b/client/src/components/Packing/usePackingListPanel.ts @@ -33,6 +33,9 @@ export interface PackingListPanelProps { clearCheckedSignal?: number saveTemplateSignal?: number inlineHeader?: boolean + // Lifted so an out-of-panel Apply Template button knows the active view (#1565). + view?: 'common' | 'personal' + onViewChange?: (view: 'common' | 'personal') => void } /** @@ -42,11 +45,13 @@ export interface PackingListPanelProps { * sections below render header, filters, the grouped list, the bag sidebar/ * modal and the import dialog. */ -export function usePackingList({ tripId, items, openImportSignal = 0, clearCheckedSignal = 0, saveTemplateSignal = 0, inlineHeader = true }: PackingListPanelProps) { +export function usePackingList({ tripId, items, openImportSignal = 0, clearCheckedSignal = 0, saveTemplateSignal = 0, inlineHeader = true, view: viewProp, onViewChange }: PackingListPanelProps) { const [filter, setFilter] = useState('alle') // 'alle' | 'offen' | 'erledigt' // Three-tier sharing (#858): 'common' = the group pool (where existing items // live — non-breaking), 'personal' = my own list (private + shared-to-me). - const [view, setView] = useState<'common' | 'personal'>('common') + const [ownView, setOwnView] = useState<'common' | 'personal'>('common') + const view = viewProp ?? ownView + const setView = onViewChange ?? setOwnView const [addingCategory, setAddingCategory] = useState(false) const [newCatName, setNewCatName] = useState('') const { addPackingItem, updatePackingItem, deletePackingItem, togglePackingItem, reorderPackingItems, @@ -307,7 +312,7 @@ export function usePackingList({ tripId, items, openImportSignal = 0, clearCheck const handleApplyTemplate = async (templateId: number) => { setApplyingTemplate(true) try { - const data = await packingApi.applyTemplate(tripId, templateId) + const data = await packingApi.applyTemplate(tripId, templateId, view) useTripStore.setState(s => ({ packingItems: [...s.packingItems, ...(data.items || [])] })) toast.success(t('packing.templateApplied', { count: data.count })) setShowTemplateDropdown(false) diff --git a/client/src/components/Planner/AirTrailImportModal.test.tsx b/client/src/components/Planner/AirTrailImportModal.test.tsx new file mode 100644 index 000000000..1f13587a2 --- /dev/null +++ b/client/src/components/Planner/AirTrailImportModal.test.tsx @@ -0,0 +1,202 @@ +// FE-PLANNER-AIRTRAIL-001 to FE-PLANNER-AIRTRAIL-008 +import { render, screen, waitFor } from '../../../tests/helpers/render'; +import userEvent from '@testing-library/user-event'; +import { http, HttpResponse } from 'msw'; +import { server } from '../../../tests/helpers/msw/server'; +import { useAuthStore } from '../../store/authStore'; +import { useTripStore } from '../../store/tripStore'; +import { resetAllStores, seedStore } from '../../../tests/helpers/store'; +import { buildUser, buildTrip, buildReservation } from '../../../tests/helpers/factories'; +import type { AirtrailFlight } from '@trek/shared'; +import AirTrailImportModal, { detectConnections } from './AirTrailImportModal'; + +const flight = (over: Partial = {}): AirtrailFlight => ({ + id: '101', + fromCode: 'BRU', + fromName: 'Brussels', + toCode: 'HEL', + toName: 'Helsinki-Vantaa', + date: '2026-08-01', + departure: '2026-08-01T06:00:00.000+00:00', + arrival: '2026-08-01T09:30:00.000+00:00', + airline: 'Finnair', + flightNumber: 'AY1502', + aircraft: null, + seatClass: 'economy', + ...over, +}); + +const legHelJfk = (): AirtrailFlight => + flight({ + id: '102', + fromCode: 'HEL', + fromName: 'Helsinki-Vantaa', + toCode: 'JFK', + toName: 'John F. Kennedy Intl.', + departure: '2026-08-01T11:00:00.000+00:00', + arrival: '2026-08-01T19:00:00.000+00:00', + flightNumber: 'AY15', + }); + +const unrelatedFlight = (): AirtrailFlight => + flight({ + id: '103', + fromCode: 'LHR', + fromName: 'London Heathrow', + toCode: 'JFK', + toName: 'John F. Kennedy Intl.', + date: '2026-08-05', + departure: '2026-08-05T10:00:00.000+00:00', + arrival: '2026-08-05T18:00:00.000+00:00', + flightNumber: 'BA117', + }); + +describe('detectConnections (#1535)', () => { + it('FE-PLANNER-AIRTRAIL-001: chains flights that connect at the same airport within 24h', () => { + const chains = detectConnections([legHelJfk(), flight(), unrelatedFlight()]); + expect(chains).toHaveLength(1); + expect(chains[0].map(f => f.id)).toEqual(['101', '102']); + }); + + it('FE-PLANNER-AIRTRAIL-002: does not chain when the layover exceeds 24h', () => { + const late = { ...legHelJfk(), date: '2026-08-03', departure: '2026-08-03T11:00:00.000+00:00', arrival: '2026-08-03T19:00:00.000+00:00' }; + expect(detectConnections([flight(), late])).toHaveLength(0); + }); + + it('FE-PLANNER-AIRTRAIL-003: skips flights without instants instead of guessing', () => { + expect(detectConnections([flight({ departure: null, arrival: null }), legHelJfk()])).toHaveLength(0); + }); + + it('FE-PLANNER-AIRTRAIL-009: does not chain an out-and-back return into a bogus connection', () => { + const returnFlight = flight({ + id: '105', + fromCode: 'HEL', + fromName: 'Helsinki-Vantaa', + toCode: 'BRU', + toName: 'Brussels', + departure: '2026-08-01T18:00:00.000+00:00', + arrival: '2026-08-01T21:30:00.000+00:00', + flightNumber: 'AY1503', + }); + expect(detectConnections([flight(), returnFlight])).toHaveLength(0); + }); +}); + +describe('AirTrailImportModal', () => { + const defaultProps = { isOpen: true, onClose: vi.fn(), tripId: 1 }; + + beforeEach(() => { + resetAllStores(); + seedStore(useAuthStore, { user: buildUser(), isAuthenticated: true }); + seedStore(useTripStore, { + trip: buildTrip({ id: 1, start_date: '2026-08-01', end_date: '2026-08-10' }), + reservations: [], + }); + server.use( + http.get('/api/integrations/airtrail/flights', () => + HttpResponse.json({ flights: [flight(), legHelJfk(), unrelatedFlight()] }), + ), + http.get('/api/trips/1/reservations', () => HttpResponse.json({ reservations: [] })), + ); + }); + + it('FE-PLANNER-AIRTRAIL-004: offers to join a detected connection, on by default', async () => { + render(); + const joinRow = await screen.findByText(/one flight with a layover in HEL/i); + expect(joinRow).toBeInTheDocument(); + // No join offer for the unrelated flight. + expect(screen.queryByText(/layover in JFK/i)).not.toBeInTheDocument(); + }); + + it('FE-PLANNER-AIRTRAIL-005: sends the chain as a connection on import', async () => { + const user = userEvent.setup(); + let body: any = null; + server.use( + http.post('/api/trips/1/reservations/import/airtrail', async ({ request }) => { + body = await request.json(); + return HttpResponse.json({ imported: body.flightIds, skipped: [] }); + }), + ); + render(); + await screen.findByText(/one flight with a layover in HEL/i); + await user.click(screen.getByRole('button', { name: /Import 3/i })); + await waitFor(() => expect(body).not.toBeNull()); + expect([...body.flightIds].sort()).toEqual(['101', '102', '103']); + expect(body.connections).toEqual([['101', '102']]); + }); + + it('FE-PLANNER-AIRTRAIL-006: sends no connection when the join is toggled off', async () => { + const user = userEvent.setup(); + let body: any = null; + server.use( + http.post('/api/trips/1/reservations/import/airtrail', async ({ request }) => { + body = await request.json(); + return HttpResponse.json({ imported: body.flightIds, skipped: [] }); + }), + ); + render(); + await user.click(await screen.findByText(/one flight with a layover in HEL/i)); + await user.click(screen.getByRole('button', { name: /Import 3/i })); + await waitFor(() => expect(body).not.toBeNull()); + expect(body.connections).toBeUndefined(); + }); + + it('FE-PLANNER-AIRTRAIL-007: re-enabling the join selects all of its legs', async () => { + const user = userEvent.setup(); + render(); + const joinRow = await screen.findByText(/one flight with a layover in HEL/i); + // Deselect one member — the join reads unchecked, one click brings both back. + await user.click(screen.getByText('Finnair AY15')); + expect(screen.getByRole('button', { name: /Import 2/i })).toBeInTheDocument(); + await user.click(joinRow); + expect(screen.getByRole('button', { name: /Import 3/i })).toBeInTheDocument(); + }); + + it('FE-PLANNER-AIRTRAIL-010: a surviving sub-chain keeps its join offer when a later leg was already imported', async () => { + const legJfkLax = flight({ + id: '106', + fromCode: 'JFK', + fromName: 'John F. Kennedy Intl.', + toCode: 'LAX', + toName: 'Los Angeles Intl.', + departure: '2026-08-01T21:00:00.000+00:00', + arrival: '2026-08-02T00:30:00.000+00:00', + flightNumber: 'AY99', + }); + seedStore(useTripStore, { + trip: buildTrip({ id: 1, start_date: '2026-08-01', end_date: '2026-08-10' }), + reservations: [ + buildReservation({ type: 'flight', external_source: 'airtrail', external_id: '106' }) as any, + ], + }); + server.use( + http.get('/api/integrations/airtrail/flights', () => + HttpResponse.json({ flights: [flight(), legHelJfk(), legJfkLax] }), + ), + ); + render(); + // BRU→HEL→JFK still connects even though JFK→LAX is gone from the pool. + expect(await screen.findByText(/one flight with a layover in HEL/i)).toBeInTheDocument(); + expect(screen.getByText(/^Imported$/)).toBeInTheDocument(); + }); + + it('FE-PLANNER-AIRTRAIL-008: legs of a joined import are marked imported via metadata.airtrail_ids', async () => { + seedStore(useTripStore, { + trip: buildTrip({ id: 1, start_date: '2026-08-01', end_date: '2026-08-10' }), + reservations: [ + buildReservation({ + type: 'flight', + external_source: 'airtrail', + external_id: '101', + metadata: JSON.stringify({ airtrail_ids: ['101', '102'] }), + }) as any, + ], + }); + render(); + await screen.findByText('Finnair AY1502'); + // Both legs disabled — including the one whose id only lives in the metadata. + expect(screen.getAllByText(/^Imported$/)).toHaveLength(2); + // A chain with an imported member cannot be joined again. + expect(screen.queryByText(/one flight with a layover/i)).not.toBeInTheDocument(); + }); +}); diff --git a/client/src/components/Planner/AirTrailImportModal.tsx b/client/src/components/Planner/AirTrailImportModal.tsx index 08c352d20..e1e9e69e3 100644 --- a/client/src/components/Planner/AirTrailImportModal.tsx +++ b/client/src/components/Planner/AirTrailImportModal.tsx @@ -7,6 +7,7 @@ import { useTranslation } from '../../i18n' import { useToast } from '../shared/Toast' import { airtrailApi, reservationsApi } from '../../api/client' import { useTripStore } from '../../store/tripStore' +import { parseReservationMetadata } from '../../utils/flightLegs' interface AirTrailImportModalProps { isOpen: boolean @@ -15,6 +16,40 @@ interface AirTrailImportModalProps { pushUndo?: (label: string, undoFn: () => Promise | void) => void } +/** + * Ordered chains of connecting flights — each arrives where the next departs, + * onward within 24 h — that the picker offers to import as ONE multi-leg + * booking with the connection as a layover stop (#1535). A flight landing back + * at the chain's origin is a return, not a connection, so a same-day + * out-and-back never gets a join offer. Same rules the server re-validates + * with. + */ +export function detectConnections(flights: AirtrailFlight[]): AirtrailFlight[][] { + const sorted = flights + .filter(f => f.departure && f.arrival && f.fromCode && f.toCode) + .sort((a, b) => Date.parse(a.departure!) - Date.parse(b.departure!)) + const chains: AirtrailFlight[][] = [] + let chain: AirtrailFlight[] = [] + for (const f of sorted) { + const prev = chain[chain.length - 1] + if (prev) { + const gap = Date.parse(f.departure!) - Date.parse(prev.arrival!) + if ( + prev.toCode!.toUpperCase() === f.fromCode!.toUpperCase() && + f.toCode!.toUpperCase() !== chain[0].fromCode!.toUpperCase() && + gap >= 0 && gap <= 24 * 3600 * 1000 + ) { + chain.push(f) + continue + } + } + if (chain.length > 1) chains.push(chain) + chain = [f] + } + if (chain.length > 1) chains.push(chain) + return chains +} + /** Locale-aware date (e.g. de → 13.06.2026, en-US → 06/13/2026). */ function fmtDate(d: string | null, locale: string): string { if (!d) return '' @@ -44,11 +79,16 @@ export default function AirTrailImportModal({ isOpen, onClose, tripId, pushUndo const [flights, setFlights] = useState([]) const [selected, setSelected] = useState>(() => new Set()) - // AirTrail flight ids already linked to a reservation in this trip. + // AirTrail flight ids already linked to a reservation in this trip. A joined + // multi-leg import carries only its first leg in external_id — the other legs + // sit in metadata.airtrail_ids (#1535). const importedIds = useMemo(() => { const set = new Set() for (const r of reservations) { - if (r.external_source === 'airtrail' && r.external_id) set.add(String(r.external_id)) + if (r.external_source !== 'airtrail') continue + if (r.external_id) set.add(String(r.external_id)) + const ids = parseReservationMetadata(r).airtrail_ids + if (Array.isArray(ids)) for (const id of ids) set.add(String(id)) } return set }, [reservations]) @@ -56,10 +96,27 @@ export default function AirTrailImportModal({ isOpen, onClose, tripId, pushUndo const inRange = (f: AirtrailFlight): boolean => !!(f.date && trip?.start_date && trip?.end_date && f.date >= trip.start_date && f.date <= trip.end_date) + // Detected connection chains that can still be joined. Already-imported + // flights are excluded BEFORE detection so a surviving sub-chain (e.g. the + // first two legs when the third was imported earlier) still gets its offer. + // Joining is on by default; joinOff remembers the chains the user opted out of. + const chains = useMemo( + () => detectConnections(flights.filter(f => !importedIds.has(f.id))), + [flights, importedIds], + ) + const chainKey = (chain: AirtrailFlight[]) => chain.map(f => f.id).join('+') + const chainOf = useMemo(() => { + const map = new Map() + for (const chain of chains) for (const f of chain) map.set(f.id, chain) + return map + }, [chains]) + const [joinOff, setJoinOff] = useState>(() => new Set()) + useEffect(() => { if (!isOpen) return setError('') setSelected(new Set()) + setJoinOff(new Set()) setLoading(true) airtrailApi .flights() @@ -94,6 +151,28 @@ export default function AirTrailImportModal({ isOpen, onClose, tripId, pushUndo }) } + const chainJoined = (chain: AirtrailFlight[]) => + !joinOff.has(chainKey(chain)) && chain.every(f => selected.has(f.id)) + + const toggleJoin = (chain: AirtrailFlight[]) => { + const key = chainKey(chain) + if (chainJoined(chain)) { + setJoinOff(prev => new Set(prev).add(key)) + } else { + // Turning the join on implies wanting all of its legs. + setJoinOff(prev => { + const next = new Set(prev) + next.delete(key) + return next + }) + setSelected(prev => { + const next = new Set(prev) + for (const f of chain) next.add(f.id) + return next + }) + } + } + const handleClose = () => { onClose() } const handleImport = async () => { @@ -102,7 +181,8 @@ export default function AirTrailImportModal({ isOpen, onClose, tripId, pushUndo setImporting(true) setError('') try { - const result: AirtrailImportResult = await airtrailApi.import(tripId, ids) + const connections = chains.filter(chainJoined).map(chain => chain.map(f => f.id)) + const result: AirtrailImportResult = await airtrailApi.import(tripId, ids, connections) await loadReservations(tripId) const imported = result.imported ?? [] @@ -175,6 +255,58 @@ export default function AirTrailImportModal({ isOpen, onClose, tripId, pushUndo ) } + const renderChain = (chain: AirtrailFlight[]) => { + const joined = chainJoined(chain) + const stops = chain.slice(0, -1).map(f => f.toCode ?? f.toName ?? '?').join(', ') + return ( +
    + {chain.map(renderFlight)} + +
    + ) + } + + // A chain renders once as a group, at the position of its first listed leg — + // its other legs are swallowed wherever else they would appear. Computed per + // section up front so a chain straddling the trip range can't leave the other + // section holding nothing but its header. + const sectionItems = useMemo(() => { + const rendered = new Set() + const build = (list: AirtrailFlight[]) => + list.flatMap((f): Array<{ key: string; chain?: AirtrailFlight[]; flight?: AirtrailFlight }> => { + const chain = chainOf.get(f.id) + if (!chain) return [{ key: f.id, flight: f }] + const key = chain.map(c => c.id).join('+') + if (rendered.has(key)) return [] + rendered.add(key) + return [{ key, chain }] + }) + return { during: build(during), others: build(others) } + }, [during, others, chainOf]) + + const renderItem = (item: { chain?: AirtrailFlight[]; flight?: AirtrailFlight }) => + item.chain ? renderChain(item.chain) : renderFlight(item.flight!) + return ReactDOM.createPortal(
    )} - {!loading && during.length > 0 && ( + {!loading && sectionItems.during.length > 0 && ( <>
    {t('reservations.airtrail.duringTrip')}
    - {during.map(renderFlight)} + {sectionItems.during.map(renderItem)} )} - {!loading && others.length > 0 && ( + {!loading && sectionItems.others.length > 0 && ( <> -
    0 ? 14 : 2}px 0 8px` }}> +
    0 ? 14 : 2}px 0 8px` }}> {t('reservations.airtrail.otherFlights')}
    - {others.map(renderFlight)} + {sectionItems.others.map(renderItem)} )} diff --git a/client/src/components/Planner/DayDetailPanel.test.tsx b/client/src/components/Planner/DayDetailPanel.test.tsx index ef5aa39ec..eb0b47936 100644 --- a/client/src/components/Planner/DayDetailPanel.test.tsx +++ b/client/src/components/Planner/DayDetailPanel.test.tsx @@ -564,6 +564,30 @@ describe('DayDetailPanel', () => { }); }); + it('FE-PLANNER-DAYDETAIL-067: hotel picker defaults check-out to the day AFTER check-in', async () => { + const day2 = buildDay({ id: 2, trip_id: 1, date: '2025-06-16', title: 'Day 2' }); + const day3 = buildDay({ id: 3, trip_id: 1, date: '2025-06-17', title: 'Day 3' }); + render(); + await userEvent.click(await screen.findByText(/Add accommodation/i)); + await waitFor(() => { + const portal = document.body.querySelector('[style*="z-index: 99999"]'); + // Closed selects render only their chosen label: check-in on the opened + // day, check-out on the following one — nobody stays a few hours. + expect(portal?.textContent).toContain('Day in Paris'); + expect(portal?.textContent).toContain('Day 2'); + expect(portal?.textContent).not.toContain('Day 3'); + }); + }); + + it('FE-PLANNER-DAYDETAIL-068: hotel picker falls back to a same-day range on the last trip day', async () => { + render(); + await userEvent.click(await screen.findByText(/Add accommodation/i)); + await waitFor(() => { + const portal = document.body.querySelector('[style*="z-index: 99999"]'); + expect(portal?.textContent?.match(/Day in Paris/g)).toHaveLength(2); + }); + }); + it('FE-PLANNER-DAYDETAIL-034: accommodation with all fields shows full details grid', async () => { server.use( http.get('/api/trips/1/accommodations', () => diff --git a/client/src/components/Planner/DayPlanSidebar.test.tsx b/client/src/components/Planner/DayPlanSidebar.test.tsx index 42c15af61..96d3040c3 100644 --- a/client/src/components/Planner/DayPlanSidebar.test.tsx +++ b/client/src/components/Planner/DayPlanSidebar.test.tsx @@ -1,6 +1,9 @@ // FE-PLANNER-DAYPLAN-001 to FE-PLANNER-DAYPLAN-042 import { render, screen, waitFor, fireEvent } from '../../../tests/helpers/render' import userEvent from '@testing-library/user-event' +import { http, HttpResponse } from 'msw' +import { server } from '../../../tests/helpers/msw/server' +import { clearExchangeRateCache } from '../../hooks/useExchangeRates' import { useAuthStore } from '../../store/authStore' import { useTripStore } from '../../store/tripStore' import { useSettingsStore } from '../../store/settingsStore' @@ -130,6 +133,9 @@ beforeEach(() => { vi.clearAllMocks() sessionStorage.clear() localStorage.clear() + // Cost totals fetch FX rates for their base currency; keep the suite hermetic. + clearExchangeRateCache() + server.use(http.get('https://api.frankfurter.dev/v2/rates', () => HttpResponse.json([]))) // Reset mutable day-notes state mockDayNotesState.noteUi = {} mockDayNotesState.dayNotes = {} @@ -386,6 +392,53 @@ describe('DayPlanSidebar', () => { expect(screen.queryByText('Alexanderplatz')).not.toBeInTheDocument() }) + it('FE-PLANNER-DAYPLAN-106: the toolbar button shows "show all" and calls onToggleAllConnections when not all routes are shown', async () => { + const user = userEvent.setup() + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const res1 = { + ...buildReservation({ id: 401, type: 'flight' }), + endpoints: [ + { role: 'from', sequence: 0, name: 'A', code: null, lat: 1, lng: 2, timezone: null, local_time: null, local_date: null }, + { role: 'to', sequence: 1, name: 'B', code: null, lat: 3, lng: 4, timezone: null, local_time: null, local_date: null }, + ], + } + const onToggleAllConnections = vi.fn() + render() + await user.click(screen.getByLabelText('Show all booking routes')) + expect(onToggleAllConnections).toHaveBeenCalledTimes(1) + }) + + it('FE-PLANNER-DAYPLAN-107: the toolbar button reads "hide" once allConnectionsShown is true, and calls onToggleAllConnections on click', async () => { + const user = userEvent.setup() + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const res1 = { + ...buildReservation({ id: 401, type: 'flight' }), + endpoints: [ + { role: 'from', sequence: 0, name: 'A', code: null, lat: 1, lng: 2, timezone: null, local_time: null, local_date: null }, + { role: 'to', sequence: 1, name: 'B', code: null, lat: 3, lng: 4, timezone: null, local_time: null, local_date: null }, + ], + } + const onToggleAllConnections = vi.fn() + render() + await user.click(screen.getByLabelText('Hide all booking routes')) + expect(onToggleAllConnections).toHaveBeenCalledTimes(1) + }) + + it('FE-PLANNER-DAYPLAN-108: the toolbar button is absent when the trip has no routable reservation', () => { + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + render() + expect(screen.queryByLabelText('Show all booking routes')).not.toBeInTheDocument() + expect(screen.queryByLabelText('Hide all booking routes')).not.toBeInTheDocument() + }) + // ── Day info button ───────────────────────────────────────────────────── it('FE-PLANNER-DAYPLAN-018: clicking day header calls onDayDetail', async () => { @@ -602,6 +655,50 @@ describe('DayPlanSidebar', () => { expect(screen.getByText('Total Cost')).toBeInTheDocument() }) + it('FE-PLANNER-DAYPLAN-037b: converts foreign-currency prices into the display currency (#1561)', async () => { + server.use(http.get('https://api.frankfurter.dev/v2/rates', ({ request }) => { + expect(new URL(request.url).searchParams.get('base')).toBe('USD') + return HttpResponse.json([{ quote: 'NOK', rate: 10 }]) // 10 NOK per 1 USD + })) + seedStore(useSettingsStore, { settings: { time_format: '24h', default_currency: 'USD' } } as any) + const placeUsd = buildPlace({ id: 1, name: 'Hotel', price: 25, currency: 'USD' } as any) + const placeNok = buildPlace({ id: 2, name: 'Museum', price: 250, currency: null } as any) // implicit trip currency + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + render() + // $25 + 250 NOK / 10 = $50, marked as approximate; footer and day header agree. + await waitFor(() => expect(screen.getByText('≈ $50.00')).toBeInTheDocument()) + expect(screen.getByText('≈ $50')).toBeInTheDocument() + }) + + it('FE-PLANNER-DAYPLAN-037c: falls back to a per-currency breakdown when rates are unavailable (#1561)', async () => { + server.use(http.get('https://api.frankfurter.dev/v2/rates', () => HttpResponse.error())) + const placeUsd = buildPlace({ id: 1, name: 'Hotel', price: 2730.27, currency: 'USD' } as any) + const placeNok = buildPlace({ id: 2, name: 'Museum', price: 2500, currency: 'NOK' } as any) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + render() + // The USD amount must never be folded into a NOK-labeled number (the #1561 bug): + // footer keeps each currency separate, base (NOK) first. + await waitFor(() => expect(screen.getByText(/kr.*\+.*\$2,730\.27|2\s?500,00\s?kr.*\+/)).toBeInTheDocument()) + expect(screen.queryByText(/≈/)).toBeNull() + expect(screen.queryByText(/5\s?230/)).toBeNull() + }) + // ── Route tools (Optimize / Google Maps) ──────────────────────────────── it('FE-PLANNER-DAYPLAN-038: optimize button calls onReorder with 3 geo-places', async () => { diff --git a/client/src/components/Planner/DayPlanSidebar.tsx b/client/src/components/Planner/DayPlanSidebar.tsx index 4bd3dbaeb..2b503f576 100644 --- a/client/src/components/Planner/DayPlanSidebar.tsx +++ b/client/src/components/Planner/DayPlanSidebar.tsx @@ -28,8 +28,9 @@ import { getTransportForDay as _getTransportForDay, getMergedItems as _getMergedItems, type MergedItem, } from '../../utils/dayMerge' -import { formatDate, formatTime, dayTotalCost, splitReservationDateTime } from '../../utils/formatters' +import { formatDate, formatTime, dayTotalCost, formatMoneySum, splitReservationDateTime } from '../../utils/formatters' import { useDayNotes } from '../../hooks/useDayNotes' +import { useExchangeRates } from '../../hooks/useExchangeRates' import { RES_ICONS, getNoteIcon } from './DayPlanSidebar.constants' import { RouteConnector, HotelRouteConnector } from './DayPlanSidebarRouteConnector' import { MobileAddPlaceButton } from './DayPlanSidebarMobileAddPlaceButton' @@ -68,6 +69,8 @@ interface DayPlanSidebarProps { reservations?: Reservation[] visibleConnectionIds?: number[] onToggleConnection?: (reservationId: number) => void + allConnectionsShown?: boolean + onToggleAllConnections?: () => void externalTransportDetail?: Reservation | null onExternalTransportDetailHandled?: () => void onAddReservation: (dayId: number) => void @@ -96,9 +99,12 @@ interface DayPlanSidebarProps { onScrollTopChange?: (top: number) => void /** Mobile: show the route tools footer (Route toggle / Optimize / travel profile) on expanded days, since selecting a day closes the sheet */ showRouteToolsWhenExpanded?: boolean - /** Mobile: drag & drop reorder is disabled (touch-scroll hijack, #1432); the - * grip handle is hidden and the arrow reorder buttons take over instead. */ isMobile?: boolean + /** Coarse primary pointer. Drag & drop reorder is disabled here (it hijacks the + * touch-scroll gesture, #1432); the grip handle is hidden and the arrow reorder + * buttons take over instead. Distinct from isMobile, which is width-based — a + * tablet is a wide touch device and needs both. */ + isTouch?: boolean } /** @@ -118,6 +124,8 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) { reservations = [], visibleConnectionIds = [], onToggleConnection, + allConnectionsShown = false, + onToggleAllConnections, externalTransportDetail, onExternalTransportDetailHandled, onAddReservation, @@ -144,7 +152,9 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) { onScrollTopChange, showRouteToolsWhenExpanded = false, isMobile = false, + isTouch = false, } = props + const dragDisabled = isMobile || isTouch const toast = useToast() const { t, language, locale } = useTranslation() const ctxMenu = useContextMenu() @@ -235,6 +245,12 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) { }, [selectedAssignmentId, selectedPlaceId]) const currency = trip?.currency || 'EUR' + // Cost totals render in the user's display currency (falling back to the + // trip's), converting foreign-currency place prices via live FX rates — + // same base resolution as BookingCostsSection / the Costs panel (#1561). + const displayCurrency = useSettingsStore(s => s.settings.default_currency) + const costBase = (displayCurrency || currency).toUpperCase() + const { rates: fxRates } = useExchangeRates(costBase) // Drag-Daten aus dataTransfer, Ref oder window lesen (dataTransfer geht bei Re-Render verloren) const getDragData = (e) => { @@ -964,10 +980,13 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) { setDraggingId(null) } - const totalCost = useMemo(() => days.reduce((s, d) => { - const da = assignments[String(d.id)] || [] - return s + da.reduce((s2, a) => s2 + (Number(a.place?.price) || 0), 0) - }, 0), [days, assignments]) + const totalCostLabel = useMemo(() => { + const entries = days.flatMap(d => (assignments[String(d.id)] || []).map(a => ({ + amount: Number(a.place?.price) || 0, + currency: a.place?.currency || currency, + }))) + return formatMoneySum(entries, costBase, locale, fxRates) + }, [days, assignments, currency, costBase, locale, fxRates]) // Bester verfügbarer Standort für Wetter: zugewiesene Orte zuerst, dann beliebiger Reiseort const anyGeoAssignment = Object.values(assignments).flatMap(da => da).find(a => a.place?.lat && a.place?.lng) @@ -999,6 +1018,8 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) { reservations, visibleConnectionIds, onToggleConnection, + allConnectionsShown, + onToggleAllConnections, externalTransportDetail, onExternalTransportDetailHandled, onAddReservation, @@ -1027,6 +1048,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) { onScrollTopChange, showRouteToolsWhenExpanded, isMobile, + dragDisabled, toast, t, language, @@ -1095,6 +1117,8 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) { initedTransportIds, lastAutoScrolledIdRef, currency, + costBase, + fxRates, getDragData, prevDayCount, toggleDay, @@ -1119,7 +1143,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) { handleOptimize, handleDropOnDay, handleDropOnRow, - totalCost, + totalCostLabel, anyGeoAssignment, anyGeoPlace, expandedRouteDayIds, @@ -1165,6 +1189,8 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP reservations, visibleConnectionIds, onToggleConnection, + allConnectionsShown, + onToggleAllConnections, externalTransportDetail, onExternalTransportDetailHandled, onAddReservation, @@ -1193,6 +1219,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP onScrollTopChange, showRouteToolsWhenExpanded, isMobile, + dragDisabled, toast, t, language, @@ -1261,6 +1288,8 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP initedTransportIds, lastAutoScrolledIdRef, currency, + costBase, + fxRates, getDragData, prevDayCount, toggleDay, @@ -1285,7 +1314,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP handleOptimize, handleDropOnDay, handleDropOnRow, - totalCost, + totalCostLabel, anyGeoAssignment, anyGeoPlace, expandedRouteDayIds, @@ -1302,6 +1331,8 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP categories={categories} assignments={assignments} reservations={reservations} + allConnectionsShown={allConnectionsShown} + onToggleAllConnections={onToggleAllConnections} dayNotes={dayNotes} t={t} locale={locale} @@ -1328,7 +1359,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP const isSelected = selectedDayId === day.id const isExpanded = expandedDays.has(day.id) const da = getDayAssignments(day.id) - const cost = dayTotalCost(day.id, assignments, currency) + const cost = dayTotalCost(day.id, assignments, costBase, currency, locale, fxRates) const formattedDate = formatDate(day.date, locale) const loc = da.find(a => a.place?.lat && a.place?.lng) // Route tools normally need 2+ stops, but a single located place is still @@ -1657,9 +1688,10 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP return (
    { - if (!canEditDays || isMobile) { e.preventDefault(); return } + if (!canEditDays || dragDisabled) { e.preventDefault(); return } e.dataTransfer.setData('assignmentId', String(assignment.id)) e.dataTransfer.setData('fromDayId', String(day.id)) e.dataTransfer.effectAllowed = 'move' @@ -1754,7 +1786,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP opacity: isDraggingThis ? 0.4 : 1, }} > - {canEditDays && !isMobile &&
    + {canEditDays && !dragDisabled &&
    }
    { - if (!canEditDays || spanPhase === 'middle' || res.__leg || isMobile) { e.preventDefault(); return } + if (!canEditDays || spanPhase === 'middle' || res.__leg || dragDisabled) { e.preventDefault(); return } // setData is required for the drag to start reliably (Firefox) and // matches how place/note items initiate their drag. e.dataTransfer.setData('reservationId', String(res.id)) @@ -2065,7 +2097,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP opacity: draggingId === res.id ? 0.4 : spanPhase === 'middle' ? 0.65 : 1, }} > - {canEditDays && spanPhase !== 'middle' && !res.__leg && !isMobile && ( + {canEditDays && spanPhase !== 'middle' && !res.__leg && !dragDisabled && (
    @@ -2182,8 +2214,9 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP return (
    { if (!canEditDays || isMobile) { e.preventDefault(); return } e.dataTransfer.setData('noteId', String(note.id)); e.dataTransfer.setData('fromDayId', String(day.id)); e.dataTransfer.effectAllowed = 'move'; dragDataRef.current = { noteId: String(note.id), fromDayId: String(day.id) }; setDraggingId(`note-${note.id}`) }} + className="dp-row" + draggable={canEditDays && !dragDisabled} + onDragStart={e => { if (!canEditDays || dragDisabled) { e.preventDefault(); return } e.dataTransfer.setData('noteId', String(note.id)); e.dataTransfer.setData('fromDayId', String(day.id)); e.dataTransfer.effectAllowed = 'move'; dragDataRef.current = { noteId: String(note.id), fromDayId: String(day.id) }; setDraggingId(`note-${note.id}`) }} onDragEnd={() => { setDraggingId(null); setDropTargetKey(null); dragDataRef.current = null }} onDragOver={e => { e.preventDefault(); e.stopPropagation(); if (dropTargetKey !== `note-${note.id}`) setDropTargetKey(`note-${note.id}`) }} onDrop={e => { @@ -2251,7 +2284,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP transition: 'background 0.1s', cursor: 'grab', userSelect: 'none', }} > - {canEditDays && !isMobile &&
    + {canEditDays && !dragDisabled &&
    }
    @@ -2487,7 +2520,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP /> {/* Budget-Fußzeile */} - +
    ) diff --git a/client/src/components/Planner/DayPlanSidebarFooter.tsx b/client/src/components/Planner/DayPlanSidebarFooter.tsx index 6c965ccf4..789ebfbf0 100644 --- a/client/src/components/Planner/DayPlanSidebarFooter.tsx +++ b/client/src/components/Planner/DayPlanSidebarFooter.tsx @@ -1,17 +1,14 @@ -import { currencyDecimals } from '../../utils/formatters' - interface DayPlanSidebarFooterProps { - totalCost: number - currency: string + totalCostLabel: string | null t: (key: string, params?: Record) => string } -export function DayPlanSidebarFooter({ totalCost, currency, t }: DayPlanSidebarFooterProps) { - if (!(totalCost > 0)) return null +export function DayPlanSidebarFooter({ totalCostLabel, t }: DayPlanSidebarFooterProps) { + if (!totalCostLabel) return null return (
    {t('dayplan.totalCost')} - {totalCost.toFixed(currencyDecimals(currency))} {currency} + {totalCostLabel}
    ) } diff --git a/client/src/components/Planner/DayPlanSidebarToolbar.tsx b/client/src/components/Planner/DayPlanSidebarToolbar.tsx index ebe92dc29..e52ea50c8 100644 --- a/client/src/components/Planner/DayPlanSidebarToolbar.tsx +++ b/client/src/components/Planner/DayPlanSidebarToolbar.tsx @@ -1,10 +1,11 @@ import React, { useState, useRef } from 'react' -import { ChevronsDownUp, ChevronsUpDown, FileDown, Undo2, ArrowUpDown, CalendarPlus } from 'lucide-react' +import { ChevronsDownUp, ChevronsUpDown, FileDown, Undo2, ArrowUpDown, CalendarPlus, Route as RouteIcon } from 'lucide-react' import { downloadTripPDF } from '../PDF/TripPDF' import { DayReorderPopup } from './DayReorderPopup' import Tooltip from '../shared/Tooltip' import { useToast } from '../shared/Toast' import { IcsSubscribeModal } from './IcsSubscribeModal' +import { isRoutableReservation } from '../../utils/reservationRoutes' import type { Trip, Day, Place, Category, AssignmentsMap, Reservation, DayNote } from '../../types' interface DayPlanSidebarToolbarProps { @@ -15,6 +16,8 @@ interface DayPlanSidebarToolbarProps { categories: Category[] assignments: AssignmentsMap reservations: Reservation[] + allConnectionsShown?: boolean + onToggleAllConnections?: () => void dayNotes: Record t: (key: string, params?: Record) => string locale: string @@ -37,6 +40,7 @@ interface DayPlanSidebarToolbarProps { export function DayPlanSidebarToolbar({ tripId, trip, days, places, categories, assignments, reservations, dayNotes, + allConnectionsShown = false, onToggleAllConnections, t, locale, toast, pdfHover, setPdfHover, setIcsHover, expandedDays, setExpandedDays, onUndo, canUndo, undoHover, setUndoHover, lastActionLabel, canEditDays, onReorderDays, onAddDay, @@ -295,6 +299,32 @@ export function DayPlanSidebarToolbar({ />
    )} + {onToggleAllConnections && reservations.some(isRoutableReservation) && (() => { + const label = t(allConnectionsShown ? 'map.hideAllConnections' : 'map.showAllConnections') + return ( + + + + ) + })()}
    ) diff --git a/client/src/components/Planner/PlaceInspector.test.tsx b/client/src/components/Planner/PlaceInspector.test.tsx index 38c0ae340..8cf77b48a 100644 --- a/client/src/components/Planner/PlaceInspector.test.tsx +++ b/client/src/components/Planner/PlaceInspector.test.tsx @@ -443,7 +443,24 @@ describe('PlaceInspector', () => { it('FE-PLANNER-INSPECTOR-032: price chip shown when place.price > 0', () => { const p = buildPlace({ id: 300, price: 15, currency: 'EUR' } as any); render(); - expect(screen.getByText(/15 EUR/)).toBeTruthy(); + // formatMoney renders in the currency's home convention (de-DE for EUR). + expect(screen.getByText(/15,00/)).toBeTruthy(); + }); + + it('FE-PLANNER-INSPECTOR-032b: price chip formats in the place currency with a neutral icon (#1561)', () => { + const p = buildPlace({ id: 300, price: 15, currency: 'USD' } as any); + render(); + expect(screen.getByText('$15.00')).toBeTruthy(); + // The chip icon must be currency-neutral, not the euro glyph. + expect(document.querySelector('.lucide-euro')).toBeNull(); + expect(document.querySelector('.lucide-banknote')).not.toBeNull(); + }); + + it('FE-PLANNER-INSPECTOR-032c: a currency-less price falls back to the trip currency (#1561)', () => { + seedStore(useTripStore, { trip: buildTrip({ id: 1, currency: 'NOK' }) } as any); + const p = buildPlace({ id: 300, price: 250, currency: null } as any); + render(); + expect(screen.getByText(/250,00\s?kr|kr\s?250,00/)).toBeTruthy(); }); // ── Phone number ─────────────────────────────────────────────────────────── diff --git a/client/src/components/Planner/PlaceInspector.tsx b/client/src/components/Planner/PlaceInspector.tsx index 35f6eccbf..b503688c6 100644 --- a/client/src/components/Planner/PlaceInspector.tsx +++ b/client/src/components/Planner/PlaceInspector.tsx @@ -4,7 +4,7 @@ import { openFile } from '../../utils/fileDownload' import Markdown from 'react-markdown' import remarkGfm from 'remark-gfm' import remarkBreaks from 'remark-breaks' -import { X, Clock, MapPin, ExternalLink, Phone, Euro, Edit2, Trash2, Plus, Minus, ChevronDown, ChevronUp, FileText, Upload, File, FileImage, Star, Navigation, Map as MapIcon, Users, Mountain, TrendingUp, Bookmark, BookmarkCheck, Copy } from 'lucide-react' +import { X, Clock, MapPin, ExternalLink, Phone, Banknote, Edit2, Trash2, Plus, Minus, ChevronDown, ChevronUp, FileText, Upload, File, FileImage, Star, Navigation, Map as MapIcon, Users, Mountain, TrendingUp, Bookmark, BookmarkCheck, Copy } from 'lucide-react' import PlaceAvatar from '../shared/PlaceAvatar' import GuestBadge from '../shared/GuestBadge' import StatusBadge from '../Collections/StatusBadge' @@ -20,7 +20,8 @@ import { usePluginStore } from '../../store/pluginStore' import PluginFrame from '../Plugins/PluginFrame' import type { Place, Category, Day, Assignment, Reservation, TripFile, AssignmentsMap } from '../../types' import type { CollectionStatus } from '@trek/shared' -import { splitReservationDateTime, formatTime } from '../../utils/formatters' +import { splitReservationDateTime, formatTime, formatMoney } from '../../utils/formatters' +import { useTripStore } from '../../store/tripStore' import { formatDistance, formatElevation } from '../../utils/units' import { getGoogleMapsUrlForPlace } from './placeGoogleMaps' import { getOpenStreetMapUrlForPlace } from './placeOpenStreetMap' @@ -160,6 +161,8 @@ export default function PlaceInspector({ return () => { cancelled = true } }, [placeIdForDetails]) const { t, locale, language } = useTranslation() + // Currency-less prices mean "the trip's currency"; null in collection mode (EUR fallback below). + const tripCurrency = useTripStore(s => s.trip?.currency) const toast = useToast() const timeFormat = useSettingsStore(s => s.settings.time_format) || '24h' const distanceUnit = useSettingsStore(s => s.settings.distance_unit) || 'metric' @@ -330,7 +333,7 @@ export default function PlaceInspector({ ) })()} {place.price > 0 && ( - } text={`${place.price} ${place.currency || '€'}`} color="#059669" bg="#ecfdf5" /> + } text={formatMoney(Number(place.price) || 0, place.currency || tripCurrency || 'EUR', locale)} color="#059669" bg="#ecfdf5" /> )}
    diff --git a/client/src/components/Planner/PlacesSidebar.test.tsx b/client/src/components/Planner/PlacesSidebar.test.tsx index 9c1089119..94bf45018 100644 --- a/client/src/components/Planner/PlacesSidebar.test.tsx +++ b/client/src/components/Planner/PlacesSidebar.test.tsx @@ -336,6 +336,39 @@ describe('Category filter dropdown', () => { await user.click(parkOpts[parkOpts.length - 1]); expect(screen.getByText(/2 categories/i)).toBeInTheDocument(); }); + + it('FE-PLANNER-SIDEBAR-047: category filter survives unmount/remount (#1541)', async () => { + const user = userEvent.setup(); + const cat = buildCategory({ name: 'Hotel', color: '#3b82f6' }); + const withCat = buildPlace({ name: 'Grand Palace', category_id: cat.id, address: 'Vienna' }); + const noCat = buildPlace({ name: 'Street Market', category_id: null, address: 'Lisbon' }); + const { unmount } = render(); + await user.click(screen.getByText(/All Categories/i)); + await user.click(screen.getByText('Hotel')); + expect(screen.queryByText('Street Market')).not.toBeInTheDocument(); + // Switching planner tabs unmounts the sidebar; the filter must come back + // both applied and visible instead of silently sticking on the map only. + unmount(); + render(); + expect(screen.queryByText(/All Categories/i)).not.toBeInTheDocument(); + expect(screen.getByText('Hotel')).toBeInTheDocument(); + expect(screen.getByText('Grand Palace')).toBeInTheDocument(); + expect(screen.queryByText('Street Market')).not.toBeInTheDocument(); + }); + + it('FE-PLANNER-SIDEBAR-048: filter tab survives unmount/remount (#1541)', async () => { + const user = userEvent.setup(); + const planned = buildPlace({ name: 'Planned Place' }); + const unplanned = buildPlace({ name: 'Unplanned Place' }); + const assignments = { '1': [buildAssignment({ place: planned, day_id: 1 })] }; + const { unmount } = render(); + await user.click(screen.getByRole('button', { name: /Unplanned/i })); + expect(screen.queryByText('Planned Place')).not.toBeInTheDocument(); + unmount(); + render(); + expect(screen.queryByText('Planned Place')).not.toBeInTheDocument(); + expect(screen.getByText('Unplanned Place')).toBeInTheDocument(); + }); }); // ── Place list interaction ───────────────────────────────────────────────────── @@ -572,4 +605,36 @@ describe('Google Maps list import', () => { ); }); }); + +}); + +// #1432: a tablet is a touch device at a desktop width. Before the fix, isTouch didn't +// exist and drag was gated on width alone, so on an iPad the rows stayed draggable and a +// scroll swipe started an HTML5 drag, which raised the drop-to-import overlay instead of +// scrolling. These cases pin the desktop-width + coarse-pointer combination. +describe('touch device at desktop width (#1432)', () => { + const touchProps = { ...defaultProps, isMobile: false, isTouch: true }; + + it('FE-PLANNER-SIDEBAR-044: place rows are not draggable', () => { + const place = buildPlace({ id: 7, name: 'Tablet Place' }); + render(); + const placeRow = screen.getByText('Tablet Place').closest('div[draggable]')!; + expect(placeRow.getAttribute('draggable')).toBe('false'); + }); + + it('FE-PLANNER-SIDEBAR-045: dragging over the sidebar does not raise the drop-to-import overlay', () => { + const place = buildPlace({ id: 7, name: 'Tablet Place' }); + const { container } = render(); + fireEvent.dragEnter(container.firstChild as HTMLElement); + expect(screen.queryByText('Drop to import')).not.toBeInTheDocument(); + }); + + it('FE-PLANNER-SIDEBAR-046: a mouse-driven desktop keeps drag and the drop-to-import overlay', () => { + const place = buildPlace({ id: 7, name: 'Desktop Place' }); + const { container } = render(); + const placeRow = screen.getByText('Desktop Place').closest('div[draggable]')!; + expect(placeRow.getAttribute('draggable')).toBe('true'); + fireEvent.dragEnter(container.firstChild as HTMLElement); + expect(screen.getByText('Drop to import')).toBeInTheDocument(); + }); }); diff --git a/client/src/components/Planner/PlacesSidebar.tsx b/client/src/components/Planner/PlacesSidebar.tsx index cefe35382..5cf637627 100644 --- a/client/src/components/Planner/PlacesSidebar.tsx +++ b/client/src/components/Planner/PlacesSidebar.tsx @@ -17,19 +17,20 @@ const PlacesSidebar = React.memo(function PlacesSidebar(props: PlacesSidebarProp sidebarDragOver, handleSidebarDragEnter, handleSidebarDragOver, handleSidebarDragLeave, handleSidebarDrop, selectMode, filtered, t, dayPickerPlace, listImportOpen, fileImportOpen, setFileImportOpen, sidebarDropFile, setSidebarDropFile, tripId, pushUndo, - ctxMenu, isMobile, pendingDeleteIds, setPendingDeleteIds, onBulkDeleteConfirm, + ctxMenu, isMobile, isTouch, pendingDeleteIds, setPendingDeleteIds, onBulkDeleteConfirm, categories, selectedIds, exitSelectMode, onBulkChangeCategory, categoryPickerOpen, setCategoryPickerOpen, collectionsEnabled, saveToListOpen, setSaveToListOpen, } = S + const dragDisabled = isMobile || isTouch return (
    - {!isMobile && sidebarDragOver && } + {!dragDisabled && sidebarDragOver && } {/* Kopfbereich */} diff --git a/client/src/components/Planner/PlacesSidebarHeader.tsx b/client/src/components/Planner/PlacesSidebarHeader.tsx index 693b0fbf1..e014d9877 100644 --- a/client/src/components/Planner/PlacesSidebarHeader.tsx +++ b/client/src/components/Planner/PlacesSidebarHeader.tsx @@ -23,8 +23,8 @@ export function PlacesHeader(S: SidebarState) { const { canEditPlaces, onAddPlace, t, setFileImportOpen, setListImportOpen, hasMultipleListImportProviders, places, categories, categoryFilters, search, setSearch, plannedIds, hasTracks, - filter, setFilter, onPlacesFilterChange, setSelectedIds, selectMode, setSelectMode, - catDropOpen, setCatDropOpen, toggleCategoryFilter, setCategoryFiltersLocal, onCategoryFilterChange, + filter, setFilter, setSelectedIds, selectMode, setSelectMode, + catDropOpen, setCatDropOpen, toggleCategoryFilter, setCategoryFilters, } = S return (
    @@ -99,7 +99,7 @@ export function PlacesHeader(S: SidebarState) { return (
    +

    The frame runs sandboxed at an opaque origin, exactly like TREK — trek.invoke() is proxied to your /api routes as the dev user.